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
1461a257adfa6ea3067806932e00592446310378
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/homotopy/cofiber.hlean
a005644ae99b7ae5947d435abc4bbec4ec30453d
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
3,650
hlean
/- Copyright (c) 2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer The Cofiber Type -/ import hit.pointed_pushout function .susp open eq pushout unit pointed is_trunc is_equiv susp unit definition cofiber {A B : Type} (f : A → B) := pushout (λ (a : A), ⋆) f namespace cofiber section parameters {A B : Type} (f : A → B) protected definition base [constructor] : cofiber f := inl ⋆ protected definition cod [constructor] : B → cofiber f := inr protected definition contr_of_equiv [H : is_equiv f] : is_contr (cofiber f) := begin fapply is_contr.mk, exact base, intro a, induction a with [u, b], { cases u, reflexivity }, { exact !glue ⬝ ap inr (right_inv f b) }, { apply eq_pathover, refine _ ⬝hp !ap_id⁻¹, refine !ap_constant ⬝ph _, apply move_bot_of_left, refine !idp_con ⬝ph _, apply transpose, esimp, refine _ ⬝hp (ap (ap inr) !adj⁻¹), refine _ ⬝hp !ap_compose, apply square_Flr_idp_ap }, end protected definition rec {A : Type} {B : Type} {f : A → B} {P : cofiber f → Type} (Pinl : P (inl ⋆)) (Pinr : Π (x : B), P (inr x)) (Pglue : Π (x : A), pathover P Pinl (glue x) (Pinr (f x))) : (Π y, P y) := begin intro y, induction y, induction x, exact Pinl, exact Pinr x, esimp, exact Pglue x, end protected definition rec_on {A : Type} {B : Type} {f : A → B} {P : cofiber f → Type} (y : cofiber f) (Pinl : P (inl ⋆)) (Pinr : Π (x : B), P (inr x)) (Pglue : Π (x : A), pathover P Pinl (glue x) (Pinr (f x))) : P y := begin induction y, induction x, exact Pinl, exact Pinr x, esimp, exact Pglue x, end end end cofiber -- Pointed version definition Cofiber {A B : Type*} (f : A →* B) : Type* := Pushout (pconst A Unit) f namespace cofiber protected definition prec {A B : Type*} {f : A →* B} {P : Cofiber f → Type} (Pinl : P (inl ⋆)) (Pinr : Π (x : B), P (inr x)) (Pglue : Π (x : A), pathover P Pinl (pglue x) (Pinr (f x))) : (Π (y : Cofiber f), P y) := begin intro y, induction y, induction x, exact Pinl, exact Pinr x, esimp, exact Pglue x end protected definition prec_on {A B : Type*} {f : A →* B} {P : Cofiber f → Type} (y : Cofiber f) (Pinl : P (inl ⋆)) (Pinr : Π (x : B), P (inr x)) (Pglue : Π (x : A), pathover P Pinl (pglue x) (Pinr (f x))) : P y := begin induction y, induction x, exact Pinl, exact Pinr x, esimp, exact Pglue x end protected definition pelim_on {A B C : Type*} {f : A →* B} (y : Cofiber f) (c : C) (g : B → C) (p : Π x, c = g (f x)) : C := begin fapply pushout.elim_on y, exact (λ x, c), exact g, exact p end --TODO more pointed recursors variables (A : Type*) definition cofiber_unit : Cofiber (pconst A Unit) ≃* Susp A := begin fconstructor, { fconstructor, intro x, induction x, exact north, exact south, exact merid x, reflexivity }, { esimp, fapply adjointify, intro s, induction s, exact inl ⋆, exact inr ⋆, apply glue a, intro s, induction s, do 2 reflexivity, esimp, apply eq_pathover, refine _ ⬝hp !ap_id⁻¹, apply hdeg_square, refine !(ap_compose (pushout.elim _ _ _)) ⬝ _, refine ap _ !elim_merid ⬝ _, apply elim_glue, intro c, induction c with [n, s], induction n, reflexivity, induction s, reflexivity, esimp, apply eq_pathover, apply hdeg_square, refine _ ⬝ !ap_id⁻¹, refine !(ap_compose (pushout.elim _ _ _)) ⬝ _, refine ap _ !elim_glue ⬝ _, apply elim_merid }, end end cofiber
96c41981a9768eea490063245f140e6eb36497d8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/data/stream_auto.lean
e4e6c3f8b5aeaf2b0be000af56756bb5fea4f924
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
19,557
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default universes u v w namespace Mathlib def stream (α : Type u) := ℕ → α namespace stream def cons {α : Type u} (a : α) (s : stream α) : stream α := fun (i : ℕ) => sorry infixr:67 " :: " => Mathlib.stream.cons def head {α : Type u} (s : stream α) : α := s 0 def tail {α : Type u} (s : stream α) : stream α := fun (i : ℕ) => s (i + 1) def drop {α : Type u} (n : ℕ) (s : stream α) : stream α := fun (i : ℕ) => s (i + n) def nth {α : Type u} (n : ℕ) (s : stream α) : α := s n protected theorem eta {α : Type u} (s : stream α) : head s :: tail s = s := funext fun (i : ℕ) => nat.cases_on i (Eq.refl (cons (head s) (tail s) 0)) fun (i : ℕ) => Eq.refl (cons (head s) (tail s) (Nat.succ i)) theorem nth_zero_cons {α : Type u} (a : α) (s : stream α) : nth 0 (a :: s) = a := rfl theorem head_cons {α : Type u} (a : α) (s : stream α) : head (a :: s) = a := rfl theorem tail_cons {α : Type u} (a : α) (s : stream α) : tail (a :: s) = s := rfl theorem tail_drop {α : Type u} (n : ℕ) (s : stream α) : tail (drop n s) = drop n (tail s) := sorry theorem nth_drop {α : Type u} (n : ℕ) (m : ℕ) (s : stream α) : nth n (drop m s) = nth (n + m) s := rfl theorem tail_eq_drop {α : Type u} (s : stream α) : tail s = drop 1 s := rfl theorem drop_drop {α : Type u} (n : ℕ) (m : ℕ) (s : stream α) : drop n (drop m s) = drop (n + m) s := sorry theorem nth_succ {α : Type u} (n : ℕ) (s : stream α) : nth (Nat.succ n) s = nth n (tail s) := rfl theorem drop_succ {α : Type u} (n : ℕ) (s : stream α) : drop (Nat.succ n) s = drop n (tail s) := rfl protected theorem ext {α : Type u} {s₁ : stream α} {s₂ : stream α} : (∀ (n : ℕ), nth n s₁ = nth n s₂) → s₁ = s₂ := fun (h : ∀ (n : ℕ), nth n s₁ = nth n s₂) => funext h def all {α : Type u} (p : α → Prop) (s : stream α) := ∀ (n : ℕ), p (nth n s) def any {α : Type u} (p : α → Prop) (s : stream α) := ∃ (n : ℕ), p (nth n s) theorem all_def {α : Type u} (p : α → Prop) (s : stream α) : all p s = ∀ (n : ℕ), p (nth n s) := rfl theorem any_def {α : Type u} (p : α → Prop) (s : stream α) : any p s = ∃ (n : ℕ), p (nth n s) := rfl protected def mem {α : Type u} (a : α) (s : stream α) := any (fun (b : α) => a = b) s protected instance has_mem {α : Type u} : has_mem α (stream α) := has_mem.mk stream.mem theorem mem_cons {α : Type u} (a : α) (s : stream α) : a ∈ a :: s := exists.intro 0 rfl theorem mem_cons_of_mem {α : Type u} {a : α} {s : stream α} (b : α) : a ∈ s → a ∈ b :: s := sorry theorem eq_or_mem_of_mem_cons {α : Type u} {a : α} {b : α} {s : stream α} : a ∈ b :: s → a = b ∨ a ∈ s := sorry theorem mem_of_nth_eq {α : Type u} {n : ℕ} {s : stream α} {a : α} : a = nth n s → a ∈ s := fun (h : a = nth n s) => exists.intro n h def map {α : Type u} {β : Type v} (f : α → β) (s : stream α) : stream β := fun (n : ℕ) => f (nth n s) theorem drop_map {α : Type u} {β : Type v} (f : α → β) (n : ℕ) (s : stream α) : drop n (map f s) = map f (drop n s) := stream.ext fun (i : ℕ) => rfl theorem nth_map {α : Type u} {β : Type v} (f : α → β) (n : ℕ) (s : stream α) : nth n (map f s) = f (nth n s) := rfl theorem tail_map {α : Type u} {β : Type v} (f : α → β) (s : stream α) : tail (map f s) = map f (tail s) := eq.mpr (id (Eq._oldrec (Eq.refl (tail (map f s) = map f (tail s))) (tail_eq_drop (map f s)))) (Eq.refl (drop 1 (map f s))) theorem head_map {α : Type u} {β : Type v} (f : α → β) (s : stream α) : head (map f s) = f (head s) := rfl theorem map_eq {α : Type u} {β : Type v} (f : α → β) (s : stream α) : map f s = f (head s) :: map f (tail s) := sorry theorem map_cons {α : Type u} {β : Type v} (f : α → β) (a : α) (s : stream α) : map f (a :: s) = f a :: map f s := sorry theorem map_id {α : Type u} (s : stream α) : map id s = s := rfl theorem map_map {α : Type u} {β : Type v} {δ : Type w} (g : β → δ) (f : α → β) (s : stream α) : map g (map f s) = map (g ∘ f) s := rfl theorem map_tail {α : Type u} {β : Type v} (f : α → β) (s : stream α) : map f (tail s) = tail (map f s) := rfl theorem mem_map {α : Type u} {β : Type v} (f : α → β) {a : α} {s : stream α} : a ∈ s → f a ∈ map f s := sorry theorem exists_of_mem_map {α : Type u} {β : Type v} {f : α → β} {b : β} {s : stream α} : b ∈ map f s → ∃ (a : α), a ∈ s ∧ f a = b := sorry def zip {α : Type u} {β : Type v} {δ : Type w} (f : α → β → δ) (s₁ : stream α) (s₂ : stream β) : stream δ := fun (n : ℕ) => f (nth n s₁) (nth n s₂) theorem drop_zip {α : Type u} {β : Type v} {δ : Type w} (f : α → β → δ) (n : ℕ) (s₁ : stream α) (s₂ : stream β) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) := stream.ext fun (i : ℕ) => rfl theorem nth_zip {α : Type u} {β : Type v} {δ : Type w} (f : α → β → δ) (n : ℕ) (s₁ : stream α) (s₂ : stream β) : nth n (zip f s₁ s₂) = f (nth n s₁) (nth n s₂) := rfl theorem head_zip {α : Type u} {β : Type v} {δ : Type w} (f : α → β → δ) (s₁ : stream α) (s₂ : stream β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl theorem tail_zip {α : Type u} {β : Type v} {δ : Type w} (f : α → β → δ) (s₁ : stream α) (s₂ : stream β) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl theorem zip_eq {α : Type u} {β : Type v} {δ : Type w} (f : α → β → δ) (s₁ : stream α) (s₂ : stream β) : zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) := sorry def const {α : Type u} (a : α) : stream α := fun (n : ℕ) => a theorem mem_const {α : Type u} (a : α) : a ∈ const a := exists.intro 0 rfl theorem const_eq {α : Type u} (a : α) : const a = a :: const a := stream.ext fun (n : ℕ) => nat.cases_on n (Eq.refl (nth 0 (const a))) fun (n : ℕ) => Eq.refl (nth (Nat.succ n) (const a)) theorem tail_const {α : Type u} (a : α) : tail (const a) = const a := (fun (this : tail (a :: const a) = const a) => eq.mp (Eq._oldrec (Eq.refl (tail (a :: const a) = const a)) (Eq.symm (const_eq a))) this) rfl theorem map_const {α : Type u} {β : Type v} (f : α → β) (a : α) : map f (const a) = const (f a) := rfl theorem nth_const {α : Type u} (n : ℕ) (a : α) : nth n (const a) = a := rfl theorem drop_const {α : Type u} (n : ℕ) (a : α) : drop n (const a) = const a := stream.ext fun (i : ℕ) => rfl def iterate {α : Type u} (f : α → α) (a : α) : stream α := fun (n : ℕ) => nat.rec_on n a fun (n : ℕ) (r : α) => f r theorem head_iterate {α : Type u} (f : α → α) (a : α) : head (iterate f a) = a := rfl theorem tail_iterate {α : Type u} (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) := sorry theorem iterate_eq {α : Type u} (f : α → α) (a : α) : iterate f a = a :: iterate f (f a) := sorry theorem nth_zero_iterate {α : Type u} (f : α → α) (a : α) : nth 0 (iterate f a) = a := rfl theorem nth_succ_iterate {α : Type u} (n : ℕ) (f : α → α) (a : α) : nth (Nat.succ n) (iterate f a) = nth n (iterate f (f a)) := eq.mpr (id (Eq._oldrec (Eq.refl (nth (Nat.succ n) (iterate f a) = nth n (iterate f (f a)))) (nth_succ n (iterate f a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (nth n (tail (iterate f a)) = nth n (iterate f (f a)))) (tail_iterate f a))) (Eq.refl (nth n (iterate f (f a))))) def is_bisimulation {α : Type u} (R : stream α → stream α → Prop) := ∀ {s₁ s₂ : stream α}, R s₁ s₂ → head s₁ = head s₂ ∧ R (tail s₁) (tail s₂) theorem nth_of_bisim {α : Type u} (R : stream α → stream α → Prop) (bisim : is_bisimulation R) {s₁ : stream α} {s₂ : stream α} (n : ℕ) : R s₁ s₂ → nth n s₁ = nth n s₂ ∧ R (drop (n + 1) s₁) (drop (n + 1) s₂) := sorry theorem eq_of_bisim {α : Type u} (R : stream α → stream α → Prop) (bisim : is_bisimulation R) {s₁ : stream α} {s₂ : stream α} : R s₁ s₂ → s₁ = s₂ := fun (r : R s₁ s₂) => stream.ext fun (n : ℕ) => and.elim_left (nth_of_bisim R bisim n r) theorem bisim_simple {α : Type u} (s₁ : stream α) (s₂ : stream α) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ := sorry theorem coinduction {α : Type u} {s₁ : stream α} {s₂ : stream α} : head s₁ = head s₂ → (∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ := sorry theorem iterate_id {α : Type u} (a : α) : iterate id a = const a := sorry theorem map_iterate {α : Type u} (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) := sorry def corec {α : Type u} {β : Type v} (f : α → β) (g : α → α) : α → stream β := fun (a : α) => map f (iterate g a) def corec_on {α : Type u} {β : Type v} (a : α) (f : α → β) (g : α → α) : stream β := corec f g a theorem corec_def {α : Type u} {β : Type v} (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) := rfl theorem corec_eq {α : Type u} {β : Type v} (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) := sorry theorem corec_id_id_eq_const {α : Type u} (a : α) : corec id id a = const a := eq.mpr (id (Eq._oldrec (Eq.refl (corec id id a = const a)) (corec_def id id a))) (eq.mpr (id (Eq._oldrec (Eq.refl (map id (iterate id a) = const a)) (map_id (iterate id a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (iterate id a = const a)) (iterate_id a))) (Eq.refl (const a)))) theorem corec_id_f_eq_iterate {α : Type u} (f : α → α) (a : α) : corec id f a = iterate f a := rfl def corec' {α : Type u} {β : Type v} (f : α → β × α) : α → stream β := corec (prod.fst ∘ f) (prod.snd ∘ f) theorem corec'_eq {α : Type u} {β : Type v} (f : α → β × α) (a : α) : corec' f a = prod.fst (f a) :: corec' f (prod.snd (f a)) := corec_eq (prod.fst ∘ f) (prod.snd ∘ f) a -- corec is also known as unfold def unfolds {α : Type u} {β : Type v} (g : α → β) (f : α → α) (a : α) : stream β := corec g f a theorem unfolds_eq {α : Type u} {β : Type v} (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) := sorry theorem nth_unfolds_head_tail {α : Type u} (n : ℕ) (s : stream α) : nth n (unfolds head tail s) = nth n s := sorry theorem unfolds_head_eq {α : Type u} (s : stream α) : unfolds head tail s = s := stream.ext fun (n : ℕ) => nth_unfolds_head_tail n s def interleave {α : Type u} (s₁ : stream α) (s₂ : stream α) : stream α := corec_on (s₁, s₂) (fun (_x : stream α × stream α) => sorry) fun (_x : stream α × stream α) => sorry infixl:65 "⋈" => Mathlib.stream.interleave theorem interleave_eq {α : Type u} (s₁ : stream α) (s₂ : stream α) : s₁⋈s₂ = head s₁ :: head s₂ :: (tail s₁⋈tail s₂) := sorry theorem tail_interleave {α : Type u} (s₁ : stream α) (s₂ : stream α) : tail (s₁⋈s₂) = s₂⋈tail s₁ := sorry theorem interleave_tail_tail {α : Type u} (s₁ : stream α) (s₂ : stream α) : tail s₁⋈tail s₂ = tail (tail (s₁⋈s₂)) := eq.mpr (id (Eq._oldrec (Eq.refl (tail s₁⋈tail s₂ = tail (tail (s₁⋈s₂)))) (interleave_eq s₁ s₂))) (Eq.refl (tail s₁⋈tail s₂)) theorem nth_interleave_left {α : Type u} (n : ℕ) (s₁ : stream α) (s₂ : stream α) : nth (bit0 1 * n) (s₁⋈s₂) = nth n s₁ := sorry theorem nth_interleave_right {α : Type u} (n : ℕ) (s₁ : stream α) (s₂ : stream α) : nth (bit0 1 * n + 1) (s₁⋈s₂) = nth n s₂ := sorry theorem mem_interleave_left {α : Type u} {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₁ → a ∈ s₁⋈s₂ := sorry theorem mem_interleave_right {α : Type u} {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₂ → a ∈ s₁⋈s₂ := sorry def even {α : Type u} (s : stream α) : stream α := corec (fun (s : stream α) => head s) (fun (s : stream α) => tail (tail s)) s def odd {α : Type u} (s : stream α) : stream α := even (tail s) theorem odd_eq {α : Type u} (s : stream α) : odd s = even (tail s) := rfl theorem head_even {α : Type u} (s : stream α) : head (even s) = head s := rfl theorem tail_even {α : Type u} (s : stream α) : tail (even s) = even (tail (tail s)) := sorry theorem even_cons_cons {α : Type u} (a₁ : α) (a₂ : α) (s : stream α) : even (a₁ :: a₂ :: s) = a₁ :: even s := sorry theorem even_tail {α : Type u} (s : stream α) : even (tail s) = odd s := rfl theorem even_interleave {α : Type u} (s₁ : stream α) (s₂ : stream α) : even (s₁⋈s₂) = s₁ := sorry theorem interleave_even_odd {α : Type u} (s₁ : stream α) : even s₁⋈odd s₁ = s₁ := sorry theorem nth_even {α : Type u} (n : ℕ) (s : stream α) : nth n (even s) = nth (bit0 1 * n) s := sorry theorem nth_odd {α : Type u} (n : ℕ) (s : stream α) : nth n (odd s) = nth (bit0 1 * n + 1) s := eq.mpr (id (Eq._oldrec (Eq.refl (nth n (odd s) = nth (bit0 1 * n + 1) s)) (odd_eq s))) (eq.mpr (id (Eq._oldrec (Eq.refl (nth n (even (tail s)) = nth (bit0 1 * n + 1) s)) (nth_even n (tail s)))) (Eq.refl (nth (bit0 1 * n) (tail s)))) theorem mem_of_mem_even {α : Type u} (a : α) (s : stream α) : a ∈ even s → a ∈ s := sorry theorem mem_of_mem_odd {α : Type u} (a : α) (s : stream α) : a ∈ odd s → a ∈ s := sorry def append_stream {α : Type u} : List α → stream α → stream α := sorry theorem nil_append_stream {α : Type u} (s : stream α) : append_stream [] s = s := rfl theorem cons_append_stream {α : Type u} (a : α) (l : List α) (s : stream α) : append_stream (a :: l) s = a :: append_stream l s := rfl infixl:65 "++ₛ" => Mathlib.stream.append_stream theorem append_append_stream {α : Type u} (l₁ : List α) (l₂ : List α) (s : stream α) : l₁ ++ l₂++ₛs = l₁++ₛ(l₂++ₛs) := sorry theorem map_append_stream {α : Type u} {β : Type v} (f : α → β) (l : List α) (s : stream α) : map f (l++ₛs) = list.map f l++ₛmap f s := sorry theorem drop_append_stream {α : Type u} (l : List α) (s : stream α) : drop (list.length l) (l++ₛs) = s := sorry theorem append_stream_head_tail {α : Type u} (s : stream α) : [head s]++ₛtail s = s := eq.mpr (id (Eq._oldrec (Eq.refl ([head s]++ₛtail s = s)) (cons_append_stream (head s) [] (tail s)))) (eq.mpr (id (Eq._oldrec (Eq.refl (head s :: ([]++ₛtail s) = s)) (nil_append_stream (tail s)))) (eq.mpr (id (Eq._oldrec (Eq.refl (head s :: tail s = s)) (stream.eta s))) (Eq.refl s))) theorem mem_append_stream_right {α : Type u} {a : α} (l : List α) {s : stream α} : a ∈ s → a ∈ l++ₛs := sorry theorem mem_append_stream_left {α : Type u} {a : α} {l : List α} (s : stream α) : a ∈ l → a ∈ l++ₛs := sorry def approx {α : Type u} : ℕ → stream α → List α := sorry theorem approx_zero {α : Type u} (s : stream α) : approx 0 s = [] := rfl theorem approx_succ {α : Type u} (n : ℕ) (s : stream α) : approx (Nat.succ n) s = head s :: approx n (tail s) := rfl theorem nth_approx {α : Type u} (n : ℕ) (s : stream α) : list.nth (approx (Nat.succ n) s) n = some (nth n s) := sorry theorem append_approx_drop {α : Type u} (n : ℕ) (s : stream α) : approx n s++ₛdrop n s = s := sorry -- Take theorem reduces a proof of equality of infinite streams to an -- induction over all their finite approximations. theorem take_theorem {α : Type u} (s₁ : stream α) (s₂ : stream α) : (∀ (n : ℕ), approx n s₁ = approx n s₂) → s₁ = s₂ := sorry -- auxiliary def for cycle corecursive def -- auxiliary def for cycle corecursive def def cycle {α : Type u} (l : List α) : l ≠ [] → stream α := sorry theorem cycle_eq {α : Type u} (l : List α) (h : l ≠ []) : cycle l h = l++ₛcycle l h := sorry theorem mem_cycle {α : Type u} {a : α} {l : List α} (h : l ≠ []) : a ∈ l → a ∈ cycle l h := fun (ainl : a ∈ l) => eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ cycle l h)) (cycle_eq l h))) (mem_append_stream_left (cycle l h) ainl) theorem cycle_singleton {α : Type u} (a : α) (h : [a] ≠ []) : cycle [a] h = const a := sorry def tails {α : Type u} (s : stream α) : stream (stream α) := corec id tail (tail s) theorem tails_eq {α : Type u} (s : stream α) : tails s = tail s :: tails (tail s) := sorry theorem nth_tails {α : Type u} (n : ℕ) (s : stream α) : nth n (tails s) = drop n (tail s) := sorry theorem tails_eq_iterate {α : Type u} (s : stream α) : tails s = iterate tail (tail s) := rfl def inits_core {α : Type u} (l : List α) (s : stream α) : stream (List α) := corec_on (l, s) (fun (_x : List α × stream α) => sorry) fun (p : List α × stream α) => sorry def inits {α : Type u} (s : stream α) : stream (List α) := inits_core [head s] (tail s) theorem inits_core_eq {α : Type u} (l : List α) (s : stream α) : inits_core l s = l :: inits_core (l ++ [head s]) (tail s) := sorry theorem tail_inits {α : Type u} (s : stream α) : tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) := sorry theorem inits_tail {α : Type u} (s : stream α) : inits (tail s) = inits_core [head (tail s)] (tail (tail s)) := rfl theorem cons_nth_inits_core {α : Type u} (a : α) (n : ℕ) (l : List α) (s : stream α) : a :: nth n (inits_core l s) = nth n (inits_core (a :: l) s) := sorry theorem nth_inits {α : Type u} (n : ℕ) (s : stream α) : nth n (inits s) = approx (Nat.succ n) s := sorry theorem inits_eq {α : Type u} (s : stream α) : inits s = [head s] :: map (List.cons (head s)) (inits (tail s)) := sorry theorem zip_inits_tails {α : Type u} (s : stream α) : zip append_stream (inits s) (tails s) = const s := sorry def pure {α : Type u} (a : α) : stream α := const a def apply {α : Type u} {β : Type v} (f : stream (α → β)) (s : stream α) : stream β := fun (n : ℕ) => nth n f (nth n s) infixl:75 "⊛" => Mathlib.stream.apply theorem identity {α : Type u} (s : stream α) : pure id⊛s = s := rfl theorem composition {α : Type u} {β : Type v} {δ : Type w} (g : stream (β → δ)) (f : stream (α → β)) (s : stream α) : pure function.comp⊛g⊛f⊛s = g⊛(f⊛s) := rfl theorem homomorphism {α : Type u} {β : Type v} (f : α → β) (a : α) : pure f⊛pure a = pure (f a) := rfl theorem interchange {α : Type u} {β : Type v} (fs : stream (α → β)) (a : α) : fs⊛pure a = (pure fun (f : α → β) => f a)⊛fs := rfl theorem map_eq_apply {α : Type u} {β : Type v} (f : α → β) (s : stream α) : map f s = pure f⊛s := rfl def nats : stream ℕ := fun (n : ℕ) => n theorem nth_nats (n : ℕ) : nth n nats = n := rfl theorem nats_eq : nats = 0 :: map Nat.succ nats := sorry end Mathlib
0a1a69e37fac0da8453d43846b4344ea884df241
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/power_series/basic.lean
78e1c3e211180c70d1954846eb15526ab7fdf6b7
[ "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
76,705
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.finsupp.interval import data.mv_polynomial.basic import data.polynomial.algebra_map import data.polynomial.coeff import linear_algebra.std_basis import ring_theory.ideal.local_ring import ring_theory.multiplicity import tactic.linarith /-! # Formal power series > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m < n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical big_operators polynomial /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R namespace mv_power_series open finsupp variables {σ R : Type*} instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default⟩ instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (mv_power_series σ A) := pi.module _ _ _ instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_smul R S] [is_scalar_tower R S A] : is_scalar_tower R S (mv_power_series σ A) := pi.is_scalar_tower section semiring variables (R) [semiring R] /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R := linear_map.std_basis R _ n /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n variables {R} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ R} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) := function.funext_iff lemma monomial_def [decidable_eq σ] (n : σ →₀ ℕ) : monomial R n = linear_map.std_basis R _ n := by convert rfl -- unify the `decidable` arguments lemma coeff_monomial [decidable_eq σ] (m n : σ →₀ ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := by rw [coeff, monomial_def, linear_map.proj_apply, linear_map.std_basis_apply, function.update_apply, pi.zero_apply] @[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) : coeff R n (monomial R n a) = a := linear_map.std_basis_same R _ n a lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) : coeff R m (monomial R n a) = 0 := linear_map.std_basis_ne R _ _ _ h a lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) : m = n := by_contra $ λ h', h $ coeff_monomial_ne h' a @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R) instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩ lemma coeff_one [decidable_eq σ] : coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 := coeff_monomial _ _ _ lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial_same 0 1 lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl instance : add_monoid_with_one (mv_power_series σ R) := { nat_cast := λ n, monomial R 0 n, nat_cast_zero := by simp [nat.cast], nat_cast_succ := by simp [nat.cast, monomial_zero_one], one := 1, .. mv_power_series.add_monoid } instance : has_mul (mv_power_series σ R) := ⟨λ φ ψ n, ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ⟩ lemma coeff_mul : coeff R n (φ * ψ) = ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := rfl protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] lemma coeff_monomial_mul (a : R) : coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_fst_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_mul_monomial (a : R) : coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_snd_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_add_monomial_mul (a : R) : coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ := begin rw [coeff_monomial_mul, if_pos, add_tsub_cancel_left], exact le_add_right le_rfl end lemma coeff_add_mul_monomial (a : R) : coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a := begin rw [coeff_mul_monomial, if_pos, add_tsub_cancel_right], exact le_add_left le_rfl end @[simp] lemma commute_monomial {a : R} {n} : commute φ (monomial R n a) ↔ ∀ m, commute (coeff R m φ) a := begin refine ext_iff.trans ⟨λ h m, _, λ h m, _⟩, { have := h (m + n), rwa [coeff_add_mul_monomial, add_comm, coeff_add_monomial_mul] at this }, { rw [coeff_mul_monomial, coeff_monomial_mul], split_ifs; [apply h, refl] } end protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ := ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1 protected lemma mul_one : φ * 1 = φ := ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1 protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := begin ext1 n, simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'], refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _; simp only [mem_antidiagonal, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp, exists_prop], { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl, simp [add_assoc] }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl, apply mul_assoc }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl, refl }, { rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl, refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] } end instance : semiring (mv_power_series σ R) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.add_monoid_with_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring R] : comm_semiring (mv_power_series σ R) := { mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm] using sum_antidiagonal_swap n (λ a b, coeff R a φ * coeff R b ψ), .. mv_power_series.semiring } instance [ring R] : ring (mv_power_series σ R) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring R] : comm_ring (mv_power_series σ R) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring R] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) : monomial R m a * monomial R n b = monomial R (m + n) (a * b) := begin ext k, simp only [coeff_mul_monomial, coeff_monomial], split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl }, { rw [← h₂, tsub_add_cancel_of_le h₁] at h₃, exact (h₃ rfl).elim }, { rw [h₃, add_tsub_cancel_right] at h₂, exact (h₂ rfl).elim }, { exact zero_mul b }, { rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim } end variables (σ) (R) /-- The constant multivariate formal power series.-/ def C : R →+* mv_power_series σ R := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, map_zero' := (monomial R (0 : _)).map_zero, .. monomial R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl lemma coeff_C [decidable_eq σ] (n : σ →₀ ℕ) (a : R) : coeff R n (C σ R a) = if n = 0 then a else 0 := coeff_monomial _ _ _ lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a := coeff_monomial_same 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1 lemma coeff_X [decidable_eq σ] (n : σ →₀ ℕ) (s : σ) : coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 := coeff_monomial _ _ _ lemma coeff_index_single_X [decidable_eq σ] (s t : σ) : coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 := by simp only [coeff_X, single_left_inj one_ne_zero] @[simp] lemma coeff_index_single_self_X (s : σ) : coeff R (single s 1) (X s : mv_power_series σ R) = 1 := coeff_monomial_same _ _ lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma commute_X (φ : mv_power_series σ R) (s : σ) : commute φ (X s) := φ.commute_monomial.mpr $ λ m, commute.one_right _ lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ R)^n = monomial R (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero, monomial_zero_one] }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow [decidable_eq σ] (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (φ * C σ R a) = coeff R n φ * a := by simpa using coeff_add_mul_monomial n 0 φ a @[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (C σ R a * φ) = a * coeff R n φ := by simpa using coeff_add_monomial_mul 0 n φ a lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_mul_monomial, if_neg this] end lemma coeff_zero_X_mul (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (X s * φ) = 0 := by rw [← (φ.commute_X s).eq, coeff_zero_mul_X] variables (σ) (R) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ R) →+* R := { to_fun := coeff R (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], map_zero' := linear_map.map_zero _, .. coeff R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) : coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl @[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (constant_coeff σ R φ) := h.map _ @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := rfl lemma smul_eq_C_mul (f : mv_power_series σ R) (a : R) : a • f = C σ R a * f := by { ext, simp } lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end semiring section map variables {S T : Type*} [semiring R] [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ R →+* mv_power_series σ S := { to_fun := λ φ n, f $ coeff R n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, f.map_sum, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coeff S n (map σ f φ) = f (coeff R n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ R) : constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl @[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) : map σ f (monomial R n a) = monomial S n (f a) := by { ext m, simp [coeff_monomial, apply_ite f] } @[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) := map_monomial _ _ _ @[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [mv_power_series.X] end map section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R (mv_power_series σ A) := { commutes' := λ a φ, by { ext n, simp [algebra.commutes] }, smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] }, to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R), .. mv_power_series.module } theorem C_eq_algebra_map : C σ R = (algebra_map R (mv_power_series σ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (mv_power_series σ A) r = C σ A (algebra_map R A r) := begin change (mv_power_series.map σ (algebra_map R A)).comp (C σ R) r = _, simp, end instance [nonempty σ] [nontrivial R] : nontrivial (subalgebra R (mv_power_series σ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], inhabit σ, refine ⟨X default, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, not_forall], refine ⟨finsupp.single default 1, _⟩, simp [algebra_map_apply, coeff_C], end⟩⟩ end algebra section trunc variables [comm_semiring R] (n : σ →₀ ℕ) /-- Auxiliary definition for the truncation function. -/ def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R := ∑ m in finset.Iio n, mv_polynomial.monomial m (coeff R m φ) lemma coeff_trunc_fun (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc_fun n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc_fun, mv_polynomial.coeff_sum] variable (R) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ R →+ mv_polynomial σ R := { to_fun := trunc_fun n, map_zero' := by { ext, simp [coeff_trunc_fun] }, map_add' := by { intros, ext, simp [coeff_trunc_fun, ite_add], split_ifs; refl } } variable {R} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc R n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc, coeff_trunc_fun] @[simp] lemma trunc_one (hnn : n ≠ 0) : trunc R n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, simp }, { symmetry, rw mv_polynomial.coeff_one, exact if_neg (ne.symm H'), }, { symmetry, rw mv_polynomial.coeff_one, refine if_neg _, rintro rfl, apply H, exact ne.bot_lt hnn, } end @[simp] lemma trunc_C (hnn : n ≠ 0) (a : R) : trunc R n (C σ R a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, exact ne.bot_lt hnn, end end trunc section semiring variable [semiring R] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [add_tsub_cancel_left, finsupp.add_apply, finsupp.tsub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, rw [coe_add, coe_add, pi.add_apply, pi.add_apply, add_tsub_cancel_left, add_comm], }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using tsub_add_cancel_of_le H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end semiring section ring variables [ring R] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R | n := if n = 0 then a else - a * ∑ x in n.antidiagonal, if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0 using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux [decidable_eq σ] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := show inv.aux a φ n = _, begin rw inv.aux, convert rfl -- unify `decidable` instances end /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : Rˣ) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) : constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) (h : constant_coeff σ R φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal, { rw [finsupp.mem_antidiagonal, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul, mul_neg, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_rfl), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring R] /-- Multivariate formal power series over a local ring form a local ring. -/ instance [local_ring R] : local_ring (mv_power_series σ R) := local_ring.of_is_unit_or_is_unit_one_sub_self $ by { intro φ, rcases local_ring.is_unit_or_is_unit_one_sub_self (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ S) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) ψ.is_unit, rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ end local_ring section field variables {k : Type*} [field k] /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv (φ : mv_power_series σ k) : mv_power_series σ k := inv.aux (constant_coeff σ k φ)⁻¹ φ instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩ lemma coeff_inv [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else - (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) : constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ k) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp] lemma zero_inv : (0 : mv_power_series σ k)⁻¹ = 0 := by rw [inv_eq_zero, constant_coeff_zero] @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv_cancel (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul_cancel (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv_cancel h] protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k} (h : constant_coeff σ k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := ⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul_cancel _ h], λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv_cancel _ h]⟩ protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul] protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h] @[simp] protected lemma mul_inv_rev (φ ψ : mv_power_series σ k) : (φ * ψ)⁻¹ = ψ⁻¹ * φ⁻¹ := begin by_cases h : constant_coeff σ k (φ * ψ) = 0, { rw inv_eq_zero.mpr h, simp only [map_mul, mul_eq_zero] at h, -- we don't have `no_zero_divisors (mw_power_series σ k)` yet, cases h; simp [inv_eq_zero.mpr h] }, { rw [mv_power_series.inv_eq_iff_mul_eq_one h], simp only [not_or_distrib, map_mul, mul_eq_zero] at h, rw [←mul_assoc, mul_assoc _⁻¹, mv_power_series.inv_mul_cancel _ h.left, mul_one, mv_power_series.inv_mul_cancel _ h.right] } end instance : inv_one_class (mv_power_series σ k) := { inv_one := by { rw [mv_power_series.inv_eq_iff_mul_eq_one, mul_one], simp }, ..mv_power_series.has_one, ..mv_power_series.has_inv } @[simp] lemma C_inv (r : k) : (C σ k r)⁻¹ = C σ k r⁻¹ := begin rcases eq_or_ne r 0 with rfl|hr, { simp }, rw [mv_power_series.inv_eq_iff_mul_eq_one, ←map_mul, inv_mul_cancel hr, map_one], simpa using hr end @[simp] lemma X_inv (s : σ) : (X s : mv_power_series σ k)⁻¹ = 0 := by rw [inv_eq_zero, constant_coeff_X] @[simp] lemma smul_inv (r : k) (φ : mv_power_series σ k) : (r • φ)⁻¹ = r⁻¹ • φ⁻¹ := by simp [smul_eq_C_mul, mul_comm] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] (φ ψ : mv_polynomial σ R) /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) := ⟨λ φ n, coeff n φ⟩ lemma coe_def : (φ : mv_power_series σ R) = λ n, coeff n φ := rfl @[simp, norm_cast] lemma coeff_coe (n : σ →₀ ℕ) : mv_power_series.coeff R n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) : (monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add : ((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul : ((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a := coe_monomial _ _ @[simp, norm_cast] lemma coe_bit0 : ((bit0 φ : mv_polynomial σ R) : mv_power_series σ R) = bit0 (φ : mv_power_series σ R) := coe_add _ _ @[simp, norm_cast] lemma coe_bit1 : ((bit1 φ : mv_polynomial σ R) : mv_power_series σ R) = bit1 (φ : mv_power_series σ R) := by rw [bit1, bit1, coe_add, coe_one, coe_bit0] @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ variables (σ R) lemma coe_injective : function.injective (coe : mv_polynomial σ R → mv_power_series σ R) := λ x y h, by { ext, simp_rw [←coeff_coe, h] } variables {σ R φ ψ} @[simp, norm_cast] lemma coe_inj : (φ : mv_power_series σ R) = ψ ↔ φ = ψ := (coe_injective σ R).eq_iff @[simp] lemma coe_eq_zero_iff : (φ : mv_power_series σ R) = 0 ↔ φ = 0 := by rw [←coe_zero, coe_inj] @[simp] lemma coe_eq_one_iff : (φ : mv_power_series σ R) = 1 ↔ φ = 1 := by rw [←coe_one, coe_inj] /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R := { to_fun := (coe : mv_polynomial σ R → mv_power_series σ R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } @[simp, norm_cast] lemma coe_pow (n : ℕ) : ((φ ^ n : mv_polynomial σ R) : mv_power_series σ R) = (φ : mv_power_series σ R) ^ n := coe_to_mv_power_series.ring_hom.map_pow _ _ variables (φ ψ) @[simp] lemma coe_to_mv_power_series.ring_hom_apply : coe_to_mv_power_series.ring_hom φ = φ := rfl section algebra variables (A : Type*) [comm_semiring A] [algebra R A] /-- The coercion from multivariable polynomials to multivariable power series as an algebra homomorphism. -/ def coe_to_mv_power_series.alg_hom : mv_polynomial σ R →ₐ[R] mv_power_series σ A := { commutes' := λ r, by simp [algebra_map_apply, mv_power_series.algebra_map_apply], ..(mv_power_series.map σ (algebra_map R A)).comp coe_to_mv_power_series.ring_hom} @[simp] lemma coe_to_mv_power_series.alg_hom_apply : (coe_to_mv_power_series.alg_hom A φ) = mv_power_series.map σ (algebra_map R A) ↑φ := rfl end algebra end mv_polynomial namespace mv_power_series variables {σ R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (f : mv_power_series σ R) instance algebra_mv_polynomial : algebra (mv_polynomial σ R) (mv_power_series σ A) := ring_hom.to_algebra (mv_polynomial.coe_to_mv_power_series.alg_hom A).to_ring_hom instance algebra_mv_power_series : algebra (mv_power_series σ R) (mv_power_series σ A) := (map σ (algebra_map R A)).to_algebra variables (A) lemma algebra_map_apply' (p : mv_polynomial σ R): algebra_map (mv_polynomial σ R) (mv_power_series σ A) p = map σ (algebra_map R A) p := rfl lemma algebra_map_apply'' : algebra_map (mv_power_series σ R) (mv_power_series σ A) f = map σ (algebra_map R A) f := rfl end mv_power_series /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type*) := mv_power_series unit R namespace power_series open finsupp (single) variable {R : Type*} section local attribute [reducible] power_series instance [inhabited R] : inhabited (power_series R) := by apply_instance instance [add_monoid R] : add_monoid (power_series R) := by apply_instance instance [add_group R] : add_group (power_series R) := by apply_instance instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance instance [semiring R] : semiring (power_series R) := by apply_instance instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance instance [ring R] : ring (power_series R) := by apply_instance instance [comm_ring R] : comm_ring (power_series R) := by apply_instance instance [nontrivial R] : nontrivial (power_series R) := by apply_instance instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (power_series A) := by apply_instance instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_smul R S] [is_scalar_tower R S A] : is_scalar_tower R S (power_series A) := pi.is_scalar_tower instance {A} [semiring A] [comm_semiring R] [algebra R A] : algebra R (power_series A) := by apply_instance end section semiring variables (R) [semiring R] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n) variables {R} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff R n = mv_power_series.coeff R s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by simp only [finsupp.unique_single_eq_iff] lemma monomial_eq_mk (n : ℕ) (a : R) : monomial R n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial_same (n : ℕ) (a : R) : coeff R n (monomial R n a) = a := mv_power_series.coeff_monomial_same _ _ @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n variable (R) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R /-- The constant formal power series.-/ def C : R →+* power_series R := mv_power_series.C unit R variable {R} /-- The variable of the formal power series ring.-/ def X : power_series R := mv_power_series.X () lemma commute_X (φ : power_series R) : commute φ X := φ.commute_X _ @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R 0) = constant_coeff R := by { rw [coeff, finsupp.single_zero], refl } lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) : coeff R 0 φ = constant_coeff R φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a := by simp lemma coeff_C (n : ℕ) (a : R) : coeff R n (C R a : power_series R) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a] lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl lemma coeff_X (n : ℕ) : coeff R n (X : power_series R) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 := by rw [coeff_X, if_pos rfl] @[simp] lemma X_ne_zero [nontrivial R] : (X : power_series R) ≠ 0 := λ H, by simpa only [coeff_one_X, one_ne_zero, map_zero] using congr_arg (coeff R 1) H lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff R n ((X : power_series R)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff R n (1 : power_series R) = if n = 0 then 1 else 0 := coeff_C n 1 lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series R) : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) : coeff R n (φ * C R a) = coeff R n φ * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (C R a * φ) = a * coeff R n φ := mv_power_series.coeff_C_mul _ φ a @[simp] lemma coeff_smul {S : Type*} [semiring S] [module R S] (n : ℕ) (φ : power_series S) (a : R) : coeff S n (a • φ) = a • coeff S n φ := rfl lemma smul_eq_C_mul (f : power_series R) (a : R) : a • f = C R a * f := by { ext, simp } @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) : coeff R (n+1) (φ * X) = coeff R n φ := begin simp only [coeff, finsupp.single_add], convert φ.coeff_add_mul_monomial (single () n) (single () 1) _, rw mul_one end @[simp] lemma coeff_succ_X_mul (n : ℕ) (φ : power_series R) : coeff R (n + 1) (X * φ) = coeff R n φ := begin simp only [coeff, finsupp.single_add, add_comm n 1], convert φ.coeff_add_monomial_mul (single () 1) (single () n) _, rw one_mul, end @[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff R).comp (C R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp lemma coeff_zero_X_mul (φ : power_series R) : coeff R 0 (X * φ) = 0 := by simp -- The following section duplicates the api of `data.polynomial.coeff` and should attempt to keep -- up to date with that section lemma coeff_C_mul_X_pow (x : R) (k n : ℕ) : coeff R n (C R x * X ^ k : power_series R) = if n = k then x else 0 := by simp [X_pow_eq, coeff_monomial] @[simp] theorem coeff_mul_X_pow (p : power_series R) (n d : ℕ) : coeff R (d + n) (p * X ^ n) = coeff R d p := begin rw [coeff_mul, finset.sum_eq_single (d, n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [finset.nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (finset.nat.mem_antidiagonal.2 rfl)).elim } end @[simp] theorem coeff_X_pow_mul (p : power_series R) (n d : ℕ) : coeff R (d + n) (X ^ n * p) = coeff R d p := begin rw [coeff_mul, finset.sum_eq_single (n,d), coeff_X_pow, if_pos rfl, one_mul], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, zero_mul], rintro rfl, apply h2, rw [finset.nat.mem_antidiagonal, add_comm, add_right_cancel_iff] at h1, subst h1 }, { rw add_comm, exact λ h1, (h1 (finset.nat.mem_antidiagonal.2 rfl)).elim } end lemma coeff_mul_X_pow' (p : power_series R) (n d : ℕ) : coeff R d (p * X ^ n) = ite (n ≤ d) (coeff R (d - n) p) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_mul_X_pow, add_tsub_cancel_right] }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, mul_zero], exact ((le_of_add_le_right (finset.nat.mem_antidiagonal.mp hx).le).trans_lt $ not_le.mp h).ne } end lemma coeff_X_pow_mul' (p : power_series R) (n d : ℕ) : coeff R d (X ^ n * p) = ite (n ≤ d) (coeff R (d - n) p) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_X_pow_mul], simp, }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, zero_mul], have := finset.nat.mem_antidiagonal.mp hx, rw add_comm at this, exact ((le_of_add_le_right this.le).trans_lt $ not_le.mp h).ne } end end /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) : is_unit (constant_coeff R φ) := mv_power_series.is_unit_constant_coeff φ h /-- Split off the constant coefficient. -/ lemma eq_shift_mul_X_add_const (φ : power_series R) : φ = mk (λ p, coeff R (p + 1) φ) * X + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, mul_zero, ring_hom.map_mul], }, { simp only [coeff_succ_mul_X, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end /-- Split off the constant coefficient. -/ lemma eq_X_mul_shift_add_const (φ : power_series R) : φ = X * mk (λ p, coeff R (p + 1) φ) + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, zero_mul, ring_hom.map_mul], }, { simp only [coeff_succ_X_mul, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end section map variables {S : Type*} {T : Type*} [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series R →+* power_series S := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id R) : power_series R → power_series R) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series R) : coeff S n (map f φ) = f (coeff R n φ) := rfl @[simp] lemma map_C (r : R) : map f (C _ r) = C _ (f r) := by { ext, simp [coeff_C, apply_ite f] } @[simp] lemma map_X : map f X = X := by { ext, simp [coeff_X, apply_ite f] } end map lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} : (X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series R} : (X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 := begin rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end end semiring section comm_semiring variables [comm_semiring R] open finset nat /-- The ring homomorphism taking a power series `f(X)` to `f(aX)`. -/ noncomputable def rescale (a : R) : power_series R →+* power_series R := { to_fun := λ f, power_series.mk $ λ n, a^n * (power_series.coeff R n f), map_zero' := by { ext, simp only [linear_map.map_zero, power_series.coeff_mk, mul_zero], }, map_one' := by { ext1, simp only [mul_boole, power_series.coeff_mk, power_series.coeff_one], split_ifs, { rw [h, pow_zero], }, refl, }, map_add' := by { intros, ext, exact mul_add _ _ _, }, map_mul' := λ f g, by { ext, rw [power_series.coeff_mul, power_series.coeff_mk, power_series.coeff_mul, finset.mul_sum], apply sum_congr rfl, simp only [coeff_mk, prod.forall, nat.mem_antidiagonal], intros b c H, rw [←H, pow_add, mul_mul_mul_comm] }, } @[simp] lemma coeff_rescale (f : power_series R) (a : R) (n : ℕ) : coeff R n (rescale a f) = a^n * coeff R n f := coeff_mk n _ @[simp] lemma rescale_zero : rescale 0 = (C R).comp (constant_coeff R) := begin ext, simp only [function.comp_app, ring_hom.coe_comp, rescale, ring_hom.coe_mk, power_series.coeff_mk _ _, coeff_C], split_ifs, { simp only [h, one_mul, coeff_zero_eq_constant_coeff, pow_zero], }, { rw [zero_pow' n h, zero_mul], }, end lemma rescale_zero_apply : rescale 0 X = C R (constant_coeff R X) := by simp @[simp] lemma rescale_one : rescale 1 = ring_hom.id (power_series R) := by { ext, simp only [ring_hom.id_apply, rescale, one_pow, coeff_mk, one_mul, ring_hom.coe_mk], } lemma rescale_mk (f : ℕ → R) (a : R) : rescale a (mk f) = mk (λ n : ℕ, a^n * (f n)) := by { ext, rw [coeff_rescale, coeff_mk, coeff_mk], } lemma rescale_rescale (f : power_series R) (a b : R) : rescale b (rescale a f) = rescale (a * b) f := begin ext, repeat { rw coeff_rescale, }, rw [mul_pow, mul_comm _ (b^n), mul_assoc], end lemma rescale_mul (a b : R) : rescale (a * b) = (rescale b).comp (rescale a) := by { ext, simp [← rescale_rescale], } section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : R[X] := ∑ m in Ico 0 n, polynomial.monomial m (coeff R m φ) lemma coeff_trunc (m) (n) (φ : power_series R) : (trunc n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc, polynomial.coeff_sum, polynomial.coeff_monomial, nat.lt_succ_iff] @[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc (n + 1) (1 : power_series R) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, rintro rfl, apply H, exact nat.zero_lt_succ _ } end @[simp] lemma trunc_C (n) (a : R) : trunc (n + 1) (C R a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring R] /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux : R → power_series R → power_series R := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series R) (u : Rˣ) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : Rˣ) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : Rˣ) : constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series R) (u : Rˣ) (h : constant_coeff R φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h /-- Two ways of removing the constant coefficient of a power series are the same. -/ lemma sub_const_eq_shift_mul_X (φ : power_series R) : φ - C R (constant_coeff R φ) = power_series.mk (λ p, coeff R (p + 1) φ) * X := sub_eq_iff_eq_add.mpr (eq_shift_mul_X_add_const φ) lemma sub_const_eq_X_mul_shift (φ : power_series R) : φ - C R (constant_coeff R φ) = X * power_series.mk (λ p, coeff R (p + 1) φ) := sub_eq_iff_eq_add.mpr (eq_X_mul_shift_add_const φ) end ring section comm_ring variables {A : Type*} [comm_ring A] @[simp] lemma rescale_X (a : A) : rescale a X = C A a * X := begin ext, simp only [coeff_rescale, coeff_C_mul, coeff_X], split_ifs with h; simp [h], end lemma rescale_neg_one_X : rescale (-1 : A) X = -X := by rw [rescale_X, map_neg, map_one, neg_one_mul] /-- The ring homomorphism taking a power series `f(X)` to `f(-X)`. -/ noncomputable def eval_neg_hom : power_series A →+* power_series A := rescale (-1 : A) @[simp] lemma eval_neg_hom_X : eval_neg_hom (X : power_series A) = -X := rescale_neg_one_X end comm_ring section domain variables [ring R] lemma eq_zero_or_eq_zero_of_mul_eq_zero [no_zero_divisors R] (φ ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw or_iff_not_imp_left, intro H, have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H }, let m := nat.find ex, have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff R (m + n)) h, rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, obtain rfl := le_antisymm hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance [no_zero_divisors R] : no_zero_divisors (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero } instance [is_domain R] : is_domain (power_series R) := no_zero_divisors.to_is_domain _ end domain section is_domain variables [comm_ring R] [is_domain R] /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime := begin suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series R) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff R 1) h } end lemma rescale_injective {a : R} (ha : a ≠ 0) : function.injective (rescale a) := begin intros p q h, rw power_series.ext_iff at *, intros n, specialize h n, rw [coeff_rescale, coeff_rescale, mul_eq_mul_left_iff] at h, apply h.resolve_right, intro h', exact ha (pow_eq_zero h'), end end is_domain section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f variables [local_ring R] [local_ring S] instance : local_ring (power_series R) := mv_power_series.local_ring end local_ring section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] theorem C_eq_algebra_map {r : R} : C R r = (algebra_map R (power_series R)) r := rfl theorem algebra_map_apply {r : R} : algebra_map R (power_series A) r = C A (algebra_map R A r) := mv_power_series.algebra_map_apply instance [nontrivial R] : nontrivial (subalgebra R (power_series R)) := mv_power_series.subalgebra.nontrivial end algebra section field variables {k : Type*} [field k] /-- The inverse 1/f of a power series f defined over a field -/ protected def inv : power_series k → power_series k := mv_power_series.inv instance : has_inv (power_series k) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series k) : φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else - (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series k) : constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series k} : φ⁻¹ = 0 ↔ constant_coeff k φ = 0 := mv_power_series.inv_eq_zero @[simp] lemma zero_inv : (0 : power_series k)⁻¹ = 0 := mv_power_series.zero_inv @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv_cancel (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv_cancel φ h @[simp] protected lemma inv_mul_cancel (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul_cancel φ h lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := mv_power_series.eq_mul_inv_iff_mul_eq h lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := mv_power_series.eq_inv_iff_mul_eq_one h lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := mv_power_series.inv_eq_iff_mul_eq_one h @[simp] protected lemma mul_inv_rev (φ ψ : power_series k) : (φ * ψ)⁻¹ = ψ⁻¹ * φ⁻¹ := mv_power_series.mul_inv_rev _ _ instance : inv_one_class (power_series k) := mv_power_series.inv_one_class @[simp] lemma C_inv (r : k) : (C k r)⁻¹ = C k r⁻¹ := mv_power_series.C_inv _ @[simp] lemma X_inv : (X : power_series k)⁻¹ = 0 := mv_power_series.X_inv _ @[simp] lemma smul_inv (r : k) (φ : power_series k) : (r • φ)⁻¹ = r⁻¹ • φ⁻¹ := mv_power_series.smul_inv _ _ end field end power_series namespace power_series variable {R : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [semiring R] {φ : power_series R} lemma exists_coeff_ne_zero_iff_ne_zero : (∃ (n : ℕ), coeff R n φ ≠ 0) ↔ φ ≠ 0 := begin refine not_iff_not.mp _, push_neg, simp [power_series.ext_iff] end /-- The order of a formal power series `φ` is the greatest `n : part_enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ def order (φ : power_series R) : part_enat := if h : φ = 0 then ⊤ else nat.find (exists_coeff_ne_zero_iff_ne_zero.mpr h) /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := dif_pos rfl lemma order_finite_iff_ne_zero : (order φ).dom ↔ φ ≠ 0 := begin simp only [order], split, { split_ifs with h h; intro H, { contrapose! H, simpa [←part.eq_none_iff'] }, { exact h } }, { intro h, simp [h] } end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin simp only [order, order_finite_iff_ne_zero.mp h, not_false_iff, dif_neg, part_enat.get_coe'], generalize_proofs h, exact nat.find_spec h end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have := exists.intro n h, rw [order, dif_neg], { simp only [part_enat.coe_le_coe, nat.find_le_iff], exact ⟨n, le_rfl, h⟩ }, { exact exists_coeff_ne_zero_iff_ne_zero.mp ⟨n, h⟩ } end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ h } /-- The `0` power series is the unique power series with infinite order.-/ @[simp] lemma order_eq_top {φ : power_series R} : φ.order = ⊤ ↔ φ = 0 := begin split, { intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] }, { rintros rfl, exact order_zero } end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := part_enat.dom_of_le_coe H.le, rw [← part_enat.coe_get this, part_enat.coe_lt_coe] at H, exact coeff_order this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series R) (n : part_enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using part_enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (part_enat.coe_lt_top i) }, { apply nat_le_order, simpa only [part_enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series R} {n : ℕ} : order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) := begin rcases eq_or_ne φ 0 with rfl|hφ, { simpa using (part_enat.coe_ne_top _).symm }, simp [order, dif_neg hφ, nat.find_eq_iff] end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series R} {n : part_enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using part_enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact part_enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (part_enat.coe_lt_top i) } }, { simpa [part_enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := begin refine le_order _ _ _, simp [coeff_of_lt_order] {contextual := tt} end private lemma order_add_of_order_eq.aux (φ ψ : power_series R) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_rfl, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw ←hi at H, rw [(coeff _ _).map_add, coeff_of_lt_order i H, add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order i hi, coeff_of_lt_order i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj), rw [← nat.cast_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : R) [decidable (a = 0)] : order (monomial R n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, linear_map.map_zero] }, { rw [order_eq], split; intros i hi, { rw [part_enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] }, { rw [part_enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) : order (monomial R n a) = n := by rw [order_monomial, if_neg h] /-- If `n` is strictly smaller than the order of `ψ`, then the `n`th coefficient of its product with any other power series is `0`. -/ lemma coeff_mul_of_lt_order {φ ψ : power_series R} {n : ℕ} (h : ↑n < ψ.order) : coeff R n (φ * ψ) = 0 := begin suffices : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, 0, rw [this, finset.sum_const_zero], rw [coeff_mul], apply finset.sum_congr rfl (λ x hx, _), refine mul_eq_zero_of_right (coeff R x.fst φ) (coeff_of_lt_order x.snd (lt_of_le_of_lt _ h)), rw finset.nat.mem_antidiagonal at hx, norm_cast, linarith, end lemma coeff_mul_one_sub_of_lt_order {R : Type*} [comm_ring R] {φ ψ : power_series R} (n : ℕ) (h : ↑n < ψ.order) : coeff R n (φ * (1 - ψ)) = coeff R n φ := by simp [coeff_mul_of_lt_order h, mul_sub] lemma coeff_mul_prod_one_sub_of_lt_order {R ι : Type*} [comm_ring R] (k : ℕ) (s : finset ι) (φ : power_series R) (f : ι → power_series R) : (∀ i ∈ s, ↑k < (f i).order) → coeff R k (φ * ∏ i in s, (1 - f i)) = coeff R k φ := begin apply finset.induction_on s, { simp }, { intros a s ha ih t, simp only [finset.mem_insert, forall_eq_or_imp] at t, rw [finset.prod_insert ha, ← mul_assoc, mul_right_comm, coeff_mul_one_sub_of_lt_order _ t.1], exact ih t.2 }, end -- TODO: link with `X_pow_dvd_iff` lemma X_pow_order_dvd (h : (order φ).dom) : X ^ ((order φ).get h) ∣ φ := begin refine ⟨power_series.mk (λ n, coeff R (n + (order φ).get h) φ), _⟩, ext n, simp only [coeff_mul, coeff_X_pow, coeff_mk, boole_mul, finset.sum_ite, finset.nat.filter_fst_eq_antidiagonal, finset.sum_const_zero, add_zero], split_ifs with hn hn, { simp [tsub_add_cancel_of_le hn] }, { simp only [finset.sum_empty], refine coeff_of_lt_order _ _, simpa [part_enat.coe_lt_iff] using λ _, hn } end lemma order_eq_multiplicity_X {R : Type*} [semiring R] (φ : power_series R) : order φ = multiplicity X φ := begin rcases eq_or_ne φ 0 with rfl|hφ, { simp }, induction ho : order φ using part_enat.cases_on with n, { simpa [hφ] using ho }, have hn : φ.order.get (order_finite_iff_ne_zero.mpr hφ) = n, { simp [ho] }, rw ←hn, refine le_antisymm (le_multiplicity_of_pow_dvd $ X_pow_order_dvd (order_finite_iff_ne_zero.mpr hφ)) (part_enat.find_le _ _ _), rintro ⟨ψ, H⟩, have := congr_arg (coeff R n) H, rw [← (ψ.commute_X.pow_right _).eq, coeff_mul_of_lt_order, ←hn] at this, { exact coeff_order _ this }, { rw [X_pow_eq, order_monomial], split_ifs, { exact part_enat.coe_lt_top _ }, { rw [←hn, part_enat.coe_lt_coe], exact nat.lt_succ_self _ } } end end order_basic section order_zero_ne_one variables [semiring R] [nontrivial R] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series R) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series R) = 1 := by simpa only [nat.cast_one] using order_monomial_of_ne_zero 1 (1:R) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_is_domain -- TODO: generalize to `[semiring R] [no_zero_divisors R]` variables [comm_ring R] [is_domain R] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series R) : order (φ * ψ) = order φ + order ψ := begin simp_rw [order_eq_multiplicity_X], exact multiplicity.mul X_prime end end order_is_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] (φ ψ : R[X]) /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe R[X] (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ lemma coe_def : (φ : power_series R) = power_series.mk (coeff φ) := rfl @[simp, norm_cast] lemma coeff_coe (n) : power_series.coeff R n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) : (monomial n a : power_series R) = power_series.monomial R n a := by { ext, simp [coeff_coe, power_series.coeff_monomial, polynomial.coeff_monomial, eq_comm] } @[simp, norm_cast] lemma coe_zero : ((0 : R[X]) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : R[X]) : power_series R) = 1 := begin have := coe_monomial 0 (1:R), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add : ((φ + ψ : R[X]) : power_series R) = φ + ψ := by { ext, simp } @[simp, norm_cast] lemma coe_mul : ((φ * ψ : R[X]) : power_series R) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : R[X]) : power_series R) = power_series.C R a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_bit0 : ((bit0 φ : R[X]) : power_series R) = bit0 (φ : power_series R) := coe_add φ φ @[simp, norm_cast] lemma coe_bit1 : ((bit1 φ : R[X]) : power_series R) = bit1 (φ : power_series R) := by rw [bit1, bit1, coe_add, coe_one, coe_bit0] @[simp, norm_cast] lemma coe_X : ((X : R[X]) : power_series R) = power_series.X := coe_monomial _ _ @[simp] lemma constant_coeff_coe : power_series.constant_coeff R φ = φ.coeff 0 := rfl variables (R) lemma coe_injective : function.injective (coe : R[X] → power_series R) := λ x y h, by { ext, simp_rw [←coeff_coe, h] } variables {R φ ψ} @[simp, norm_cast] lemma coe_inj : (φ : power_series R) = ψ ↔ φ = ψ := (coe_injective R).eq_iff @[simp] lemma coe_eq_zero_iff : (φ : power_series R) = 0 ↔ φ = 0 := by rw [←coe_zero, coe_inj] @[simp] lemma coe_eq_one_iff : (φ : power_series R) = 1 ↔ φ = 1 := by rw [←coe_one, coe_inj] variables (φ ψ) /-- The coercion from polynomials to power series as a ring homomorphism. -/ def coe_to_power_series.ring_hom : R[X] →+* power_series R := { to_fun := (coe : R[X] → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } @[simp] lemma coe_to_power_series.ring_hom_apply : coe_to_power_series.ring_hom φ = φ := rfl @[simp, norm_cast] lemma coe_pow (n : ℕ): ((φ ^ n : R[X]) : power_series R) = (φ : power_series R) ^ n := coe_to_power_series.ring_hom.map_pow _ _ variables (A : Type*) [semiring A] [algebra R A] /-- The coercion from polynomials to power series as an algebra homomorphism. -/ def coe_to_power_series.alg_hom : R[X] →ₐ[R] power_series A := { commutes' := λ r, by simp [algebra_map_apply, power_series.algebra_map_apply], ..(power_series.map (algebra_map R A)).comp coe_to_power_series.ring_hom } @[simp] lemma coe_to_power_series.alg_hom_apply : (coe_to_power_series.alg_hom A φ) = power_series.map (algebra_map R A) ↑φ := rfl end polynomial namespace power_series variables {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (f : power_series R) instance algebra_polynomial : algebra R[X] (power_series A) := ring_hom.to_algebra (polynomial.coe_to_power_series.alg_hom A).to_ring_hom instance algebra_power_series : algebra (power_series R) (power_series A) := (map (algebra_map R A)).to_algebra @[priority 100] -- see Note [lower instance priority] instance algebra_polynomial' {A : Type*} [comm_semiring A] [algebra R A[X]] : algebra R (power_series A) := ring_hom.to_algebra $ polynomial.coe_to_power_series.ring_hom.comp (algebra_map R A[X]) variables (A) lemma algebra_map_apply' (p : R[X]) : algebra_map R[X] (power_series A) p = map (algebra_map R A) p := rfl lemma algebra_map_apply'' : algebra_map (power_series R) (power_series A) f = map (algebra_map R A) f := rfl end power_series
70967e5bca7ac2aa207dd0d9885be0ea23283e2e
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/topology/sheaves/forget.lean
7d3db6f567bc592a922ae98210260be6ec531a58
[ "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
7,889
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 topology.sheaves.sheaf import category_theory.limits.preserves.shapes import category_theory.limits.types /-! # Checking the sheaf condition on the underlying presheaf of types. If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. ## References * https://stacks.math.columbia.edu/tag/0073 -/ open category_theory open category_theory.limits open topological_space open opposite namespace Top namespace sheaf_condition universes v u₁ u₂ variables {C : Type u₁} [category.{v} C] [has_limits C] variables {D : Type u₂} [category.{v} D] [has_limits D] variables (G : C ⥤ D) [preserves_limits G] variables {X : Top.{v}} (F : presheaf C X) variables {ι : Type v} (U : ι → opens X) local attribute [reducible] sheaf_condition.diagram local attribute [reducible] sheaf_condition.left_res sheaf_condition.right_res /-- When `G` preserves limits, the sheaf condition diagram for `F` composed with `G` is naturally isomorphic to the sheaf condition diagram for `F ⋙ G`. -/ def diagram_comp_preserves_limits : sheaf_condition.diagram F U ⋙ G ≅ sheaf_condition.diagram (F ⋙ G) U := begin fapply nat_iso.of_components, rintro ⟨j⟩, exact (preserves_products_iso _ _), exact (preserves_products_iso _ _), rintros ⟨⟩ ⟨⟩ ⟨⟩, { ext, simp, dsimp, simp, }, -- non-terminal `simp`, but `squeeze_simp` fails { ext, simp only [limit.lift_π, functor.comp_map, parallel_pair_map_left, fan.mk_π_app, map_lift_comp_preserves_products_iso_hom, functor.map_comp, category.assoc], dsimp, simp, }, { ext, simp only [limit.lift_π, functor.comp_map, parallel_pair_map_right, fan.mk_π_app, map_lift_comp_preserves_products_iso_hom, functor.map_comp, category.assoc], dsimp, simp, }, { ext, simp, dsimp, simp, }, end local attribute [reducible] sheaf_condition.res /-- When `G` preserves limits, the image under `G` of the sheaf condition fork for `F` is the sheaf condition fork for `F ⋙ G`, postcomposed with the inverse of the natural isomorphism `diagram_comp_preserves_limits`. -/ def map_cone_fork : G.map_cone (sheaf_condition.fork F U) ≅ (cones.postcompose (diagram_comp_preserves_limits G F U).inv).obj (sheaf_condition.fork (F ⋙ G) U) := cones.ext (iso.refl _) (λ j, begin dsimp, simp [diagram_comp_preserves_limits], cases j; dsimp, { rw iso.eq_comp_inv, ext, simp, dsimp, simp, }, { rw iso.eq_comp_inv, ext, simp, -- non-terminal `simp`, but `squeeze_simp` fails dsimp, simp only [limit.lift_π, fan.mk_π_app, ←G.map_comp, limit.lift_π_assoc, fan.mk_π_app] } end) end sheaf_condition universes v u₁ u₂ open sheaf_condition variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D] variables (G : C ⥤ D) variables [reflects_isomorphisms G] variables [has_limits C] [has_limits D] [preserves_limits G] variables {X : Top.{v}} (F : presheaf C X) /-- If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. Another useful example is the forgetful functor `TopCommRing ⥤ Top`. -/ def sheaf_condition_equiv_sheaf_condition_comp : sheaf_condition F ≃ sheaf_condition (F ⋙ G) := begin apply equiv_of_subsingleton_of_subsingleton, { intros S ι U, -- We have that the sheaf condition fork for `F` is a limit fork, have t₁ := S U, -- and since `G` preserves limits, the image under `G` of this fork is a limit fork too. have t₂ := @preserves_limit.preserves _ _ _ _ _ _ _ G _ _ t₁, -- As we established above, that image is just the sheaf condition fork -- for `F ⋙ G` postcomposed with some natural isomorphism, have t₃ := is_limit.of_iso_limit t₂ (map_cone_fork G F U), -- and as postcomposing by a natural isomorphism preserves limit cones, have t₄ := is_limit.postcompose_inv_equiv _ _ t₃, -- we have our desired conclusion. exact t₄, }, { intros S ι U, -- Let `f` be the universal morphism from `F.obj U` to the equalizer of the sheaf condition fork, -- whatever it is. Our goal is to show that this is an isomorphism. let f := equalizer.lift _ (w F U), -- If we can do that, suffices : is_iso (G.map f), { resetI, -- we have that `f` itself is an isomorphism, since `G` reflects isomorphisms haveI : is_iso f := is_iso_of_reflects_iso f G, -- TODO package this up as a result elsewhere: apply is_limit.of_iso_limit (limit.is_limit _), apply iso.symm, fapply cones.ext, exact (as_iso f), rintro ⟨_|_⟩; { dsimp [f], simp, }, }, { -- Returning to the task of shwoing that `G.map f` is an isomorphism, -- we note that `G.map f` is almost but not quite (see below) a morphism -- from the sheaf condition cone for `F ⋙ G` to the -- image under `G` of the equalizer cone for the sheaf condition diagram. let c := sheaf_condition.fork (F ⋙ G) U, have hc : is_limit c := S U, let d := G.map_cone (equalizer.fork (left_res F U) (right_res F U)), have hd : is_limit d := preserves_limit.preserves (limit.is_limit _), -- Since both of these are limit cones -- (`c` by our hypothesis `S`, and `d` because `G` preserves limits), -- we hope to be able to conclude that `f` is an isomorphism. -- We say "not quite" above because `c` and `d` don't quite have the same shape: -- we need to postcompose by the natural isomorphism `diagram_comp_preserves_limits` -- introduced above. let d' := (cones.postcompose (diagram_comp_preserves_limits G F U).hom).obj d, have hd' : is_limit d' := (is_limit.postcompose_hom_equiv (diagram_comp_preserves_limits G F U) d).symm hd, -- Now everything works: we verify that `f` really is a morphism between these cones: let f' : c ⟶ d' := fork.mk_hom (G.map f) begin dsimp only [c, d, d', f, diagram_comp_preserves_limits, res], dunfold fork.ι, ext1 j, dsimp, simp only [category.assoc, ←functor.map_comp_assoc, equalizer.lift_ι, map_lift_comp_preserves_products_iso_hom_assoc], dsimp [res], simp, end, -- conclude that it is an isomorphism, -- just because it's a morphism between two limit cones. haveI : is_iso f' := is_limit.hom_is_iso hc hd' f', -- A cone morphism is an isomorphism exactly if the morphism between the cone points is, -- so we're done! exact { ..((cones.forget _).map_iso (as_iso f')) }, }, }, end /-! As an example, we now have everything we need to check the sheaf condition for a presheaf of commutative rings, merely by checking the sheaf condition for the underlying sheaf of types. ``` example (X : Top) (F : presheaf CommRing X) (h : sheaf_condition (F ⋙ (forget CommRing))) : sheaf_condition F := (sheaf_condition_equiv_sheaf_condition_forget F).symm h ``` -/ end Top
af676253071a60ad227fff03efac0743fb8bfd1d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/perm/list.lean
78de80f5411efb9b6169040c82b764b8b3e210f3
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
17,165
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.list.rotate import group_theory.perm.support /-! # Permutations from a list A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. When there are duplicate elements in `l`, how and in what arrangement with respect to the other elements they appear in the list determines the formed permutation. This is because `list.form_perm` is implemented as a product of `equiv.swap`s. That means that presence of a sublist of two adjacent duplicates like `[..., x, x, ...]` will produce the same permutation as if the adjacent duplicates were not present. The `list.form_perm` definition is meant to primarily be used with `nodup l`, so that the resulting permutation is cyclic (if `l` has at least two elements). The presence of duplicates in a particular placement can lead `list.form_perm` to produce a nontrivial permutation that is noncyclic. -/ namespace list variables {α β : Type*} section form_perm variables [decidable_eq α] (l : list α) open equiv equiv.perm /-- A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. -/ def form_perm : equiv.perm α := (zip_with equiv.swap l l.tail).prod @[simp] lemma form_perm_nil : form_perm ([] : list α) = 1 := rfl @[simp] lemma form_perm_singleton (x : α) : form_perm [x] = 1 := rfl @[simp] lemma form_perm_cons_cons (x y : α) (l : list α) : form_perm (x :: y :: l) = swap x y * form_perm (y :: l) := prod_cons lemma form_perm_pair (x y : α) : form_perm [x, y] = swap x y := rfl variables {l} {x : α} lemma form_perm_apply_of_not_mem (x : α) (l : list α) (h : x ∉ l) : form_perm l x = x := begin cases l with y l, { simp }, induction l with z l IH generalizing x y, { simp }, { specialize IH x z (mt (mem_cons_of_mem y) h), simp only [not_or_distrib, mem_cons_iff] at h, simp [IH, swap_apply_of_ne_of_ne, h] } end lemma mem_of_form_perm_apply_ne (x : α) (l : list α) : l.form_perm x ≠ x → x ∈ l := not_imp_comm.2 $ list.form_perm_apply_of_not_mem _ _ lemma form_perm_apply_mem_of_mem (x : α) (l : list α) (h : x ∈ l) : form_perm l x ∈ l := begin cases l with y l, { simpa }, induction l with z l IH generalizing x y, { simpa using h }, { by_cases hx : x ∈ z :: l, { rw [form_perm_cons_cons, mul_apply, swap_apply_def], split_ifs; simp [IH _ _ hx] }, { replace h : x = y := or.resolve_right h hx, simp [form_perm_apply_of_not_mem _ _ hx, ←h] } } end lemma mem_of_form_perm_apply_mem (x : α) (l : list α) (h : l.form_perm x ∈ l) : x ∈ l := begin cases l with y l, { simpa }, induction l with z l IH generalizing x y, { simpa using h }, { by_cases hx : (z :: l).form_perm x ∈ z :: l, { rw [list.form_perm_cons_cons, mul_apply, swap_apply_def] at h, split_ifs at h; simp [IH _ _ hx] }, { replace hx := (function.injective.eq_iff (equiv.injective _)).mp (list.form_perm_apply_of_not_mem _ _ hx), simp only [list.form_perm_cons_cons, hx, equiv.perm.coe_mul, function.comp_app, list.mem_cons_iff, swap_apply_def, ite_eq_left_iff] at h, simp only [list.mem_cons_iff], obtain h | h | h := h; { split_ifs at h; cc }}} end lemma form_perm_mem_iff_mem : l.form_perm x ∈ l ↔ x ∈ l := ⟨l.mem_of_form_perm_apply_mem x, l.form_perm_apply_mem_of_mem x⟩ @[simp] lemma form_perm_cons_concat_apply_last (x y : α) (xs : list α) : form_perm (x :: (xs ++ [y])) y = x := begin induction xs with z xs IH generalizing x y, { simp }, { simp [IH] } end @[simp] lemma form_perm_apply_last (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).last (cons_ne_nil x xs)) = x := begin induction xs using list.reverse_rec_on with xs y IH generalizing x; simp end @[simp] lemma form_perm_apply_nth_le_length (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).nth_le xs.length (by simp)) = x := by rw [nth_le_cons_length, form_perm_apply_last] lemma form_perm_apply_head (x y : α) (xs : list α) (h : nodup (x :: y :: xs)) : form_perm (x :: y :: xs) x = y := by simp [form_perm_apply_of_not_mem _ _ h.not_mem] lemma form_perm_apply_nth_le_zero (l : list α) (h : nodup l) (hl : 1 < l.length) : form_perm l (l.nth_le 0 (zero_lt_one.trans hl)) = l.nth_le 1 hl := begin rcases l with (_|⟨x, _|⟨y, tl⟩⟩), { simp }, { simp }, { simpa using form_perm_apply_head _ _ _ h } end variables (l) lemma form_perm_eq_head_iff_eq_last (x y : α) : form_perm (y :: l) x = y ↔ x = last (y :: l) (cons_ne_nil _ _) := iff.trans (by rw form_perm_apply_last) (form_perm (y :: l)).injective.eq_iff lemma zip_with_swap_prod_support' (l l' : list α) : {x | (zip_with swap l l').prod x ≠ x} ≤ l.to_finset ⊔ l'.to_finset := begin simp only [set.sup_eq_union, set.le_eq_subset], induction l with y l hl generalizing l', { simp }, { cases l' with z l', { simp }, { intro x, simp only [set.union_subset_iff, mem_cons_iff, zip_with_cons_cons, foldr, prod_cons, mul_apply], intro hx, by_cases h : x ∈ {x | (zip_with swap l l').prod x ≠ x}, { specialize hl l' h, refine set.mem_union.elim hl (λ hm, _) (λ hm, _); { simp only [finset.coe_insert, set.mem_insert_iff, finset.mem_coe, to_finset_cons, mem_to_finset] at hm ⊢, simp [hm] } }, { simp only [not_not, set.mem_set_of_eq] at h, simp only [h, set.mem_set_of_eq] at hx, rw swap_apply_ne_self_iff at hx, rcases hx with ⟨hyz, rfl|rfl⟩; simp } } } end lemma zip_with_swap_prod_support [fintype α] (l l' : list α) : (zip_with swap l l').prod.support ≤ l.to_finset ⊔ l'.to_finset := begin intros x hx, have hx' : x ∈ {x | (zip_with swap l l').prod x ≠ x} := by simpa using hx, simpa using zip_with_swap_prod_support' _ _ hx' end lemma support_form_perm_le' : {x | form_perm l x ≠ x} ≤ l.to_finset := begin refine (zip_with_swap_prod_support' l l.tail).trans _, simpa [finset.subset_iff] using tail_subset l end lemma support_form_perm_le [fintype α] : support (form_perm l) ≤ l.to_finset := begin intros x hx, have hx' : x ∈ {x | form_perm l x ≠ x} := by simpa using hx, simpa using support_form_perm_le' _ hx' end lemma form_perm_apply_lt (xs : list α) (h : nodup xs) (n : ℕ) (hn : n + 1 < xs.length) : form_perm xs (xs.nth_le n ((nat.lt_succ_self n).trans hn)) = xs.nth_le (n + 1) hn := begin induction n with n IH generalizing xs, { simpa using form_perm_apply_nth_le_zero _ h _ }, { rcases xs with (_|⟨x, _|⟨y, l⟩⟩), { simp }, { simp }, { specialize IH (y :: l) h.of_cons _, { simpa [nat.succ_lt_succ_iff] using hn }, simp only [swap_apply_eq_iff, coe_mul, form_perm_cons_cons, nth_le], generalize_proofs at IH, rw [IH, swap_apply_of_ne_of_ne, nth_le]; { rintro rfl, simpa [nth_le_mem _ _ _] using h } } } end lemma form_perm_apply_nth_le (xs : list α) (h : nodup xs) (n : ℕ) (hn : n < xs.length) : form_perm xs (xs.nth_le n hn) = xs.nth_le ((n + 1) % xs.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases xs with x xs, { simp }, { have : n ≤ xs.length, { refine nat.le_of_lt_succ _, simpa using hn }, rcases this.eq_or_lt with rfl|hn', { simp }, { simp [form_perm_apply_lt, h, nat.mod_eq_of_lt, nat.succ_lt_succ hn'] } } end lemma support_form_perm_of_nodup' (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : {x | form_perm l x ≠ x} = l.to_finset := begin apply le_antisymm, { exact support_form_perm_le' l }, { intros x hx, simp only [finset.mem_coe, mem_to_finset] at hx, obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, rw [set.mem_set_of_eq, form_perm_apply_nth_le _ h], intro H, rw nodup_iff_nth_le_inj at h, specialize h _ _ _ _ H, cases (nat.succ_le_of_lt hn).eq_or_lt with hn' hn', { simp only [←hn', nat.mod_self] at h, refine not_exists.mpr h' _, simpa [←h, eq_comm, length_eq_one] using hn' }, { simpa [nat.mod_eq_of_lt hn'] using h } } end lemma support_form_perm_of_nodup [fintype α] (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : support (form_perm l) = l.to_finset := begin rw ←finset.coe_inj, convert support_form_perm_of_nodup' _ h h', simp [set.ext_iff] end lemma form_perm_rotate_one (l : list α) (h : nodup l) : form_perm (l.rotate 1) = form_perm l := begin have h' : nodup (l.rotate 1), { simpa using h }, ext x, by_cases hx : x ∈ l.rotate 1, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ h', nth_le_rotate l, nth_le_rotate l, form_perm_apply_nth_le _ h], simp }, { rw [form_perm_apply_of_not_mem _ _ hx, form_perm_apply_of_not_mem], simpa using hx } end lemma form_perm_rotate (l : list α) (h : nodup l) (n : ℕ) : form_perm (l.rotate n) = form_perm l := begin induction n with n hn, { simp }, { rw [nat.succ_eq_add_one, ←rotate_rotate, form_perm_rotate_one, hn], rwa is_rotated.nodup_iff, exact is_rotated.forall l n } end lemma form_perm_eq_of_is_rotated {l l' : list α} (hd : nodup l) (h : l ~r l') : form_perm l = form_perm l' := begin obtain ⟨n, rfl⟩ := h, exact (form_perm_rotate l hd n).symm end lemma form_perm_reverse (l : list α) (h : nodup l) : form_perm l.reverse = (form_perm l)⁻¹ := begin -- Let's show `form_perm l` is an inverse to `form_perm l.reverse`. rw [eq_comm, inv_eq_iff_mul_eq_one], ext x, -- We only have to check for `x ∈ l` that `form_perm l (form_perm l.reverse x)` rw [mul_apply, one_apply], by_cases hx : x ∈ l, swap, { rw [form_perm_apply_of_not_mem x l.reverse, form_perm_apply_of_not_mem _ _ hx], simpa using hx }, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem (mem_reverse.mpr hx), rw [form_perm_apply_nth_le l.reverse (nodup_reverse.mpr h), nth_le_reverse', form_perm_apply_nth_le _ h, nth_le_reverse'], { congr, rw [length_reverse, ←nat.succ_le_iff, nat.succ_eq_add_one] at hk, cases hk.eq_or_lt with hk' hk', { simp [←hk'] }, { rw [length_reverse, nat.mod_eq_of_lt hk', tsub_add_eq_add_tsub (nat.le_pred_of_lt hk'), nat.mod_eq_of_lt], { simp }, { rw tsub_add_cancel_of_le, refine tsub_lt_self _ (nat.zero_lt_succ _), all_goals { simpa using (nat.zero_le _).trans_lt hk' } } } }, all_goals { rw [← tsub_add_eq_tsub_tsub, ←length_reverse], refine tsub_lt_self _ (zero_lt_one.trans_le (le_add_right le_rfl)), exact k.zero_le.trans_lt hk } }, end lemma form_perm_pow_apply_nth_le (l : list α) (h : nodup l) (n k : ℕ) (hk : k < l.length) : (form_perm l ^ n) (l.nth_le k hk) = l.nth_le ((k + n) % l.length) (nat.mod_lt _ (k.zero_le.trans_lt hk)) := begin induction n with n hn, { simp [nat.mod_eq_of_lt hk] }, { simp [pow_succ, mul_apply, hn, form_perm_apply_nth_le _ h, nat.succ_eq_add_one, ←nat.add_assoc] } end lemma form_perm_pow_apply_head (x : α) (l : list α) (h : nodup (x :: l)) (n : ℕ) : (form_perm (x :: l) ^ n) x = (x :: l).nth_le (n % (x :: l).length) (nat.mod_lt _ (nat.zero_lt_succ _)) := by { convert form_perm_pow_apply_nth_le _ h n 0 _; simp } lemma form_perm_ext_iff {x y x' y' : α} {l l' : list α} (hd : nodup (x :: y :: l)) (hd' : nodup (x' :: y' :: l')) : form_perm (x :: y :: l) = form_perm (x' :: y' :: l') ↔ (x :: y :: l) ~r (x' :: y' :: l') := begin refine ⟨λ h, _, λ hr, form_perm_eq_of_is_rotated hd hr⟩, rw equiv.perm.ext_iff at h, have hx : x' ∈ (x :: y :: l), { have : x' ∈ {z | form_perm (x :: y :: l) z ≠ z}, { rw [set.mem_set_of_eq, h x', form_perm_apply_head _ _ _ hd'], simp only [mem_cons_iff, nodup_cons] at hd', push_neg at hd', exact hd'.left.left.symm }, simpa using support_form_perm_le' _ this }, obtain ⟨n, hn, hx'⟩ := nth_le_of_mem hx, have hl : (x :: y :: l).length = (x' :: y' :: l').length, { rw [←dedup_eq_self.mpr hd, ←dedup_eq_self.mpr hd', ←card_to_finset, ←card_to_finset], refine congr_arg finset.card _, rw [←finset.coe_inj, ←support_form_perm_of_nodup' _ hd (by simp), ←support_form_perm_of_nodup' _ hd' (by simp)], simp only [h] }, use n, apply list.ext_le, { rw [length_rotate, hl] }, { intros k hk hk', rw nth_le_rotate, induction k with k IH, { simp_rw [nat.zero_add, nat.mod_eq_of_lt hn], simpa }, { have : k.succ = (k + 1) % (x' :: y' :: l').length, { rw [←nat.succ_eq_add_one, nat.mod_eq_of_lt hk'] }, simp_rw this, rw [←form_perm_apply_nth_le _ hd' k (k.lt_succ_self.trans hk'), ←IH (k.lt_succ_self.trans hk), ←h, form_perm_apply_nth_le _ hd], congr' 1, have h1 : 1 = 1 % (x' :: y' :: l').length := by simp, rw [hl, nat.mod_eq_of_lt hk', h1, ←nat.add_mod, nat.succ_add] } } end lemma form_perm_apply_mem_eq_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = x ↔ length l ≤ 1 := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ hl, hl.nth_le_inj_iff], cases hn : l.length, { exact absurd k.zero_le (hk.trans_le hn.le).not_le }, { rw hn at hk, cases (nat.le_of_lt_succ hk).eq_or_lt with hk' hk', { simp [←hk', nat.succ_le_succ_iff, eq_comm] }, { simpa [nat.mod_eq_of_lt (nat.succ_lt_succ hk'), nat.succ_lt_succ_iff] using k.zero_le.trans_lt hk' } } end lemma form_perm_apply_mem_ne_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x ≠ x ↔ 2 ≤ l.length := begin rw [ne.def, form_perm_apply_mem_eq_self_iff _ hl x hx, not_le], exact ⟨nat.succ_le_of_lt, nat.lt_of_succ_le⟩ end lemma mem_of_form_perm_ne_self (l : list α) (x : α) (h : form_perm l x ≠ x) : x ∈ l := begin suffices : x ∈ {y | form_perm l y ≠ y}, { rw ←mem_to_finset, exact support_form_perm_le' _ this }, simpa using h end lemma form_perm_eq_self_of_not_mem (l : list α) (x : α) (h : x ∉ l) : form_perm l x = x := by_contra (λ H, h $ mem_of_form_perm_ne_self _ _ H) lemma form_perm_eq_one_iff (hl : nodup l) : form_perm l = 1 ↔ l.length ≤ 1 := begin cases l with hd tl, { simp }, { rw ←form_perm_apply_mem_eq_self_iff _ hl hd (mem_cons_self _ _), split, { simp {contextual := tt} }, { intro h, simp only [(hd :: tl).form_perm_apply_mem_eq_self_iff hl hd (mem_cons_self hd tl), add_le_iff_nonpos_left, length, nonpos_iff_eq_zero, length_eq_zero] at h, simp [h] } } end lemma form_perm_eq_form_perm_iff {l l' : list α} (hl : l.nodup) (hl' : l'.nodup) : l.form_perm = l'.form_perm ↔ l ~r l' ∨ l.length ≤ 1 ∧ l'.length ≤ 1 := begin rcases l with (_ | ⟨x, _ | ⟨y, l⟩⟩), { suffices : l'.length ≤ 1 ↔ l' = nil ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero] }, refine ⟨λ h, or.inr h, _⟩, rintro (rfl | h), { simp }, { exact h } }, { suffices : l'.length ≤ 1 ↔ [x] ~r l' ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero, le_rfl] }, refine ⟨λ h, or.inr h, _⟩, rintro (h | h), { simp [←h.perm.length_eq] }, { exact h } }, { rcases l' with (_ | ⟨x', _ | ⟨y', l'⟩⟩), { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, { suffices : ¬ (x :: y :: l) ~r [x'], { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, intro h, simpa using h.perm.length_eq }, { simp [-form_perm_cons_cons, form_perm_ext_iff hl hl'] } } end lemma form_perm_zpow_apply_mem_imp_mem (l : list α) (x : α) (hx : x ∈ l) (n : ℤ) : ((form_perm l) ^ n) x ∈ l := begin by_cases h : (l.form_perm ^ n) x = x, { simpa [h] using hx }, { have : x ∈ {x | (l.form_perm ^ n) x ≠ x} := h, rw ←set_support_apply_mem at this, replace this := set_support_zpow_subset _ _ this, simpa using support_form_perm_le' _ this } end lemma form_perm_pow_length_eq_one_of_nodup (hl : nodup l) : (form_perm l) ^ (length l) = 1 := begin ext x, by_cases hx : x ∈ l, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, simp [form_perm_pow_apply_nth_le _ hl, nat.mod_eq_of_lt hk] }, { have : x ∉ {x | (l.form_perm ^ l.length) x ≠ x}, { intros H, refine hx _, replace H := set_support_zpow_subset l.form_perm l.length H, simpa using support_form_perm_le' _ H }, simpa } end end form_perm end list
cfa580cc61df17885871b851e01c0c6f91019879
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love08_operational_semantics_homework_solution.lean
5db2f782fa66cbf287f1ef87ffcba30c88922b42
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,356
lean
import .lovelib /- # LoVe Homework 8: Operational Semantics Homework must be done individually. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Question 1 (6 points + 1 bonus point): Semantics of the REPEAT Language We introduce REPEAT, a programming language that resembles the WHILE language but whose defining feature is a `repeat` loop. The Lean definition of its abstract syntax tree follows: -/ inductive stmt : Type | skip : stmt | assign : string → (state → ℕ) → stmt | seq : stmt → stmt → stmt | unless : (state → Prop) → stmt → stmt | repeat : ℕ → stmt → stmt infixr ` ;; ` : 90 := stmt.seq /- The `skip`, `assign`, and `S ;; T` statements have the same syntax and semantics as in the WHILE language. The `unless b S` statement executes `S` unless `b` is true—i.e., it executes `S` if `b` is false. Otherwise, `unless b S` does nothing. This construct is inspired by the Perl language. The `repeat n S` statement executes `S` exactly `n` times. Thus, `repeat 5 S` is equivalent to `S ;; S ;; S ;; S ;; S` (in terms of a big-step semantics at least) and `repeat 0 S` is equivalent to `skip`. 1.1 (1.5 points). Complete the following definition of a big-step semantics: -/ inductive big_step : stmt × state → state → Prop | skip {s} : big_step (stmt.skip, s) s | assign {x a s} : big_step (stmt.assign x a, s) (s{x ↦ a s}) | seq {S T s t u} (hs : big_step (S, s) t) (ht : big_step (T, t) u) : big_step (S ;; T, s) u | unless_false {b : state → Prop} {S s t} (hcond : ¬ b s) (hbody : big_step (S, s) t) : big_step (stmt.unless b S, s) t | unless_true {b : state → Prop} {S s} (hcond : b s) : big_step (stmt.unless b S, s) s | repeat_zero {S s} : big_step (stmt.repeat 0 S, s) s | repeat_succ {n S s t u} (hbody : big_step (S, s) t) (hrest : big_step (stmt.repeat n S, t) u) : big_step (stmt.repeat (n + 1) S, s) u infix ` ⟹ ` : 110 := big_step /- 1.2 (1.5 points). Complete the following definition of a small-step semantics: -/ inductive small_step : stmt × state → stmt × state → Prop | assign {x a s} : small_step (stmt.assign x a, s) (stmt.skip, s{x ↦ a s}) | seq_step {S S' T s s'} (hS : small_step (S, s) (S', s')) : small_step (S ;; T, s) (S' ;; T, s') | seq_skip {T s} : small_step (stmt.skip ;; T, s) (T, s) | unless_false {b : state → Prop} {S s} (hcond : ¬ b s) : small_step (stmt.unless b S, s) (S, s) | unless_true {b : state → Prop} {S s} (hcond : b s) : small_step (stmt.unless b S, s) (stmt.skip, s) | repeat_zero {S s} : small_step (stmt.repeat 0 S, s) (stmt.skip, s) | repeat_succ {n S s} : small_step (stmt.repeat (n + 1) S, s) (S ;; stmt.repeat n S, s) infixr ` ⇒ ` := small_step infixr ` ⇒* ` : 100 := star small_step /- 1.3 (1 point). We will now attempt to prove termination of the REPEAT language. More precisely, we will show that there cannot be infinite chains of the form `(S₀, s₀) ⇒ (S₁, s₁) ⇒ (S₂, s₂) ⇒ ⋯` Towards this goal, you are asked to define a __measure__ function: a function `mess` that takes a statement `S` and that returns a natural number indicating how "big" the statement is. The measure should be defined so that it strictly decreases with each small-step transition. -/ def mess : stmt → ℕ | stmt.skip := 0 | (stmt.assign _ _) := 1 | (S ;; T) := mess S + mess T + 1 | (stmt.unless _ S) := mess S + 1 | (stmt.repeat n S) := n * (mess S + 2) + 1 /- 1.4 (1 point). Consider the following program `S₀`: -/ def incr (x : string) : stmt := stmt.assign x (λs, s x + 1) def S₀ : stmt := stmt.repeat 1 (incr "m" ;; incr "n") /- Check that `mess` strictly decreases with each step of its small-step evaluation, by giving `S₀`, `S₁`, `S₂`, …, as well as the corresponding values of `mess` (which you can obtain using `#eval`). -/ def S₁ : stmt := (incr "m" ;; incr "n") ;; stmt.repeat 0 (incr "m" ;; incr "n") def S₂ : stmt := (stmt.skip ;; incr "n") ;; stmt.repeat 0 (incr "m" ;; incr "n") def S₃ : stmt := incr "n" ;; stmt.repeat 0 (incr "m" ;; incr "n") def S₄ : stmt := stmt.skip ;; stmt.repeat 0 (incr "m" ;; incr "n") def S₅ : stmt := stmt.repeat 0 (incr "m" ;; incr "n") def S₆ : stmt := stmt.skip #eval mess S₀ -- result: 6 #eval mess S₁ -- result: 5 #eval mess S₂ -- result: 4 #eval mess S₃ -- result: 3 #eval mess S₄ -- result: 2 #eval mess S₅ -- result: 1 #eval mess S₆ -- result: 0 /- 1.5 (1 point). Prove that the measure decreases with each small-step transition. If necessary, revise your answer to question 1.3. -/ lemma small_step_mess_decreases {Ss Tt : stmt × state} (h : Ss ⇒ Tt) : mess (prod.fst Ss) > mess (prod.fst Tt) := by induction' h; simp [mess, mul_add, add_mul] at *; linarith /- 1.6 (1 bonus point). Prove that the inverse of the `⇒` relation is well founded. The inverse is simply `λTt Ss, Ss ⇒ Tt`. A relation `≺` is well founded if there exist no infinite left-descending chains of the form `⋯ ≺ x₂ ≺ x₁ ≺ x₀` Proof strategy: The `measure` function from `mathlib` converts a function to `ℕ` to a relation, using `<` to compare two numbers. Hence, start by proving that `measure mess`, or rather `measure (mess ∘ prod.fst)`, is well founded. Here, `library_search` can help, or just search manually in `wf.lean`, close to the definition of `measure`. Then prove that `λTt Ss, Ss ⇒ Tt` is a subrelation of `measure (mess ∘ prod.fst)` (using lemma `small_step_mess_decreases` from question 1.5) and therefore (using another lemma from `wf.lean`) that it must be well founded. -/ lemma small_step_wf : well_founded (λTt Ss, Ss ⇒ Tt) := begin apply subrelation.wf _ (measure_wf (mess ∘ prod.fst)), rw subrelation, intros x y h, rw measure, rw inv_image, exact small_step_mess_decreases h end /- ## Question 2 (3 points): Inversion Rules 2.1 (1 point). Prove the following inversion rule for the big-step semantics of `unless`. -/ lemma big_step_ite_iff {b S s t} : (stmt.unless b S, s) ⟹ t ↔ (b s ∧ s = t) ∨ (¬ b s ∧ (S, s) ⟹ t) := begin apply iff.intro, { intro h, cases' h; cc }, { intro h, cases' h; cases' h, { cases' right, apply big_step.unless_true, assumption }, { apply big_step.unless_false; assumption } } end /- 2.2 (2 points). Prove the following inversion rule for the big-step semantics of `repeat`. -/ lemma big_step_repeat_iff {n S s u} : (stmt.repeat n S, s) ⟹ u ↔ (n = 0 ∧ u = s) ∨ (∃m t, n = m + 1 ∧ (S, s) ⟹ t ∧ (stmt.repeat m S, t) ⟹ u) := begin apply iff.intro, { intro h, cases' h, case repeat_zero { apply or.intro_left, apply and.intro; refl }, case repeat_succ : m S t' t u hS hr { apply or.intro_right, apply exists.intro m, apply exists.intro t, repeat { apply and.intro }, { refl }, repeat { assumption } } }, { intro h, cases' h, case inl { cases' h with hn hu, cases' hn, cases' hu, apply big_step.repeat_zero }, case inr { cases' h with m h, cases' h with t h, cases' h with hn h, cases' h with hS hr, rw hn, rw ←nat.succ_eq_add_one, exact big_step.repeat_succ hS hr } } end end LoVe
e53219ba8890354db10effafea78030ea7ba9d88
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/module/pi.lean
5ab8521fc21cf29140995e5038051f04e30559be
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
2,904
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.module.basic algebra.ring.pi /-! # Pi instances for module and multiplicative actions This file defines instances for module, mul_action and related structures on Pi Types -/ namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) instance has_scalar {α : Type*} [Π i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp] lemma smul_apply {α : Type*} [Π i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance has_scalar' {g : I → Type*} [Π i, has_scalar (f i) (g i)] : has_scalar (Π i, f i) (Π i : I, g i) := ⟨λ s x, λ i, (s i) • (x i)⟩ @[simp] lemma smul_apply' {g : I → Type*} [∀ i, has_scalar (f i) (g i)] (s : Π i, f i) (x : Π i, g i) : (s • x) i = s i • x i := rfl instance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] : @mul_action α (Π i : I, f i) m := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] : @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul _ _ } instance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i} [∀ i, distrib_mul_action α $ f i] : @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } instance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i} [Π i, distrib_mul_action (f i) (g i)] : @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) := { smul_add := by { intros, ext x, apply smul_add }, smul_zero := by { intros, ext x, apply smul_zero } } variables (I f) instance semimodule (α) {r : semiring α} {m : ∀ i, add_comm_monoid $ f i} [∀ i, semimodule α $ f i] : @semimodule α (Π i : I, f i) r (@pi.add_comm_monoid I f m) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance semimodule' {g : I → Type*} {r : Π i, semiring (f i)} {m : Π i, add_comm_monoid (g i)} [Π i, semimodule (f i) (g i)] : semimodule (Π i, f i) (Π i, g i) := { add_smul := by { intros, ext1, apply add_smul }, zero_smul := by { intros, ext1, apply zero_smul } } end pi
0cd47b1623bbbc003ab14610acc8cf996685a96a
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/sum.lean
f0c83d8668e95f8d50d99ee9cabe1ccc3ce97ec9
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
3,346
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro More theorems about the sum type. -/ universes u v variables {α : Type u} {β : Type v} open sum attribute [derive decidable_eq] sum @[simp] theorem sum.forall {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ (∀ b, p (inr b)) := ⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩ @[simp] theorem sum.exists {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) := ⟨λ h, match h with | ⟨inl a, h⟩ := or.inl ⟨a, h⟩ | ⟨inr b, h⟩ := or.inr ⟨b, h⟩ end, λ h, match h with | or.inl ⟨a, h⟩ := ⟨inl a, h⟩ | or.inr ⟨b, h⟩ := ⟨inr b, h⟩ end⟩ namespace sum @[simp] theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b := ⟨inl.inj, congr_arg _⟩ @[simp] theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b := ⟨inr.inj, congr_arg _⟩ @[simp] theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b. @[simp] theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a. section variables (ra : α → α → Prop) (rb : β → β → Prop) /-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`, otherwise use the respective order on `α` or `β`. -/ inductive lex : α ⊕ β → α ⊕ β → Prop | inl {a₁ a₂} (h : ra a₁ a₂) : lex (inl a₁) (inl a₂) | inr {b₁ b₂} (h : rb b₁ b₂) : lex (inr b₁) (inr b₂) | sep (a b) : lex (inl a) (inr b) variables {ra rb} @[simp] theorem lex_inl_inl {a₁ a₂} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ := ⟨λ h, by cases h; assumption, lex.inl _⟩ @[simp] theorem lex_inr_inr {b₁ b₂} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ := ⟨λ h, by cases h; assumption, lex.inr _⟩ @[simp] theorem lex_inr_inl {b a} : ¬ lex ra rb (inr b) (inl a) := λ h, by cases h attribute [simp] lex.sep theorem lex_acc_inl {a} (aca : acc ra a) : acc (lex ra rb) (inl a) := begin induction aca with a H IH, constructor, intros y h, cases h with a' _ h', exact IH _ h' end theorem lex_acc_inr (aca : ∀ a, acc (lex ra rb) (inl a)) {b} (acb : acc rb b) : acc (lex ra rb) (inr b) := begin induction acb with b H IH, constructor, intros y h, cases h with _ _ _ b' _ h' a, { exact IH _ h' }, { exact aca _ } end theorem lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) := have aca : ∀ a, acc (lex ra rb) (inl a), from λ a, lex_acc_inl (ha.apply a), ⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩ end @[simp] def map {α' β'} (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β' | (sum.inl l) := sum.inl $ f l | (sum.inr r) := sum.inr $ g r /-- Swap the factors of a sum type -/ @[simp] def swap : α ⊕ β → β ⊕ α | (inl a) := inr a | (inr b) := inl b @[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x := by cases x; refl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) := funext $ swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap end sum
7762896b5aaa2843fad360f2b72a2fe6c5e84d69
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/wf2.lean
94bc3a290726f1cc046410495ee6e96ed0f7e736
[ "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
127
lean
def g (x : Nat) (y : Nat) : Nat := if x < y then 2 * g (x-1) y -- Error here else 0 termination_by' measure (·.1)
1173bdcb6e382061bb8fbe1d6a7a3f1bd7432e40
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/logic.hlean
a422a9e5be7c389a8072fe7ce1bc027ac92a7329
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
257
hlean
--javra: Maybe this should go somewhere else open eq inductive tdecidable [class] (A : Type) : Type := inl : A → tdecidable A, inr : ¬A → tdecidable A structure decidable_paths [class] (A : Type) := (elim : ∀(x y : A), tdecidable (x = y))
c942da4141d27e2a7446a407ade2a68e1a15862a
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/algebra/group/units_hom.lean
e93fc416bd3230e7122251d508b890d4f73d5463
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
1,522
lean
/- Copyright (c) 2018 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes, Kevin Buzzard Lift monoid homomorphisms to group homomorphisms of their units subgroups. -/ import algebra.group.units algebra.group.hom universes u v w namespace units variables {α : Type u} {β : Type v} {γ : Type w} [monoid α] [monoid β] [monoid γ] def map (f : α →* β) : units α →* units β := monoid_hom.mk' (λ u, ⟨f u.val, f u.inv, by rw [← f.map_mul, u.val_inv, f.map_one], by rw [← f.map_mul, u.inv_val, f.map_one]⟩) (λ x y, ext (f.map_mul x y)) @[reducible] def map' (f : α → β) [is_monoid_hom f] : units α →* units β := map (as_monoid_hom f) @[simp] lemma coe_map (f : α →* β) (x : units α) : ↑(map f x) = f x := rfl @[simp] lemma coe_map' (f : α → β) [is_monoid_hom f] (x : units α) : ↑((map' f : units α → units β) x) = f x := rfl @[simp] lemma map_comp (f : α →* β) (g : β →* γ) : map (g.comp f) = (map g).comp (map f) := rfl variables (α) @[simp] lemma map_id : map (monoid_hom.id α) = monoid_hom.id (units α) := by ext; refl /-- Coercion `units α → α` as a monoid homomorphism. -/ def coe_hom : units α →* α := ⟨coe, coe_one, coe_mul⟩ @[simp] lemma coe_hom_apply (x : units α) : coe_hom α x = ↑x := rfl instance coe_is_monoid_hom : is_monoid_hom (coe : units α → α) := (coe_hom α).is_monoid_hom end units
f7dd7ec2f0780d2e91becc57f6ce5376124c2ed9
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/tests/lean/run/matchtac.lean
1c3ef45d3621c9f50f368db16ec52661b03bb6c7
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
2,573
lean
theorem tst1 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by match h:xs with | [] => exact h₂ h | z::zs => apply h₁ z zs; assumption theorem tst2 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by match h:xs with | [] => ?nilCase | z::zs => ?consCase; case consCase => exact h₁ z zs h; case nilCase => exact h₂ h def tst3 {α β γ : Type} (h : α × β × γ) : β × α × γ := by { match h with | (a, b, c) => exact (b, a, c) } theorem tst4 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by match h:xs with | [] => _ | z::zs => _ case match_2 => exact h₁ z zs h exact h₂ h theorem tst5 {p q r} (h : p ∨ q ∨ r) : r ∨ q ∨ p:= by match h with | Or.inl h => exact Or.inr (Or.inr h) | Or.inr (Or.inl h) => ?c1 | Or.inr (Or.inr h) => ?c2 case c2 => apply Or.inl assumption case c1 => apply Or.inr apply Or.inl assumption theorem tst6 {p q r} (h : p ∨ q ∨ r) : r ∨ q ∨ p:= by match h with | Or.inl h => exact Or.inr (Or.inr h) | Or.inr (Or.inl h) => ?c1 | Or.inr (Or.inr h) => apply Or.inl assumption case c1 => apply Or.inr; apply Or.inl; assumption theorem tst7 {p q r} (h : p ∨ q ∨ r) : r ∨ q ∨ p:= by match h with | Or.inl h => exact Or.inr (Or.inr h) | Or.inr (Or.inl h) => apply Or.inr; apply Or.inl; assumption | Or.inr (Or.inr h) => apply Or.inl; assumption inductive ListLast.{u} {α : Type u} : List α → Type u | empty : ListLast [] | nonEmpty : (as : List α) → (a : α) → ListLast (as ++ [a]) axiom last {α} (xs : List α) : ListLast xs axiom back {α} [Inhabited α] (xs : List α) : α axiom popBack {α} : List α → List α axiom backEq {α} [Inhabited α] : (xs : List α) → (x : α) → back (xs ++ [x]) = x axiom popBackEq {α} : (xs : List α) → (x : α) → popBack (xs ++ [x]) = xs theorem tst8 {α} [Inhabited α] (xs : List α) : xs ≠ [] → xs = popBack xs ++ [back xs] := match xs, h:last xs with | _, ListLast.empty => fun h => absurd rfl h | _, ListLast.nonEmpty ys y => fun _ => sorry theorem tst9 {α} [Inhabited α] (xs : List α) : xs ≠ [] → xs = popBack xs ++ [back xs] := by match xs, h:last xs with | _, ListLast.empty => intro h; exact absurd rfl h | _, ListLast.nonEmpty ys y => intro; rw [popBackEq, backEq]
a411710498846a52c5ecafd59e22e49658eaf184
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/group_power/basic.lean
8151f5c4f8c4e942e79c7173fbbf0e6bc480ead3
[ "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
17,364
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.ordered_ring import tactic.monotonicity.basic import group_theory.group_action.defs /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. This module contains the definitions of `monoid.pow` and `group.pow` and their additive counterparts `nsmul` and `gsmul`, along with a few lemmas. Further lemmas can be found in `algebra.group_power.lemmas`. ## Notation The class `has_pow α β` provides the notation `a^b` for powers. We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`. Scalar multiplication by naturals and integers is handled by the `•` (`has_scalar.smul`) notation defined elsewhere. ## Implementation details We adopt the convention that `0^0 = 1`. This module provides the instance `has_pow ℕ ℕ` (via `monoid.has_pow`) and is imported by `data.nat.basic`, so it has to live low in the import hierarchy. Not all of its imports are needed yet; the intent is to move more lemmas here from `.lemmas` so that they are available in `data.nat.basic`, and the imports will be required then. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨λ x n, npow n x⟩ instance add_monoid.has_scalar_nat [add_monoid M] : has_scalar ℕ M := ⟨nsmul⟩ attribute [to_additive add_monoid.has_scalar_nat] monoid.has_pow instance div_inv_monoid.has_pow [div_inv_monoid M] : has_pow M ℤ := ⟨λ x n, gpow n x⟩ instance sub_neg_monoid.has_scalar_int [sub_neg_monoid M] : has_scalar ℤ M := ⟨gsmul⟩ attribute [to_additive sub_neg_monoid.has_scalar_int] div_inv_monoid.has_pow @[simp, to_additive nsmul_eq_smul] lemma npow_eq_pow {M : Type*} [monoid M] (n : ℕ) (x : M) : npow n x = x^n := rfl @[simp, to_additive gsmul_eq_smul] lemma gpow_eq_pow {M : Type*} [div_inv_monoid M] (n : ℤ) (x : M) : gpow n x = x^n := rfl /-! ### Commutativity First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about `pow` and/or `nsmul` and will be useful later in this file. -/ namespace semiconj_by variables [monoid M] attribute [to_additive add_monoid.nsmul_zero'] monoid.npow_zero' @[simp, to_additive] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) := begin induction n with n ih, { simp [← npow_eq_pow, monoid.npow_zero'], }, { simp only [← npow_eq_pow, nat.succ_eq_add_one, npow_one, npow_add] at ⊢ ih, exact ih.mul_right h } end end semiconj_by namespace commute variables [monoid M] {a b : M} @[simp, to_additive] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n @[simp, to_additive] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm @[simp, to_additive] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) := (h.pow_left m).pow_right n @[simp, to_additive] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n @[simp, to_additive] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n @[simp, to_additive] theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) := (commute.refl a).pow_pow m n end commute section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] -- the attributes are intentionally out of order. `zero_smul` proves `zero_nsmul`. @[to_additive zero_nsmul, simp] theorem pow_zero (a : M) : a^0 = 1 := monoid.npow_zero' _ @[to_additive succ_nsmul] theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := by rw [← npow_eq_pow, nat.add_comm, npow_add, npow_one, npow_eq_pow] /-- Note that most of the lemmas about powers of two refer to it as `sq`. -/ @[to_additive two_nsmul] theorem pow_two (a : M) : a^2 = a * a := by rw [← npow_eq_pow, show 2 = 1 + 1, by refl, npow_add, npow_one] alias pow_two ← sq @[to_additive nsmul_add_comm'] theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n @[to_additive succ_nsmul'] theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] @[to_additive add_nsmul] theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [nat.add_zero, pow_zero, mul_one], rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', nat.add_assoc]] @[simp, to_additive one_nsmul] theorem pow_one (a : M) : a^1 = a := by rw [← npow_eq_pow, npow_one] @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp -- the attributes are intentionally out of order. `smul_zero` proves `nsmul_zero`. @[to_additive nsmul_zero, simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [exact pow_zero _, rw [pow_succ, ih, one_mul]] @[to_additive mul_nsmul'] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := begin induction n with n ih, { rw [nat.mul_zero, pow_zero, pow_zero] }, { rw [nat.mul_succ, pow_add, pow_succ', ih] } end @[to_additive mul_nsmul] theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [nat.mul_comm, pow_mul] @[to_additive nsmul_add_sub_nsmul] theorem pow_mul_pow_sub (a : M) {m n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n := by rw [←pow_add, nat.add_comm, nat.sub_add_cancel h] @[to_additive sub_nsmul_nsmul_add] theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [←pow_add, nat.sub_add_cancel h] @[to_additive bit0_nsmul] theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ @[to_additive bit1_nsmul] theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] @[to_additive nsmul_add_comm] theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n @[simp, to_additive add_monoid_hom.map_nsmul] theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := by rw [pow_zero, pow_zero, f.map_one] | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] @[to_additive] lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := nat.rec_on n (by simp only [pow_zero, one_mul]) $ λ n ihn, by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm] theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n := (neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n @[to_additive bit0_nsmul'] theorem pow_bit0' (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n := by rw [pow_bit0, (commute.refl a).mul_pow] @[to_additive bit1_nsmul'] theorem pow_bit1' (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a := by rw [bit1, pow_succ', pow_bit0'] @[simp] theorem neg_pow_bit0 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit0 n) = a ^ (bit0 n) := by rw [pow_bit0', neg_mul_neg, pow_bit0'] @[simp] theorem neg_pow_bit1 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit1 n) = - a ^ (bit1 n) := by simp only [bit1, pow_succ, neg_pow_bit0, neg_mul_eq_neg_mul] end monoid /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] @[to_additive nsmul_add] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n /-- The `n`th power map on a commutative monoid for a natural `n`, considered as a morphism of monoids. -/ @[to_additive nsmul_add_monoid_hom "Multiplication by a natural `n` on a commutative additive monoid, considered as a morphism of additive monoids.", simps] def pow_monoid_hom (n : ℕ) : M →* M := { to_fun := (^ n), map_one' := one_pow _, map_mul' := λ a b ,mul_pow a b n } -- the below line causes the linter to complain :-/ -- attribute [simps] pow_monoid_hom nsmul_add_monoid_hom lemma dvd_pow {x y : M} : ∀ {n : ℕ} (hxy : x ∣ y) (hn : n ≠ 0), x ∣ y^n | 0 hxy hn := (hn rfl).elim | (n+1) hxy hn := by { rw [pow_succ], exact dvd_mul_of_dvd_left hxy _ } end comm_monoid section div_inv_monoid variable [div_inv_monoid G] open int @[simp, norm_cast, to_additive] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := begin induction n with n ih, { change gpow 0 a = a ^ 0, rw [div_inv_monoid.gpow_zero', pow_zero] }, { change gpow (of_nat n) a = a ^ n at ih, change gpow (of_nat n.succ) a = a ^ n.succ, rw [div_inv_monoid.gpow_succ', pow_succ, ih] } end @[to_additive] theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := gpow_coe_nat _ _ @[simp, to_additive] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := by { rw ← gpow_coe_nat, exact div_inv_monoid.gpow_neg' n a } @[simp, to_additive zero_gsmul] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := by { convert pow_zero a using 1, exact gpow_coe_nat a 0 } @[simp, to_additive one_gsmul] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := by { convert pow_one a using 1, exact gpow_coe_nat a 1 } end div_inv_monoid section group variables [group G] [group H] [add_group A] [add_group B] open int section nat @[simp, to_additive neg_nsmul] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := begin induction n with n ih, { rw [pow_zero, pow_zero, one_inv] }, { rw [pow_succ', pow_succ, ih, mul_inv_rev] } end @[to_additive nsmul_sub] -- rename to sub_nsmul? theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 @[to_additive nsmul_neg_comm] theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := (commute.refl a).inv_left.pow_pow m n end nat @[simp, to_additive gsmul_zero] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := by rw [gpow_coe_nat, one_pow] | -[1+ n] := by rw [gpow_neg_succ_of_nat, one_pow, one_inv] @[simp, to_additive neg_gsmul] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := div_inv_monoid.gpow_neg' _ _ | 0 := by { change a ^ (0 : ℤ) = (a ^ (0 : ℤ))⁻¹, simp } | -[1+ n] := by { rw [gpow_neg_succ_of_nat, inv_inv, ← gpow_coe_nat], refl } lemma mul_gpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) := by simp only [mul_inv_rev, gpow_one, gpow_neg] @[to_additive neg_one_gsmul] theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := by { rw [← congr_arg has_inv.inv (pow_one x), gpow_neg, ← gpow_coe_nat], refl } @[to_additive gsmul_neg] theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := by rw [gpow_coe_nat, gpow_coe_nat, inv_pow] | -[1+ n] := by rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, inv_pow] @[to_additive add_commute.gsmul_add] theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n | (n : ℕ) := by simp [gpow_coe_nat, h.mul_pow n] | -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq] end group section comm_group variables [comm_group G] [add_comm_group A] @[to_additive gsmul_add] theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n @[to_additive gsmul_sub] theorem div_gpow (a b : G) (n : ℤ) : (a / b) ^ n = a ^ n / b ^ n := by rw [div_eq_mul_inv, div_eq_mul_inv, mul_gpow, inv_gpow] /-- The `n`th power map (`n` an integer) on a commutative group, considered as a group homomorphism. -/ @[to_additive "Multiplication by an integer `n` on a commutative additive group, considered as an additive group homomorphism.", simps] def gpow_group_hom (n : ℤ) : G →* G := { to_fun := (^ n), map_one' := one_gpow n, map_mul' := λ a b, mul_gpow a b n } end comm_group lemma zero_pow [monoid_with_zero R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := by rw [pow_succ, zero_mul] lemma zero_pow_eq [monoid_with_zero R] (n : ℕ) : (0 : R)^n = if n = 0 then 1 else 0 := begin split_ifs with h, { rw [h, pow_zero], }, { rw [zero_pow (nat.pos_of_ne_zero h)] }, end lemma pow_eq_zero_of_le [monoid_with_zero M] {x : M} {n m : ℕ} (hn : n ≤ m) (hx : x^n = 0) : x^m = 0 := by rw [← nat.sub_add_cancel hn, pow_add, hx, mul_zero] namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a end ring_hom section variables (R) theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl (pow_zero _) | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) end @[simp] lemma neg_one_pow_mul_eq_zero_iff [ring R] {n : ℕ} {r : R} : (-1)^n * r = 0 ↔ r = 0 := by rcases neg_one_pow_eq_or R n; simp [h] @[simp] lemma mul_neg_one_pow_eq_zero_iff [ring R] {n : ℕ} {r : R} : r * (-1)^n = 0 ↔ r = 0 := by rcases neg_one_pow_eq_or R n; simp [h] lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_comm, nat.sub_add_cancel h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := by rw [pow_zero, pow_zero] | (n+1) := by { rw [pow_succ, pow_succ], exact mul_dvd_mul h (pow_dvd_pow_of_dvd n) } lemma sq_sub_sq {R : Type*} [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [sq, sq, mul_self_sub_mul_self] alias sq_sub_sq ← pow_two_sub_pow_two lemma eq_or_eq_neg_of_sq_eq_sq [integral_domain R] (a b : R) (h : a ^ 2 = b ^ 2) : a = b ∨ a = -b := by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero, ← sq_sub_sq a b, sub_eq_zero] theorem pow_eq_zero [monoid_with_zero R] [no_zero_divisors R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, { rw pow_succ at H, exact or.cases_on (mul_eq_zero.1 H) id ih } end @[simp] lemma pow_eq_zero_iff [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨pow_eq_zero, _⟩, rintros rfl, exact zero_pow hn, end lemma pow_ne_zero_iff [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n ≠ 0 ↔ a ≠ 0 := by rwa [not_iff_not, pow_eq_zero_iff] @[field_simps] theorem pow_ne_zero [monoid_with_zero R] [no_zero_divisors R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h section semiring variables [semiring R] lemma min_pow_dvd_add {n m : ℕ} {a b c : R} (ha : c ^ n ∣ a) (hb : c ^ m ∣ b) : c ^ (min n m) ∣ a + b := begin replace ha := dvd.trans (pow_dvd_pow c (min_le_left n m)) ha, replace hb := dvd.trans (pow_dvd_pow c (min_le_right n m)) hb, exact dvd_add ha hb end end semiring section comm_semiring variables [comm_semiring R] lemma add_sq (a b : R) : (a + b) ^ 2 = a ^ 2 + 2 * a * b + b ^ 2 := by simp only [sq, add_mul_self_eq] alias add_sq ← add_pow_two end comm_semiring @[simp] lemma neg_sq {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [sq] alias neg_sq ← neg_pow_two lemma sub_sq {R} [comm_ring R] (a b : R) : (a - b) ^ 2 = a ^ 2 - 2 * a * b + b ^ 2 := by rw [sub_eq_add_neg, add_sq, neg_sq, mul_neg_eq_neg_mul_symm, ← sub_eq_add_neg] alias sub_sq ← sub_pow_two lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl lemma of_mul_pow {A : Type*} [monoid A] (x : A) (n : ℕ) : additive.of_mul (x ^ n) = n • (additive.of_mul x) := rfl lemma of_mul_gpow [group G] (x : G) (n : ℤ) : additive.of_mul (x ^ n) = n • additive.of_mul x := rfl @[simp] lemma semiconj_by.gpow_right [group G] {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := by simp [gpow_coe_nat, h.pow_right n] | -[1+n] := by simp [(h.pow_right n.succ).inv_right] namespace commute variables [group G] {a b : G} @[simp] lemma gpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.gpow_right m @[simp] lemma gpow_left (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.gpow_right m).symm lemma gpow_gpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.gpow_left m).gpow_right n variables (a) (m n : ℤ) @[simp] theorem self_gpow : commute a (a ^ n) := (commute.refl a).gpow_right n @[simp] theorem gpow_self : commute (a ^ n) a := (commute.refl a).gpow_left n @[simp] theorem gpow_gpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).gpow_gpow m n end commute
dbdd0750ce451e70b146f7a2a60961a49a18e9bc
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/e5.lean
559ea6fd36025c80e19b83444a52ee2548ae1818
[ "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
1,533
lean
prelude definition Prop := Type.{0} definition false : Prop := ∀x : Prop, x check false theorem false.elim (C : Prop) (H : false) : C := H C definition eq {A : Type} (a b : A) := ∀ P : A → Prop, P a → P b check eq infix `=`:50 := eq theorem refl {A : Type} (a : A) : a = a := λ P H, H definition true : Prop := false = false theorem trivial : true := refl false theorem subst {A : Type} {P : A -> Prop} {a b : A} (H1 : a = b) (H2 : P a) : P b := H1 _ H2 theorem symm {A : Type} {a b : A} (H : a = b) : b = a := subst H (refl a) theorem trans {A : Type} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c := subst H2 H1 inductive nat : Type := | zero : nat | succ : nat → nat namespace nat end nat open nat print "using strict implicit arguments" definition symmetric {A : Type} (R : A → A → Prop) := ∀ ⦃a b⦄, R a b → R b a check symmetric constant p : nat → nat → Prop check symmetric p axiom H1 : symmetric p axiom H2 : p zero (succ zero) check H1 check H1 H2 print "------------" print "using implicit arguments" definition symmetric2 {A : Type} (R : A → A → Prop) := ∀ {a b}, R a b → R b a check symmetric2 check symmetric2 p axiom H3 : symmetric2 p axiom H4 : p zero (succ zero) check H3 check H3 H4 print "-----------------" print "using strict implicit arguments (ASCII notation)" definition symmetric3 {A : Type} (R : A → A → Prop) := ∀ {{a b}}, R a b → R b a check symmetric3 check symmetric3 p axiom H5 : symmetric3 p axiom H6 : p zero (succ zero) check H5 check H5 H6
f41544ff989fb7574b1a14be2ea0c9b584fe4676
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/category/CommRing/basic.lean
f4e8a28e7111528ec1375c405df2b31d8b35fffc
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
7,229
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Yury Kudryashov -/ import algebra.category.Group import data.equiv.ring /-! # Category instances for semiring, ring, comm_semiring, and comm_ring. We introduce the bundled categories: * `SemiRing` * `Ring` * `CommSemiRing` * `CommRing` along with the relevant forgetful functors between them. ## Implementation notes See the note [locally reducible category instances]. -/ universes u v open category_theory /-- The category of semirings. -/ def SemiRing : Type (u+1) := bundled semiring namespace SemiRing /-- Construct a bundled SemiRing from the underlying type and typeclass. -/ def of (R : Type u) [semiring R] : SemiRing := bundled.of R instance : inhabited SemiRing := ⟨of punit⟩ local attribute [reducible] SemiRing instance : has_coe_to_sort SemiRing := infer_instance -- short-circuit type class inference instance (R : SemiRing) : semiring R := R.str instance bundled_hom : bundled_hom @ring_hom := ⟨@ring_hom.to_fun, @ring_hom.id, @ring_hom.comp, @ring_hom.coe_inj⟩ instance : category SemiRing := infer_instance -- short-circuit type class inference instance : concrete_category SemiRing := infer_instance -- short-circuit type class inference instance has_forget_to_Mon : has_forget₂ SemiRing Mon := bundled_hom.mk_has_forget₂ @semiring.to_monoid (λ R₁ R₂, ring_hom.to_monoid_hom) (λ _ _ _, rfl) instance has_forget_to_AddCommMon : has_forget₂ SemiRing AddCommMon := -- can't use bundled_hom.mk_has_forget₂, since AddCommMon is an induced category { forget₂ := { obj := λ R, AddCommMon.of R, map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } } end SemiRing /-- The category of rings. -/ def Ring : Type (u+1) := bundled ring namespace Ring instance : bundled_hom.parent_projection @ring.to_semiring := ⟨⟩ /-- Construct a bundled Ring from the underlying type and typeclass. -/ def of (R : Type u) [ring R] : Ring := bundled.of R instance : inhabited Ring := ⟨of punit⟩ local attribute [reducible] Ring instance : has_coe_to_sort Ring := by apply_instance -- short-circuit type class inference instance (R : Ring) : ring R := R.str instance : category Ring := infer_instance -- short-circuit type class inference instance : concrete_category Ring := infer_instance -- short-circuit type class inference instance has_forget_to_SemiRing : has_forget₂ Ring SemiRing := bundled_hom.forget₂ _ _ instance has_forget_to_AddCommGroup : has_forget₂ Ring AddCommGroup := -- can't use bundled_hom.mk_has_forget₂, since AddCommGroup is an induced category { forget₂ := { obj := λ R, AddCommGroup.of R, map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } } end Ring /-- The category of commutative semirings. -/ def CommSemiRing : Type (u+1) := bundled comm_semiring namespace CommSemiRing instance : bundled_hom.parent_projection @comm_semiring.to_semiring := ⟨⟩ /-- Construct a bundled CommSemiRing from the underlying type and typeclass. -/ def of (R : Type u) [comm_semiring R] : CommSemiRing := bundled.of R instance : inhabited CommSemiRing := ⟨of punit⟩ local attribute [reducible] CommSemiRing instance : has_coe_to_sort CommSemiRing := infer_instance -- short-circuit type class inference instance (R : CommSemiRing) : comm_semiring R := R.str instance : category CommSemiRing := infer_instance -- short-circuit type class inference instance : concrete_category CommSemiRing := infer_instance -- short-circuit type class inference instance has_forget_to_SemiRing : has_forget₂ CommSemiRing SemiRing := bundled_hom.forget₂ _ _ /-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/ instance has_forget_to_CommMon : has_forget₂ CommSemiRing CommMon := has_forget₂.mk' (λ R : CommSemiRing, CommMon.of R) (λ R, rfl) (λ R₁ R₂ f, f.to_monoid_hom) (by tidy) end CommSemiRing /-- The category of commutative rings. -/ def CommRing : Type (u+1) := bundled comm_ring namespace CommRing instance : bundled_hom.parent_projection @comm_ring.to_ring := ⟨⟩ /-- Construct a bundled CommRing from the underlying type and typeclass. -/ def of (R : Type u) [comm_ring R] : CommRing := bundled.of R instance : inhabited CommRing := ⟨of punit⟩ local attribute [reducible] CommRing instance : has_coe_to_sort CommRing := infer_instance -- short-circuit type class inference instance (R : CommRing) : comm_ring R := R.str instance : category CommRing := infer_instance -- short-circuit type class inference instance : concrete_category CommRing := infer_instance -- short-circuit type class inference instance has_forget_to_Ring : has_forget₂ CommRing Ring := bundled_hom.forget₂ _ _ /-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/ instance has_forget_to_CommSemiRing : has_forget₂ CommRing CommSemiRing := has_forget₂.mk' (λ R : CommRing, CommSemiRing.of R) (λ R, rfl) (λ R₁ R₂ f, f) (by tidy) end CommRing -- This example verifies an improvement possible in Lean 3.8. -- Before that, to have `add_ring_hom.map_zero` usable by `simp` here, -- we had to mark all the concrete category `has_coe_to_sort` instances reducible. -- Now, it just works. example {R S : CommRing} (i : R ⟶ S) (r : R) (h : r = 0) : i r = 0 := by simp [h] namespace ring_equiv variables {X Y : Type u} /-- Build an isomorphism in the category `Ring` from a `ring_equiv` between `ring`s. -/ @[simps] def to_Ring_iso [ring X] [ring Y] (e : X ≃+* Y) : Ring.of X ≅ Ring.of Y := { hom := e.to_ring_hom, inv := e.symm.to_ring_hom } /-- Build an isomorphism in the category `CommRing` from a `ring_equiv` between `comm_ring`s. -/ @[simps] def to_CommRing_iso [comm_ring X] [comm_ring Y] (e : X ≃+* Y) : CommRing.of X ≅ CommRing.of Y := { hom := e.to_ring_hom, inv := e.symm.to_ring_hom } end ring_equiv namespace category_theory.iso /-- Build a `ring_equiv` from an isomorphism in the category `Ring`. -/ def Ring_iso_to_ring_equiv {X Y : Ring} (i : X ≅ Y) : X ≃+* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_mul' := by tidy }. /-- Build a `ring_equiv` from an isomorphism in the category `CommRing`. -/ def CommRing_iso_to_ring_equiv {X Y : CommRing} (i : X ≅ Y) : X ≃+* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_mul' := by tidy }. end category_theory.iso /-- ring equivalences between `ring`s are the same as (isomorphic to) isomorphisms in `Ring`. -/ def ring_equiv_iso_Ring_iso {X Y : Type u} [ring X] [ring Y] : (X ≃+* Y) ≅ (Ring.of X ≅ Ring.of Y) := { hom := λ e, e.to_Ring_iso, inv := λ i, i.Ring_iso_to_ring_equiv, } /-- ring equivalences between `comm_ring`s are the same as (isomorphic to) isomorphisms in `CommRing`. -/ def ring_equiv_iso_CommRing_iso {X Y : Type u} [comm_ring X] [comm_ring Y] : (X ≃+* Y) ≅ (CommRing.of X ≅ CommRing.of Y) := { hom := λ e, e.to_CommRing_iso, inv := λ i, i.CommRing_iso_to_ring_equiv, }
cdc8f90a3dc1898647ef093fcc9a351d3503d756
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/parity.lean
0e2077bf429fce716e9043f19df46f978a384db0
[ "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
13,665
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.ring.basic import algebra.algebra.basic import algebra.group_power.basic import algebra.field_power import algebra.opposites /-! # Squares, even and odd elements This file proves some general facts about squares, even and odd elements of semirings. In the implementation, we define `is_square` and we let `even` be the notion transported by `to_additive`. The definition are therefore as follows: ```lean is_square a ↔ ∃ r, a = r * r even a ↔ ∃ r, a = r + r ``` Odd elements are not unified with a multiplicative notion. ## Future work * TODO: Try to generalize further the typeclass assumptions on `is_square/even`. For instance, in some cases, there are `semiring` assumptions that I (DT) am not convinced are necessary. * TODO: Consider moving the definition and lemmas about `odd` to a separate file. * TODO: The "old" definition of `even a` asked for the existence of an element `c` such that `a = 2 * c`. For this reason, several fixes introduce an extra `two_mul` or `← two_mul`. It might be the case that by making a careful choice of `simp` lemma, this can be avoided. -/ open mul_opposite variables {F α β R : Type*} /-- An element `a` of a type `α` with multiplication satisfies `square a` if `a = r * r`, for some `r : α`. -/ @[to_additive "An element `a` of a type `α` with addition satisfies `even a` if `a = r + r`, for some `r : α`."] def is_square [has_mul α] (a : α) : Prop := ∃ r, a = r * r @[simp, to_additive] lemma is_square_mul_self [has_mul α] (m : α) : is_square (m * m) := ⟨m, rfl⟩ @[to_additive even_iff_exists_two_nsmul] lemma is_square_iff_exists_sq [monoid α] (m : α) : is_square m ↔ ∃ c, m = c ^ 2 := by simp [is_square, pow_two] alias is_square_iff_exists_sq ↔ is_square.exists_sq is_square_of_exists_sq attribute [to_additive even.exists_two_nsmul "Alias of the forwards direction of `even_iff_exists_two_nsmul`."] is_square.exists_sq attribute [to_additive even_of_exists_two_nsmul "Alias of the backwards direction of `even_iff_exists_two_nsmul`."] is_square_of_exists_sq @[simp, to_additive] lemma is_square_one [mul_one_class α] : is_square (1 : α) := ⟨1, (mul_one _).symm⟩ @[to_additive] lemma is_square.map [mul_one_class α] [mul_one_class β] [monoid_hom_class F α β] {m : α} (f : F) : is_square m → is_square (f m) := by { rintro ⟨m, rfl⟩, exact ⟨f m, by simp⟩ } /-- Create a decidability instance for `is_square` on `fintype`s. -/ instance is_square_decidable [fintype α] [has_mul α] [decidable_eq α] : decidable_pred (is_square : α → Prop) := λ a, fintype.decidable_exists_fintype section monoid variables [monoid α] @[simp, to_additive even_two_nsmul] lemma is_square_sq (a : α) : is_square (a ^ 2) := ⟨a, pow_two _⟩ variables [has_distrib_neg α] {n : ℕ} lemma even.neg_pow : even n → ∀ a : α, (-a) ^ n = a ^ n := by { rintro ⟨c, rfl⟩ a, simp_rw [←two_mul, pow_mul, neg_sq] } lemma even.neg_one_pow (h : even n) : (-1 : α) ^ n = 1 := by rw [h.neg_pow, one_pow] /-- `0` is always a square (in a monoid with zero). -/ lemma is_square_zero (M : Type*) [monoid_with_zero M] : is_square (0 : M) := by { use 0, simp only [mul_zero] } end monoid @[to_additive] lemma is_square.mul_is_square [comm_monoid α] {m n : α} (hm : is_square m) (hn : is_square n) : is_square (m * n) := begin rcases hm with ⟨m, rfl⟩, rcases hn with ⟨n, rfl⟩, refine ⟨m * n, mul_mul_mul_comm m m n n⟩, end section group variable [group α] @[to_additive] lemma is_square_op_iff (a : α) : is_square (op a) ↔ is_square a := ⟨λ ⟨c, hc⟩, ⟨unop c, by rw [← unop_mul, ← hc, unop_op]⟩, λ ⟨c, hc⟩, by simp [hc]⟩ @[simp, to_additive] lemma is_square_inv (a : α) : is_square a⁻¹ ↔ is_square a := begin refine ⟨λ h, _, λ h, _⟩, { rw [← is_square_op_iff, ← inv_inv a], exact h.map (mul_equiv.inv' α) }, { exact ((is_square_op_iff a).mpr h).map (mul_equiv.inv' α).symm } end end group section comm_group variable [comm_group α] @[to_additive] lemma is_square.div_is_square {m n : α} (hm : is_square m) (hn : is_square n) : is_square (m / n) := by { rw div_eq_mul_inv, exact hm.mul_is_square ((is_square_inv n).mpr hn) } end comm_group -- `odd.tsub_odd` requires `canonically_linear_ordered_semiring`, which we don't have lemma even.tsub_even [canonically_linear_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] [contravariant_class α α (+) (≤)] {m n : α} (hm : even m) (hn : even n) : even (m - n) := begin obtain ⟨a, rfl⟩ := hm, obtain ⟨b, rfl⟩ := hn, refine ⟨a - b, _⟩, obtain h | h := le_total a b, { rw [tsub_eq_zero_of_le h, tsub_eq_zero_of_le (add_le_add h h), add_zero] }, { exact (tsub_add_tsub_comm h h).symm } end lemma even_iff_exists_bit0 [has_add α] {a : α} : even a ↔ ∃ b, a = bit0 b := iff.rfl alias even_iff_exists_bit0 ↔ even.exists_bit0 _ section semiring variables [semiring α] [semiring β] {m n : α} lemma even_iff_exists_two_mul (m : α) : even m ↔ ∃ c, m = 2 * c := by simp [even_iff_exists_two_nsmul] lemma even_iff_two_dvd {a : α} : even a ↔ 2 ∣ a := by simp [even, has_dvd.dvd, two_mul] @[simp] lemma range_two_mul (α : Type*) [semiring α] : set.range (λ x : α, 2 * x) = {a | even a} := by { ext x, simp [eq_comm, two_mul, even] } @[simp] lemma even_bit0 (a : α) : even (bit0 a) := ⟨a, rfl⟩ @[simp] lemma even_two : even (2 : α) := ⟨1, rfl⟩ @[simp] lemma even.mul_left (hm : even m) (n) : even (n * m) := hm.map (add_monoid_hom.mul_left n) @[simp] lemma even.mul_right (hm : even m) (n) : even (m * n) := hm.map (add_monoid_hom.mul_right n) lemma even_two_mul (m : α) : even (2 * m) := ⟨m, two_mul _⟩ lemma even.pow_of_ne_zero (hm : even m) : ∀ {a : ℕ}, a ≠ 0 → even (m ^ a) | 0 a0 := (a0 rfl).elim | (a + 1) _ := by { rw pow_succ, exact hm.mul_right _ } section with_odd /-- An element `a` of a semiring is odd if there exists `k` such `a = 2*k + 1`. -/ def odd (a : α) : Prop := ∃ k, a = 2*k + 1 lemma odd_iff_exists_bit1 {a : α} : odd a ↔ ∃ b, a = bit1 b := exists_congr $ λ b, by { rw two_mul, refl } alias odd_iff_exists_bit1 ↔ odd.exists_bit1 _ @[simp] lemma odd_bit1 (a : α) : odd (bit1 a) := odd_iff_exists_bit1.2 ⟨a, rfl⟩ @[simp] lemma range_two_mul_add_one (α : Type*) [semiring α] : set.range (λ x : α, 2 * x + 1) = {a | odd a} := by { ext x, simp [odd, eq_comm] } lemma even.add_odd (hm : even m) (hn : odd n) : odd (m + n) := begin rcases hm with ⟨m, rfl⟩, rcases hn with ⟨n, rfl⟩, exact ⟨m + n, by rw [mul_add, ← two_mul, add_assoc]⟩ end lemma odd.add_even (hm : odd m) (hn : even n) : odd (m + n) := by { rw add_comm, exact hn.add_odd hm } lemma odd.add_odd (hm : odd m) (hn : odd n) : even (m + n) := begin rcases hm with ⟨m, rfl⟩, rcases hn with ⟨n, rfl⟩, refine ⟨n + m + 1, _⟩, rw [← two_mul, ←add_assoc, add_comm _ (2 * n), ←add_assoc, ←mul_add, add_assoc, mul_add _ (n + m), mul_one], refl end @[simp] lemma odd_one : odd (1 : α) := ⟨0, (zero_add _).symm.trans (congr_arg (+ (1 : α)) (mul_zero _).symm)⟩ @[simp] lemma odd_two_mul_add_one (m : α) : odd (2 * m + 1) := ⟨m, rfl⟩ lemma ring_hom.odd (f : α →+* β) (hm : odd m) : odd (f m) := begin rcases hm with ⟨m, rfl⟩, exact ⟨f m, by simp [two_mul]⟩ end @[simp] lemma odd.mul_odd (hm : odd m) (hn : odd n) : odd (m * n) := begin rcases hm with ⟨m, rfl⟩, rcases hn with ⟨n, rfl⟩, refine ⟨2 * m * n + n + m, _⟩, rw [mul_add, add_mul, mul_one, ← add_assoc, one_mul, mul_assoc, ← mul_add, ← mul_add, ← mul_assoc, ← nat.cast_two, ← nat.cast_comm], end lemma odd.pow (hm : odd m) : ∀ {a : ℕ}, odd (m ^ a) | 0 := by { rw pow_zero, exact odd_one } | (a + 1) := by { rw pow_succ, exact hm.mul_odd odd.pow } end with_odd end semiring section monoid variables [monoid α] [has_distrib_neg α] {a : α} {n : ℕ} lemma odd.neg_pow : odd n → ∀ a : α, (-a) ^ n = - a ^ n := by { rintro ⟨c, rfl⟩ a, simp_rw [pow_add, pow_mul, neg_sq, pow_one, mul_neg] } lemma odd.neg_one_pow (h : odd n) : (-1 : α) ^ n = -1 := by rw [h.neg_pow, one_pow] end monoid section ring variables [ring α] {a b : α} {n : ℕ} @[simp] lemma even_neg_two : even (- 2 : α) := by simp only [even_neg, even_two] lemma even_abs [linear_order α] {a : α} : even (|a|) ↔ even a := begin rcases abs_choice a with h | h; rw h, exact even_neg a, end lemma odd.neg (hp : odd a) : odd (-a) := begin obtain ⟨k, hk⟩ := hp, use -(k + 1), rw [mul_neg, mul_add, neg_add, add_assoc, two_mul (1 : α), neg_add, neg_add_cancel_right, ←neg_add, hk], end @[simp] lemma odd_neg (a : α) : odd (-a) ↔ odd a := ⟨λ h, neg_neg a ▸ h.neg, odd.neg⟩ @[simp] lemma odd_neg_one : odd (- 1 : α) := by simp lemma odd.sub_even (ha : odd a) (hb : even b) : odd (a - b) := by { rw sub_eq_add_neg, exact ha.add_even ((even_neg _).mpr hb) } lemma even.sub_odd (ha : even a) (hb : odd b) : odd (a - b) := by { rw sub_eq_add_neg, exact ha.add_odd ((odd_neg _).mpr hb) } lemma odd.sub_odd (ha : odd a) (hb : odd b) : even (a - b) := by { rw sub_eq_add_neg, exact ha.add_odd ((odd_neg _).mpr hb) } lemma odd_abs [linear_order α] {a : α} : odd (abs a) ↔ odd a := by { cases abs_choice a with h h; simp only [h, odd_neg] } end ring section powers variables [linear_ordered_ring R] {a : R} {n : ℕ} lemma even.pow_nonneg (hn : even n) (a : R) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_nonneg a k lemma even.pow_pos (hn : even n) (ha : a ≠ 0) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_pos ha k lemma odd.pow_nonpos (hn : odd n) (ha : a ≤ 0) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonpos_iff.mpr ha lemma odd.pow_neg (hn : odd n) (ha : a < 0) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_neg_iff.mpr ha lemma odd.pow_nonneg_iff (hn : odd n) : 0 ≤ a ^ n ↔ 0 ≤ a := ⟨λ h, le_of_not_lt (λ ha, h.not_lt $ hn.pow_neg ha), λ ha, pow_nonneg ha n⟩ lemma odd.pow_nonpos_iff (hn : odd n) : a ^ n ≤ 0 ↔ a ≤ 0 := ⟨λ h, le_of_not_lt (λ ha, h.not_lt $ pow_pos ha _), hn.pow_nonpos⟩ lemma odd.pow_pos_iff (hn : odd n) : 0 < a ^ n ↔ 0 < a := ⟨λ h, lt_of_not_le (λ ha, h.not_le $ hn.pow_nonpos ha), λ ha, pow_pos ha n⟩ lemma odd.pow_neg_iff (hn : odd n) : a ^ n < 0 ↔ a < 0 := ⟨λ h, lt_of_not_le (λ ha, h.not_le $ pow_nonneg ha _), hn.pow_neg⟩ lemma even.pow_pos_iff (hn : even n) (h₀ : 0 < n) : 0 < a ^ n ↔ a ≠ 0 := ⟨λ h ha, by { rw [ha, zero_pow h₀] at h, exact lt_irrefl 0 h }, hn.pow_pos⟩ lemma even.pow_abs {p : ℕ} (hp : even p) (a : R) : |a| ^ p = a ^ p := begin rw [←abs_pow, abs_eq_self], exact hp.pow_nonneg _ end @[simp] lemma pow_bit0_abs (a : R) (p : ℕ) : |a| ^ bit0 p = a ^ bit0 p := (even_bit0 _).pow_abs _ lemma odd.strict_mono_pow (hn : odd n) : strict_mono (λ a : R, a ^ n) := by cases hn with k hk; simpa only [hk, two_mul] using strict_mono_pow_bit1 _ end powers /-- The cardinality of `fin (bit0 k)` is even, `fact` version. This `fact` is needed as an instance by `matrix.special_linear_group.has_neg`. -/ lemma fintype.card_fin_even {k : ℕ} : fact (even (fintype.card (fin (bit0 k)))) := ⟨by { rw [fintype.card_fin], exact even_bit0 k }⟩ section field_power variable {K : Type*} section division_ring variables [division_ring K] {n : ℤ} lemma even.neg_zpow (h : even n) (a : K) : (-a) ^ n = a ^ n := by { obtain ⟨k, rfl⟩ := h, exact zpow_bit0_neg _ _ } lemma odd.neg_zpow (h : odd n) (a : K) : (-a) ^ n = - a ^ n := by { obtain ⟨k, rfl⟩ := h.exists_bit1, exact zpow_bit1_neg _ _ } lemma even.neg_one_zpow (h : even n) : (-1 : K) ^ n = 1 := by rw [h.neg_zpow, one_zpow₀] lemma odd.neg_one_zpow (h : odd n) : (-1 : K) ^ n = -1 := by rw [h.neg_zpow, one_zpow₀] end division_ring variables [linear_ordered_field K] {n : ℤ} {a : K} protected lemma even.zpow_nonneg (hn : even n) (a : K) : 0 ≤ a ^ n := begin cases le_or_lt 0 a with h h, { exact zpow_nonneg h _ }, { exact (hn.neg_zpow a).subst (zpow_nonneg (neg_nonneg_of_nonpos h.le) _) } end theorem even.zpow_pos (hn : even n) (ha : a ≠ 0) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit0_pos ha k protected lemma odd.zpow_nonneg (hn : odd n) (ha : 0 ≤ a) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_nonneg_iff.mpr ha theorem odd.zpow_pos (hn : odd n) (ha : 0 < a) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_pos_iff.mpr ha theorem odd.zpow_nonpos (hn : odd n) (ha : a ≤ 0) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_nonpos_iff.mpr ha theorem odd.zpow_neg (hn : odd n) (ha : a < 0) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_neg_iff.mpr ha lemma even.zpow_abs {p : ℤ} (hp : even p) (a : K) : |a| ^ p = a ^ p := begin cases abs_choice a with h h; simp only [h, hp.neg_zpow _], end @[simp] lemma zpow_bit0_abs (a : K) (p : ℤ) : |a| ^ bit0 p = a ^ bit0 p := (even_bit0 _).zpow_abs _ lemma even.abs_zpow {p : ℤ} (hp : even p) (a : K) : |a ^ p| = a ^ p := begin rw [abs_eq_self], exact hp.zpow_nonneg _ end @[simp] lemma abs_zpow_bit0 (a : K) (p : ℤ) : |a ^ bit0 p| = a ^ bit0 p := (even_bit0 _).abs_zpow _ end field_power
3ef84051f136a0b8ce65a13c66cdf885bf06c4ef
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/semiquot.lean
50d0885522584a0a165452765c330b48e9347e9a
[ "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
7,927
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.set.lattice /-! # Semiquotients > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A data type for semiquotients, which are classically equivalent to nonempty sets, but are useful for programming; the idea is that a semiquotient set `S` represents some (particular but unknown) element of `S`. This can be used to model nondeterministic functions, which return something in a range of values (represented by the predicate `S`) but are not completely determined. -/ /-- A member of `semiquot α` is classically a nonempty `set α`, and in the VM is represented by an element of `α`; the relation between these is that the VM element is required to be a member of the set `s`. The specific element of `s` that the VM computes is hidden by a quotient construction, allowing for the representation of nondeterministic functions. -/ structure {u} semiquot (α : Type*) := mk' :: (s : set α) (val : trunc ↥s) namespace semiquot variables {α : Type*} {β : Type*} instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩ /-- Construct a `semiquot α` from `h : a ∈ s` where `s : set α`. -/ def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α := ⟨s, trunc.mk ⟨a, h⟩⟩ theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s := begin refine ⟨congr_arg _, λ h, _⟩, cases q₁, cases q₂, cc, end theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ := ext_s.trans set.ext_iff theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q := let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩ theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) : q = @mk _ a q.1 h := ext_s.2 rfl theorem nonempty (q : semiquot α) : q.s.nonempty := q.exists_mem /-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/ protected def pure (a : α) : semiquot α := mk (set.mem_singleton a) @[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b := set.mem_singleton_iff /-- Replace `s` in a `semiquot` with a superset. -/ def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α := ⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩) (λ _ _, trunc.eq _ _) q.2⟩ /-- Replace `s` in a `q : semiquot α` with a union `s ∪ q.s` -/ def blur (s : set α) (q : semiquot α) : semiquot α := blur' q (set.subset_union_right s q.s) theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) : blur s q = blur' q h := by unfold blur; congr; exact set.union_eq_self_of_subset_right h @[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) {a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl /-- Convert a `trunc α` to a `semiquot α`. -/ def of_trunc (q : trunc α) : semiquot α := ⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩ /-- Convert a `semiquot α` to a `trunc α`. -/ def to_trunc (q : semiquot α) : trunc α := q.2.map subtype.val /-- If `f` is a constant on `q.s`, then `q.lift_on f` is the value of `f` at any point of `q`. -/ def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β := trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ x.2 _ y.2) theorem lift_on_of_mem (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) (a : α) (aq : a ∈ q) : lift_on q f h = f a := by revert h; rw eq_mk_of_mem aq; intro; refl /-- Apply a function to the unknown value stored in a `semiquot α`. -/ def map (f : α → β) (q : semiquot α) : semiquot β := ⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩ @[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) : b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _ /-- Apply a function returning a `semiquot` to a `semiquot`. -/ def bind (q : semiquot α) (f : α → semiquot β) : semiquot β := ⟨⋃ a ∈ q.1, (f a).1, q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩ @[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) : b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := set.mem_Union₂ instance : monad semiquot := { pure := @semiquot.pure, map := @semiquot.map, bind := @semiquot.bind } @[simp] lemma map_def {β} : ((<$>) : (α → β) → semiquot α → semiquot β) = map := rfl @[simp] lemma bind_def {β} : ((>>=) : semiquot α → (α → semiquot β) → semiquot β) = bind := rfl @[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b := set.mem_singleton_iff theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) := set.mem_singleton a @[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b := ext_s.trans set.singleton_eq_singleton_iff instance : is_lawful_monad semiquot := { pure_bind := λ α β x f, ext.2 $ by simp, bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩, λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩, id_map := λ α q, ext.2 $ by simp, bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] } instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩ instance : partial_order (semiquot α) := { le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t, le_refl := λ s, set.subset.refl _, le_trans := λ s t u, set.subset.trans, le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) } instance : semilattice_sup (semiquot α) := { sup := λ s, blur s.s, le_sup_left := λ s t, set.subset_union_left _ _, le_sup_right := λ s t, set.subset_union_right _ _, sup_le := λ s t u, set.union_subset, ..semiquot.partial_order } @[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s := set.singleton_subset_iff /-- Assert that a `semiquot` contains only one possible value. -/ def is_pure (q : semiquot α) : Prop := ∀ a b ∈ q, a = b /-- Extract the value from a `is_pure` semiquotient. -/ def get (q : semiquot α) (h : q.is_pure) : α := lift_on q id h theorem get_mem {q : semiquot α} (p) : get q p ∈ q := let ⟨a, h⟩ := exists_mem q in by unfold get; rw lift_on_of_mem q _ _ a h; exact h theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) := ext.2 $ λ a, by simp; exact ⟨λ h, p _ h _ (get_mem _), λ e, e.symm ▸ get_mem _⟩ @[simp] theorem pure_is_pure (a : α) : is_pure (pure a) | b ab c ac := by { rw [mem_pure] at ab ac, cc } theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a := ⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩ theorem is_pure.mono {s t : semiquot α} (st : s ≤ t) (h : is_pure t) : is_pure s | a as b bs := h _ (st as) _ (st bs) theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t := ⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp; exact h _ (get_mem _) _ (st $ get_mem _), le_of_eq⟩ theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q | a b aq bq := subsingleton.elim _ _ /-- `univ : semiquot α` represents an unspecified element of `univ : set α`. -/ def univ [inhabited α] : semiquot α := mk $ set.mem_univ default instance [inhabited α] : inhabited (semiquot α) := ⟨univ⟩ @[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ := @set.mem_univ α @[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J := ext.2 $ by simp @[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α := ⟨λ h, ⟨λ a b, h a trivial b trivial⟩, λ ⟨h⟩ a _ b _, h a b⟩ instance [inhabited α] : order_top (semiquot α) := { top := univ, le_top := λ s, set.subset_univ _ } end semiquot
f80f67538ae7c3d86d2198232943b78eb1e23cc7
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/nat/examples/partial_sum.lean
5e697b95d453a25f72a41c31a737b293fce6be16
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
1,165
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 -/ import data.nat open nat definition partial_sum : nat → nat | 0 := 0 | (succ n) := succ n + partial_sum n example : partial_sum 5 = 15 := rfl example : partial_sum 6 = 21 := rfl lemma two_mul_partial_sum_eq : ∀ n, 2 * partial_sum n = (succ n) * n | 0 := by reflexivity | (succ n) := calc 2 * (succ n + partial_sum n) = 2 * succ n + 2 * partial_sum n : left_distrib ... = 2 * succ n + succ n * n : two_mul_partial_sum_eq ... = 2 * succ n + n * succ n : mul.comm ... = (2 + n) * succ n : right_distrib ... = (n + 2) * succ n : add.comm ... = (succ (succ n)) * succ n : rfl theorem partial_sum_eq : ∀ n, partial_sum n = ((n + 1) * n) / 2 := take n, assert h₁ : (2 * partial_sum n) / 2 = ((succ n) * n) / 2, by rewrite two_mul_partial_sum_eq, assert h₂ : (2:nat) > 0, from dec_trivial, by rewrite [nat.mul_div_cancel_left _ h₂ at h₁]; exact h₁
60ecb5c7f95247ad382bf4cc2d85c5d94cff42eb
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/tools/super/equality.lean
554d282b6755d8fb2e75977a9bff584860682f9a
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,259
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 list namespace super meta def try_unify_eq_l (c : clause) (i : nat) : tactic clause := do guard $ clause.literal.is_neg (clause.get_lit c i), qf ← clause.open_metan c c^.num_quants, match is_eq (qf.1^.get_lit i)^.formula with | none := failed | some (lhs, rhs) := do unify lhs rhs, ty ← infer_type lhs, univ ← infer_univ ty, refl ← return $ app_of_list (const ``eq.refl [univ]) [ty, lhs], opened ← clause.open_constn qf.1 i, clause.meta_closure qf.2 $ clause.close_constn (opened.1^.inst refl) opened.2 end @[super.inf] meta def unify_eq_inf : inf_decl := inf_decl.mk 40 $ take given, sequence' $ do i ← given^.selected, [inf_if_successful 0 given (do u ← try_unify_eq_l given^.c i, return [u])] meta def has_refl_r (c : clause) : bool := list.bor $ do literal ← c^.get_lits, guard literal^.is_pos, match is_eq literal^.formula with | some (lhs, rhs) := [decidable.to_bool (lhs = rhs)] | none := [] end meta def refl_r_pre : prover unit := preprocessing_rule $ take new, return $ filter (λc, ¬has_refl_r c^.c) new end super
43b31e42c9611fdeba97ca80190cf1af7e0c06bc
f1dc39e1c68f71465c8bf79910c4664d03824751
/library/init/meta/environment.lean
cadb1de4466f9afa74d36af40065916760f32412
[ "Apache-2.0" ]
permissive
kckennylau/lean-2
6504f45da07bc98b098d726b74130103be25885c
c9a9368bc0fd600d832bd56c5cb2124b8a523ef9
refs/heads/master
1,659,140,308,864
1,589,361,166,000
1,589,361,166,000
263,748,786
0
0
null
1,589,405,915,000
1,589,405,915,000
null
UTF-8
Lean
false
false
10,103
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.declaration init.meta.exceptional init.data.option.basic import init.meta.rb_map /-- An __environment__ contains all of the declarations and notation that have been defined so far. -/ meta constant environment : Type namespace environment /-- Consider a type `ψ` which is an inductive datatype using a single constructor `mk (a : α) (b : β) : ψ`. Lean will automatically make two projection functions `a : ψ → α`, `b : ψ → β`. Lean tags these declarations as __projections__. This helps the simplifier / rewriter not have to expand projectors. Eg `a (mk x y)` will automatically reduce to `x`. If you `extend` a structure, all of the projections on the parent will also be created for the child. Projections are also treated differently in the VM for efficiency. Note that projections have nothing to do with the dot `mylist.map` syntax. You can find out if a declaration is a projection using `environment.is_projection` which returns `projection_info`. Data for a projection declaration: - `cname` is the name of the constructor associated with the projection. - `nparams` is the number of constructor parameters. Eg `and.intro` has two type parameters. - `idx` is the parameter being projected by this projection. - `is_class` is tt iff this is a typeclass projection. ### Examples: - `and.right` is a projection with ``{cname := `and.intro, nparams := 2, idx := 1, is_class := ff}`` - `ordered_ring.neg` is a projection with ``{cname := `ordered_ring.mk, nparams := 1, idx := 5, is_class := tt}``. -/ structure projection_info := (cname : name) (nparams : nat) (idx : nat) (is_class : bool) /-- A marking on the binders of structures and inductives indicating how this constructor should mark its parameters. inductive foo | one {} : foo -> foo -- relaxed_implicit | two ( ) : foo -> foo -- explicit | two [] : foo -> foo -- implicit | three : foo -> foo -- relaxed implicit (default) -/ inductive implicit_infer_kind | implicit | relaxed_implicit | none instance implicit_infer_kind.inhabited : inhabited implicit_infer_kind := ⟨implicit_infer_kind.implicit⟩ /-- One introduction rule in an inductive declaration -/ meta structure intro_rule := (constr : name) (type : expr) (infer : implicit_infer_kind := implicit_infer_kind.implicit) /-- Create a standard environment using the given trust level -/ meta constant mk_std : nat → environment /-- Return the trust level of the given environment -/ meta constant trust_lvl : environment → nat /-- Add a new declaration to the environment -/ meta constant add : environment → declaration → exceptional environment /-- make declaration `n` protected -/ meta constant mk_protected : environment → name → environment /-- add declaration `d` and make it protected -/ meta def add_protected (env : environment) (d : declaration) : exceptional environment := do env ← env.add d, pure $ env.mk_protected d.to_name /-- check if `n` is the name of a protected declaration -/ meta constant is_protected : environment → name → bool /-- Retrieve a declaration from the environment -/ meta constant get : environment → name → exceptional declaration meta def contains (env : environment) (d : name) : bool := match env.get d with | exceptional.success _ := tt | exceptional.exception _ := ff end meta constant add_defn_eqns (env : environment) (opt : options) (lp_params : list name) (params : list expr) (sig : expr) (eqns : list (list (expr ff) × expr)) (is_meta : bool) : exceptional environment /-- Register the given name as a namespace, making it available to the `open` command -/ meta constant add_namespace : environment → name → environment /-- Return tt iff the given name is a namespace -/ meta constant is_namespace : environment → name → bool /-- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta constant add_inductive (env : environment) (n : name) (levels : list name) (num_params : nat) (type : expr) (intros : list (name × expr)) (is_meta : bool) : exceptional environment /-- Add a new general inductive declaration to the environment. This has the same effect as a `inductive` in the file, including generating all the auxiliary definitions, as well as triggering mutual/nested inductive compilation, by contrast to `environment.add_inductive` which only adds the core axioms supported by the kernel. The `inds` argument should be a list of inductives in the mutual family. The first argument is a pair of the name of the type being constructed and the type of this inductive family (not including the params). The second argument is a list of intro rules, specified by a name, an `implicit_infer_kind` giving the implicitness of the params for this constructor, and an expression with the type of the constructor (not including the params). -/ meta constant add_ginductive (env : environment) (opt : options) (levels : list name) (params : list expr) (inds : list ((name × expr) × list intro_rule)) (is_meta : bool) : exceptional environment /-- Return tt iff the given name is an inductive datatype -/ meta constant is_inductive : environment → name → bool /-- Return tt iff the given name is a constructor -/ meta constant is_constructor : environment → name → bool /-- Return tt iff the given name is a recursor -/ meta constant is_recursor : environment → name → bool /-- Return tt iff the given name is a recursive inductive datatype -/ meta constant is_recursive : environment → name → bool /-- Return the name of the inductive datatype of the given constructor. -/ meta constant inductive_type_of : environment → name → option name /-- Return the constructors of the inductive datatype with the given name -/ meta constant constructors_of : environment → name → list name /-- Return the recursor of the given inductive datatype -/ meta constant recursor_of : environment → name → option name /-- Return the number of parameters of the inductive datatype -/ meta constant inductive_num_params : environment → name → nat /-- Return the number of indices of the inductive datatype -/ meta constant inductive_num_indices : environment → name → nat /-- Return tt iff the inductive datatype recursor supports dependent elimination -/ meta constant inductive_dep_elim : environment → name → bool /-- Functionally equivalent to `is_inductive`. Technically, this works by checking if the name is in the ginductive environment extension which is outside the kernel, whereas `is_inductive` works by looking at the kernel extension. But there are no `is_inductive`s which are not `is_ginductive`. -/ meta constant is_ginductive : environment → name → bool /-- See the docstring for `projection_info`. -/ meta constant is_projection : environment → name → option projection_info /-- Fold over declarations in the environment. -/ meta constant fold {α :Type} : environment → α → (declaration → α → α) → α /-- `relation_info env n` returns some value if n is marked as a relation in the given environment. the tuple contains: total number of arguments of the relation, lhs position and rhs position. -/ meta constant relation_info : environment → name → option (nat × nat × nat) /-- `refl_for env R` returns the name of the reflexivity theorem for the relation R -/ meta constant refl_for : environment → name → option name /-- `symm_for env R` returns the name of the symmetry theorem for the relation R -/ meta constant symm_for : environment → name → option name /-- `trans_for env R` returns the name of the transitivity theorem for the relation R -/ meta constant trans_for : environment → name → option name /-- `decl_olean env d` returns the name of the .olean file where d was defined. The result is none if d was not defined in an imported file. -/ meta constant decl_olean : environment → name → option string /-- `decl_pos env d` returns the source location of d if available. -/ meta constant decl_pos : environment → name → option pos /-- Return the fields of the structure with the given name, or `none` if it is not a structure -/ meta constant structure_fields : environment → name → option (list name) /-- `get_class_attribute_symbols env attr_name` return symbols occurring in instances of type classes tagged with the attribute `attr_name`. Example: [algebra] -/ meta constant get_class_attribute_symbols : environment → name → name_set /-- The fingerprint of the environment is a hash formed from all of the declarations in the environment. -/ meta constant fingerprint : environment → nat open expr meta constant unfold_untrusted_macros : environment → expr → expr meta constant unfold_all_macros : environment → expr → expr meta def is_constructor_app (env : environment) (e : expr) : bool := is_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e)) meta def is_refl_app (env : environment) (e : expr) : option (name × expr × expr) := match (refl_for env (const_name (get_app_fn e))) with | (some n) := if get_app_num_args e ≥ 2 then some (n, app_arg (app_fn e), app_arg e) else none | none := none end /-- Return true if 'n' has been declared in the current file -/ meta def in_current_file (env : environment) (n : name) : bool := (env.decl_olean n).is_none && env.contains n meta def is_definition (env : environment) (n : name) : bool := match env.get n with | exceptional.success (declaration.defn _ _ _ _ _ _) := tt | _ := ff end end environment meta instance : has_repr environment := ⟨λ e, "[environment]"⟩ meta instance : inhabited environment := ⟨environment.mk_std 0⟩
6a3d5ca5c697d516118b01c9b210c41b03ca767c
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/pullConstantThroughUnion2.lean
ab98ec5d97bd859967040e0f052fdd3681ab8bba
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
2,089
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..meta.ucongr import ..meta.TDP -- set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int variable integer_1: const datatypes.int variable integer_2: const datatypes.int theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL (((SELECT1 (combine (e2p (constantExpr integer_2)) (combine (right⋅emp_deptno) (right⋅emp_job))) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (combine (e2p (constantExpr integer_1)) (combine (right⋅emp_deptno) (right⋅emp_job))) FROM1 (table rel_emp) )) :SQL Γ _) = denoteSQL (((SELECT1 (combine (e2p (constantExpr integer_2)) (combine (right⋅emp_deptno) (right⋅emp_job))) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (combine (e2p (constantExpr integer_1)) (combine (right⋅emp_deptno) (right⋅emp_job))) FROM1 (table rel_emp) )) :SQL Γ _) := begin intros, unfold_all_denotations, funext, try {simp}, try {TDP' ucongr}, end
c843c726ca3f11fcf1a8c0ac688323c15a48024f
7afc29faca4febb6e5005c20aa4aa5c3df5cf35c
/src/finite.lean
95a3e4e150888efc3d77fcc37fd2247f194ffc06
[ "MIT" ]
permissive
Piwry/Proof-of-Surreal
ad2883027e275050b43a578c5513ae3fe350515b
6b92baf2382ac23dd0d700f5c958aa910ad4b754
refs/heads/master
1,670,521,185,736
1,599,657,591,000
1,599,657,591,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,287
lean
import data.list tactic.omega defs single height def left_bintree : list bintree → list bintree | [] := [] | (t :: l) := ⟦t ∣⟧ :: left_bintree l def right_bintree : list bintree → list bintree | [] := [] | (t :: l) := ⟦∣ t⟧ :: right_bintree l def full_list_bintree (t : bintree) : list bintree → list bintree | [] := [] | (t' :: l) := ⟦t, t'⟧ :: (full_list_bintree l) def full_list : list bintree → list bintree → list bintree | [] := λ l, [] | (t :: l) := λ l', full_list_bintree t l' ++ full_list l l' lemma left_bintree_correct : ∀ l t, t ∈ l → ⟦t ∣⟧ ∈ left_bintree l := begin intros l t h, induction l, cases h, cases h, begin unfold left_bintree, rewrite h, apply list.mem_cons_self end, begin unfold left_bintree, apply list.mem_cons_of_mem, apply l_ih, apply h end end lemma right_bintree_correct : ∀ l t, t ∈ l → ⟦∣ t⟧ ∈ right_bintree l := begin intros l t h, induction l, cases h, cases h, begin unfold right_bintree, rewrite h, apply list.mem_cons_self end, begin unfold right_bintree, apply list.mem_cons_of_mem, apply l_ih, apply h end end lemma full_list_bintree_correct : ∀ l t t', t' ∈ l → ⟦t, t'⟧ ∈ full_list_bintree t l := begin intros l, induction l, begin intros, cases a end, begin intros t t' h, cases h, begin rewrite h, unfold full_list_bintree, apply list.mem_cons_self end, begin unfold full_list_bintree, apply list.mem_cons_of_mem, apply l_ih, assumption end, end end lemma full_bintree_correct : ∀ l l' t t', t ∈ l → t' ∈ l' → ⟦t, t'⟧ ∈ full_list l l' := begin intros l, induction l, begin intros l' t t' h1 h2, cases h1 end, begin intros l' t t' h1 h2, unfold full_list, cases h1, begin rewrite h1, apply list.mem_append_left, apply full_list_bintree_correct, assumption end, begin apply list.mem_append_right, apply l_ih, assumption, assumption end end end lemma cross_product_bintree : ∀ l : list bintree, ∃ l' : list bintree, ∀ t t', t ∈ l → t' ∈ l → ⟦t, t'⟧ ∈ l' ∧ ⟦t ∣⟧ ∈ l' ∧ ⟦∣ t'⟧ ∈ l' := begin intros l, have ht : ∃ l', l' = left_bintree l ++ right_bintree l ++ full_list l l, existsi left_bintree l ++ right_bintree l ++ full_list l l, refl, cases ht, existsi ht_w, intros t t' h1 h2, split, begin -- full rewrite ht_h, apply list.mem_append_right, apply full_bintree_correct, repeat {assumption} end, split, begin -- left rewrite ht_h, apply list.mem_append_left, apply list.mem_append_left, apply left_bintree_correct, assumption end, begin -- right rewrite ht_h, apply list.mem_append_left, apply list.mem_append_right, apply right_bintree_correct, assumption end end lemma bounded_height_list : ∀ h : ℕ, ∃ l : list bintree, ∀ t : bintree, height t ≤ h → t ∈ l := begin intros h, induction h, begin existsi list.nil, intros t a, simp at a, exfalso, exact a end, begin cases h_n, begin -- actuall induction basis existsi ([●]), intros t h, cases t, simp, repeat { simp at h, exfalso, exact h }, end, begin cases h_ih, cases (cross_product_bintree h_ih_w), existsi (list.cons ● w), intros t ht, cases t, begin apply list.mem_cons_self end, repeat { apply list.mem_cons_of_mem, have hi : ● ∈ h_ih_w, apply h_ih_h, unfold height, omega, have hj : t ∈ h_ih_w, apply h_ih_h, unfold height at ht, omega, try {exact (and.left (and.right (h t ● hj hi)))}, try {exact (and.right (and.right (h ● t hi hj)))} }, apply list.mem_cons_of_mem, have hm : height t_a ≤ max (height t_a) (height t_a_1), apply le_max_left, have hn : height t_a_1 ≤ max (height t_a) (height t_a_1), apply le_max_right, have hi : t_a ∈ h_ih_w, apply h_ih_h, unfold height at ht, omega, have hj : t_a_1 ∈ h_ih_w, apply h_ih_h, unfold height at ht, omega, exact (and.left (h t_a t_a_1 hi hj)), end end end
8867826cd5dd5dacde62808383201396003b6749
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/algebra/lie_algebra.lean
6f66d14092d59d9f8de3625e1c2bd141b2ac6d7a
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
26,457
lean
/- Copyright (c) 2019 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import ring_theory.algebra import linear_algebra.linear_action /-! # Lie algebras This file defines Lie rings, and Lie algebras over a commutative ring. It shows how these arise from associative rings and algebras via the ring commutator. In particular it defines the Lie algebra of endomorphisms of a module as well as of the algebra of square matrices over a commutative ring. It also includes definitions of morphisms of Lie algebras, Lie subalgebras, Lie modules, Lie submodules, and the quotient of a Lie algebra by an ideal. ## Notations We introduce the notation ⁅x, y⁆ for the Lie bracket. Note that these are the Unicode "square with quill" brackets rather than the usual square brackets. We also introduce the notations L →ₗ⁅R⁆ L' for a morphism of Lie algebras over a commutative ring R, and L →ₗ⁅⁆ L' for the same, when the ring is implicit. ## Implementation notes Lie algebras are defined as modules with a compatible Lie ring structure, and thus are partially unbundled. Since they extend Lie rings, these are also partially unbundled. ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*][bourbaki1975] ## Tags lie bracket, ring commutator, jacobi identity, lie ring, lie algebra -/ universes u v w w₁ /-- A binary operation, intended use in Lie algebras and similar structures. -/ class has_bracket (L : Type v) := (bracket : L → L → L) notation `⁅`x`,` y`⁆` := has_bracket.bracket x y /-- An Abelian Lie algebra is one in which all brackets vanish. Arguably this class belongs in the `has_bracket` namespace but it seems much more user-friendly to compromise slightly and put it in the `lie_algebra` namespace. -/ class lie_algebra.is_abelian (L : Type v) [has_bracket L] [has_zero L] : Prop := (abelian : ∀ (x y : L), ⁅x, y⁆ = 0) namespace ring_commutator variables {A : Type v} [ring A] /-- The ring commutator captures the extent to which a ring is commutative. It is identically zero exactly when the ring is commutative. -/ def commutator (x y : A) := x*y - y*x local notation `⁅`x`,` y`⁆` := commutator x y @[simp] lemma add_left (x y z : A) : ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆ := by simp [commutator, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm] @[simp] lemma add_right (x y z : A) : ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆ := by simp [commutator, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm] @[simp] lemma alternate (x : A) : ⁅x, x⁆ = 0 := by simp [commutator] lemma jacobi (x y z : A) : ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0 := begin unfold commutator, repeat { rw mul_sub_left_distrib }, repeat { rw mul_sub_right_distrib }, repeat { rw add_sub }, repeat { rw ←sub_add }, repeat { rw ←mul_assoc }, have h : ∀ (x y z : A), x - y + z + y = x+z := by simp [sub_eq_add_neg, add_left_comm], repeat { rw h }, simp [sub_eq_add_neg, add_left_comm], end end ring_commutator section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie ring is an additive group with compatible product, known as the bracket, satisfying the Jacobi identity. The bracket is not associative unless it is identically zero. -/ class lie_ring (L : Type v) extends add_comm_group L, has_bracket L := (add_lie : ∀ (x y z : L), ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆) (lie_add : ∀ (x y z : L), ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆) (lie_self : ∀ (x : L), ⁅x, x⁆ = 0) (jacobi : ∀ (x y z : L), ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0) end prio section lie_ring variables {L : Type v} [lie_ring L] @[simp] lemma add_lie (x y z : L) : ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆ := lie_ring.add_lie x y z @[simp] lemma lie_add (x y z : L) : ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆ := lie_ring.lie_add x y z @[simp] lemma lie_self (x : L) : ⁅x, x⁆ = 0 := lie_ring.lie_self x @[simp] lemma lie_skew (x y : L) : -⁅y, x⁆ = ⁅x, y⁆ := begin symmetry, rw [←sub_eq_zero_iff_eq, sub_neg_eq_add], have H : ⁅x + y, x + y⁆ = 0, from lie_self _, rw add_lie at H, simpa using H, end @[simp] lemma lie_zero (x : L) : ⁅x, 0⁆ = 0 := begin have H : ⁅x, 0⁆ + ⁅x, 0⁆ = ⁅x, 0⁆ + 0 := by { rw ←lie_add, simp, }, exact add_left_cancel H, end @[simp] lemma zero_lie (x : L) : ⁅0, x⁆ = 0 := by { rw [←lie_skew, lie_zero], simp, } @[simp] lemma neg_lie (x y : L) : ⁅-x, y⁆ = -⁅x, y⁆ := by { rw [←sub_eq_zero_iff_eq, sub_neg_eq_add, ←add_lie], simp, } @[simp] lemma lie_neg (x y : L) : ⁅x, -y⁆ = -⁅x, y⁆ := by { rw [←lie_skew, ←lie_skew], simp, } @[simp] lemma gsmul_lie (x y : L) (n : ℤ) : ⁅n • x, y⁆ = n • ⁅x, y⁆ := add_monoid_hom.map_gsmul ⟨λ x, ⁅x, y⁆, zero_lie y, λ _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_gsmul (x y : L) (n : ℤ) : ⁅x, n • y⁆ = n • ⁅x, y⁆ := begin rw [←lie_skew, ←lie_skew x, gsmul_lie], unfold has_scalar.smul, rw gsmul_neg, end /-- An associative ring gives rise to a Lie ring by taking the bracket to be the ring commutator. -/ def lie_ring.of_associative_ring (A : Type v) [ring A] : lie_ring A := { bracket := ring_commutator.commutator, add_lie := ring_commutator.add_left, lie_add := ring_commutator.add_right, lie_self := ring_commutator.alternate, jacobi := ring_commutator.jacobi } local attribute [instance] lie_ring.of_associative_ring lemma lie_ring.of_associative_ring_bracket (A : Type v) [ring A] (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl lemma commutative_ring_iff_abelian_lie_ring (A : Type v) [ring A] : is_commutative A (*) ↔ lie_algebra.is_abelian A := begin have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩, have h₂ : lie_algebra.is_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩, simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero], end end lie_ring section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie algebra is a module with compatible product, known as the bracket, satisfying the Jacobi identity. Forgetting the scalar multiplication, every Lie algebra is a Lie ring. -/ class lie_algebra (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] extends module R L := (lie_smul : ∀ (t : R) (x y : L), ⁅x, t • y⁆ = t • ⁅x, y⁆) end prio @[simp] lemma lie_smul (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (t : R) (x y : L) : ⁅x, t • y⁆ = t • ⁅x, y⁆ := lie_algebra.lie_smul t x y @[simp] lemma smul_lie (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (t : R) (x y : L) : ⁅t • x, y⁆ = t • ⁅x, y⁆ := by { rw [←lie_skew, ←lie_skew x y], simp [-lie_skew], } namespace lie_algebra set_option old_structure_cmd true /-- A morphism of Lie algebras is a linear map respecting the bracket operations. -/ structure morphism (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends linear_map R L L' := (map_lie : ∀ {x y : L}, to_fun ⁅x, y⁆ = ⁅to_fun x, to_fun y⁆) attribute [nolint doc_blame] lie_algebra.morphism.to_linear_map infixr ` →ₗ⁅⁆ `:25 := morphism _ notation L ` →ₗ⁅`:25 R:25 `⁆ `:0 L':0 := morphism R L L' section morphism_properties variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃] variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃] instance : has_coe (L₁ →ₗ⁅R⁆ L₂) (L₁ →ₗ[R] L₂) := ⟨morphism.to_linear_map⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ →ₗ⁅R⁆ L₂) := ⟨_, morphism.to_fun⟩ @[simp] lemma map_lie (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f ⁅x, y⁆ = ⁅f x, f y⁆ := morphism.map_lie f /-- The constant 0 map is a Lie algebra morphism. -/ instance : has_zero (L₁ →ₗ⁅R⁆ L₂) := ⟨{ map_lie := by simp, ..(0 : L₁ →ₗ[R] L₂)}⟩ /-- The identity map is a Lie algebra morphism. -/ instance : has_one (L₁ →ₗ⁅R⁆ L₁) := ⟨{ map_lie := by simp, ..(1 : L₁ →ₗ[R] L₁)}⟩ instance : inhabited (L₁ →ₗ⁅R⁆ L₂) := ⟨0⟩ /-- The composition of morphisms is a morphism. -/ def morphism.comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : L₁ →ₗ⁅R⁆ L₃ := { map_lie := λ x y, by { change f (g ⁅x, y⁆) = ⁅f (g x), f (g y)⁆, rw [map_lie, map_lie], }, ..linear_map.comp f.to_linear_map g.to_linear_map } lemma morphism.comp_apply (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) (x : L₁) : f.comp g x = f (g x) := rfl /-- The inverse of a bijective morphism is a morphism. -/ def morphism.inverse (f : L₁ →ₗ⁅R⁆ L₂) (g : L₂ → L₁) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : L₂ →ₗ⁅R⁆ L₁ := { map_lie := λ x y, by { calc g ⁅x, y⁆ = g ⁅f (g x), f (g y)⁆ : by { conv_lhs { rw [←h₂ x, ←h₂ y], }, } ... = g (f ⁅g x, g y⁆) : by rw map_lie ... = ⁅g x, g y⁆ : (h₁ _), }, ..linear_map.inverse f.to_linear_map g h₁ h₂ } end morphism_properties /-- An equivalence of Lie algebras is a morphism which is also a linear equivalence. We could instead define an equivalence to be a morphism which is also a (plain) equivalence. However it is more convenient to define via linear equivalence to get `.to_linear_equiv` for free. -/ structure equiv (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends L →ₗ⁅R⁆ L', L ≃ₗ[R] L' attribute [nolint doc_blame] lie_algebra.equiv.to_morphism attribute [nolint doc_blame] lie_algebra.equiv.to_linear_equiv notation L ` ≃ₗ⁅`:50 R `⁆ ` L' := equiv R L L' namespace equiv variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃] variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃] instance : has_one (L₁ ≃ₗ⁅R⁆ L₁) := ⟨{ map_lie := λ x y, by { change ((1 : L₁→ₗ[R] L₁) ⁅x, y⁆) = ⁅(1 : L₁→ₗ[R] L₁) x, (1 : L₁→ₗ[R] L₁) y⁆, simp, }, ..(1 : L₁ ≃ₗ[R] L₁)}⟩ instance : inhabited (L₁ ≃ₗ⁅R⁆ L₁) := ⟨1⟩ /-- Lie algebra equivalences are reflexive. -/ @[refl] def refl : L₁ ≃ₗ⁅R⁆ L₁ := 1 /-- Lie algebra equivalences are symmetric. -/ @[symm] def symm (e : L₁ ≃ₗ⁅R⁆ L₂) : L₂ ≃ₗ⁅R⁆ L₁ := { ..morphism.inverse e.to_morphism e.inv_fun e.left_inv e.right_inv, ..e.to_linear_equiv.symm } /-- Lie algebra equivalences are transitive. -/ @[trans] def trans (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) : L₁ ≃ₗ⁅R⁆ L₃ := { ..morphism.comp e₂.to_morphism e₁.to_morphism, ..linear_equiv.trans e₁.to_linear_equiv e₂.to_linear_equiv } end equiv namespace direct_sum open dfinsupp variables {R : Type u} [comm_ring R] variables {ι : Type v} [decidable_eq ι] {L : ι → Type w} variables [Π i, lie_ring (L i)] [Π i, lie_algebra R (L i)] /-- The direct sum of Lie rings carries a natural Lie ring structure. -/ instance : lie_ring (direct_sum ι L) := { bracket := zip_with (λ i, λ x y, ⁅x, y⁆) (λ i, lie_zero 0), add_lie := λ x y z, by { ext, simp only [zip_with_apply, add_apply, add_lie], }, lie_add := λ x y z, by { ext, simp only [zip_with_apply, add_apply, lie_add], }, lie_self := λ x, by { ext, simp only [zip_with_apply, add_apply, lie_self, zero_apply], }, jacobi := λ x y z, by { ext, simp only [zip_with_apply, add_apply, lie_ring.jacobi, zero_apply], }, ..(infer_instance : add_comm_group _) } @[simp] lemma bracket_apply {x y : direct_sum ι L} {i : ι} : ⁅x, y⁆ i = ⁅x i, y i⁆ := zip_with_apply /-- The direct sum of Lie algebras carries a natural Lie algebra structure. -/ instance : lie_algebra R (direct_sum ι L) := { lie_smul := λ c x y, by { ext, simp only [zip_with_apply, smul_apply, bracket_apply, lie_smul], }, ..(infer_instance : module R _) } end direct_sum variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] /-- An associative algebra gives rise to a Lie algebra by taking the bracket to be the ring commutator. -/ def of_associative_algebra (A : Type v) [ring A] [algebra R A] : @lie_algebra R A _ (lie_ring.of_associative_ring _) := { lie_smul := λ t x y, by rw [lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_sub], } instance (M : Type v) [add_comm_group M] [module R M] : lie_ring (module.End R M) := lie_ring.of_associative_ring _ local attribute [instance] lie_ring.of_associative_ring local attribute [instance] lie_algebra.of_associative_algebra /-- The map `of_associative_algebra` associating a Lie algebra to an associative algebra is functorial. -/ def of_associative_algebra_hom {R : Type u} {A : Type v} {B : Type w} [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : A →ₗ⁅R⁆ B := { map_lie := λ x y, show f ⁅x,y⁆ = ⁅f x,f y⁆, by simp only [lie_ring.of_associative_ring_bracket, alg_hom.map_sub, alg_hom.map_mul], ..f.to_linear_map, } @[simp] lemma of_associative_algebra_hom_id {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] : of_associative_algebra_hom (alg_hom.id R A) = 1 := rfl @[simp] lemma of_associative_algebra_hom_comp {R : Type u} {A : Type v} {B : Type w} {C : Type w₁} [comm_ring R] [ring A] [ring B] [ring C] [algebra R A] [algebra R B] [algebra R C] (f : A →ₐ[R] B) (g : B →ₐ[R] C) : of_associative_algebra_hom (g.comp f) = (of_associative_algebra_hom g).comp (of_associative_algebra_hom f) := rfl /-- An important class of Lie algebras are those arising from the associative algebra structure on module endomorphisms. -/ instance of_endomorphism_algebra (M : Type v) [add_comm_group M] [module R M] : lie_algebra R (module.End R M) := of_associative_algebra (module.End R M) lemma endo_algebra_bracket (M : Type v) [add_comm_group M] [module R M] (f g : module.End R M) : ⁅f, g⁆ = f.comp g - g.comp f := rfl /-- The adjoint action of a Lie algebra on itself. -/ def Ad : L →ₗ⁅R⁆ module.End R L := { to_fun := λ x, { to_fun := has_bracket.bracket x, add := by { intros, apply lie_add, }, smul := by { intros, apply lie_smul, } }, add := by { intros, ext, simp, }, smul := by { intros, ext, simp, }, map_lie := by { intros x y, ext z, rw endo_algebra_bracket, suffices : ⁅⁅x, y⁆, z⁆ = ⁅x, ⁅y, z⁆⁆ + ⁅⁅x, z⁆, y⁆, by simpa [sub_eq_add_neg], rw [eq_comm, ←lie_skew ⁅x, y⁆ z, ←lie_skew ⁅x, z⁆ y, ←lie_skew x z, lie_neg, neg_neg, ←sub_eq_zero_iff_eq, sub_neg_eq_add, lie_ring.jacobi], } } end lie_algebra section lie_subalgebra variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] /-- A Lie subalgebra of a Lie algebra is submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie algebra. -/ structure lie_subalgebra extends submodule R L := (lie_mem : ∀ {x y}, x ∈ carrier → y ∈ carrier → ⁅x, y⁆ ∈ carrier) /-- The zero algebra is a subalgebra of any Lie algebra. -/ instance : has_zero (lie_subalgebra R L) := ⟨{ lie_mem := λ x y hx hy, by { rw [((submodule.mem_bot R).1 hx), zero_lie], exact submodule.zero_mem (0 : submodule R L), }, ..(0 : submodule R L) }⟩ instance : inhabited (lie_subalgebra R L) := ⟨0⟩ instance lie_subalgebra_coe_submodule : has_coe (lie_subalgebra R L) (submodule R L) := ⟨lie_subalgebra.to_submodule⟩ /-- A Lie subalgebra forms a new Lie ring. -/ instance lie_subalgebra_lie_ring (L' : lie_subalgebra R L) : lie_ring L' := { bracket := λ x y, ⟨⁅x.val, y.val⁆, L'.lie_mem x.property y.property⟩, lie_add := by { intros, apply set_coe.ext, apply lie_add, }, add_lie := by { intros, apply set_coe.ext, apply add_lie, }, lie_self := by { intros, apply set_coe.ext, apply lie_self, }, jacobi := by { intros, apply set_coe.ext, apply lie_ring.jacobi, } } /-- A Lie subalgebra forms a new Lie algebra. -/ instance lie_subalgebra_lie_algebra (L' : lie_subalgebra R L) : @lie_algebra R L' _ (lie_subalgebra_lie_ring _ _ _) := { lie_smul := by { intros, apply set_coe.ext, apply lie_smul } } local attribute [instance] lie_ring.of_associative_ring local attribute [instance] lie_algebra.of_associative_algebra /-- A subalgebra of an associative algebra is a Lie subalgebra of the associated Lie algebra. -/ def lie_subalgebra_of_subalgebra (A : Type v) [ring A] [algebra R A] (A' : subalgebra R A) : lie_subalgebra R A := { lie_mem := λ x y hx hy, by { change ⁅x, y⁆ ∈ A', change x ∈ A' at hx, change y ∈ A' at hy, rw lie_ring.of_associative_ring_bracket, have hxy := subalgebra.mul_mem A' x y hx hy, have hyx := subalgebra.mul_mem A' y x hy hx, exact submodule.sub_mem A'.to_submodule hxy hyx, }, ..A'.to_submodule } end lie_subalgebra section lie_module variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] variables (M : Type v) [add_comm_group M] [module R M] section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie module is a module over a commutative ring, together with a linear action of a Lie algebra on this module, such that the Lie bracket acts as the commutator of endomorphisms. -/ class lie_module extends linear_action R L M := (lie_act : ∀ (l l' : L) (m : M), act ⁅l, l'⁆ m = act l (act l' m) - act l' (act l m)) end prio @[simp] lemma lie_act [lie_module R L M] (l l' : L) (m : M) : linear_action.act R ⁅l, l'⁆ m = linear_action.act R l (linear_action.act R l' m) - linear_action.act R l' (linear_action.act R l m) := lie_module.lie_act l l' m protected lemma of_endo_map_action (α : L →ₗ⁅R⁆ module.End R M) (x : L) (m : M) : @linear_action.act R _ _ _ _ _ _ _ (linear_action.of_endo_map R L M α) x m = α x m := rfl /-- A Lie morphism from a Lie algebra to the endomorphism algebra of a module yields a Lie module structure. -/ def lie_module.of_endo_morphism (α : L →ₗ⁅R⁆ module.End R M) : lie_module R L M := { lie_act := by { intros x y m, rw [of_endo_map_action, lie_algebra.map_lie, lie_algebra.endo_algebra_bracket], refl, }, ..(linear_action.of_endo_map R L M α) } /-- Every Lie algebra is a module over itself. -/ instance lie_algebra_self_module : lie_module R L L := lie_module.of_endo_morphism R L L lie_algebra.Ad /-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie module. -/ structure lie_submodule [lie_module R L M] extends submodule R M := (lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → linear_action.act R x m ∈ carrier) /-- The zero module is a Lie submodule of any Lie module. -/ instance [lie_module R L M] : has_zero (lie_submodule R L M) := ⟨{ lie_mem := λ x m h, by { rw [((submodule.mem_bot R).1 h), linear_action_zero], exact submodule.zero_mem (0 : submodule R M), }, ..(0 : submodule R M)}⟩ instance [lie_module R L M] : inhabited (lie_submodule R L M) := ⟨0⟩ instance lie_submodule_coe_submodule [lie_module R L M] : has_coe (lie_submodule R L M) (submodule R M) := ⟨lie_submodule.to_submodule⟩ instance lie_submodule_has_mem [lie_module R L M] : has_mem M (lie_submodule R L M) := ⟨λ x N, x ∈ (N : set M)⟩ instance lie_submodule_lie_module [lie_module R L M] (N : lie_submodule R L M) : lie_module R L N := { act := λ x m, ⟨linear_action.act R x m.val, N.lie_mem m.property⟩, add_act := by { intros x y m, apply set_coe.ext, apply linear_action.add_act, }, act_add := by { intros x m n, apply set_coe.ext, apply linear_action.act_add, }, act_smul := by { intros r x y, apply set_coe.ext, apply linear_action.act_smul, }, smul_act := by { intros r x y, apply set_coe.ext, apply linear_action.smul_act, }, lie_act := by { intros x y m, apply set_coe.ext, apply lie_module.lie_act, } } /-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/ abbreviation lie_ideal := lie_submodule R L L lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I := by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, } /-- An ideal of a Lie algebra is a Lie subalgebra. -/ def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L := { lie_mem := by { intros x y hx hy, apply lie_mem_right, exact hy, }, ..I.to_submodule, } /-- A Lie module is irreducible if its only non-trivial Lie submodule is itself. -/ class lie_module.is_irreducible [lie_module R L M] : Prop := (irreducible : ∀ (M' : lie_submodule R L M), (∃ (m : M'), m ≠ 0) → (∀ (m : M), m ∈ M')) /-- A Lie algebra is simple if it is irreducible as a Lie module over itself via the adjoint action, and it is non-Abelian. -/ class lie_algebra.is_simple : Prop := (simple : lie_module.is_irreducible R L L ∧ ¬lie_algebra.is_abelian L) end lie_module namespace lie_submodule variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] variables {M : Type v} [add_comm_group M] [module R M] [α : lie_module R L M] variables (N : lie_submodule R L M) (I : lie_ideal R L) /-- The quotient of a Lie module by a Lie submodule. It is a Lie module. -/ abbreviation quotient := N.to_submodule.quotient namespace quotient variables {N I} /-- Map sending an element of `M` to the corresponding element of `M/N`, when `N` is a lie_submodule of the lie_module `N`. -/ abbreviation mk : M → N.quotient := submodule.quotient.mk lemma is_quotient_mk (m : M) : quotient.mk' m = (mk m : N.quotient) := rfl /-- Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M`, there is a natural linear map from `L` to the endomorphisms of `M` leaving `N` invariant. -/ def lie_submodule_invariant : L →ₗ[R] submodule.compatible_maps N.to_submodule N.to_submodule := linear_map.cod_restrict _ (α.to_linear_action.to_endo_map _ _ _) N.lie_mem instance lie_quotient_action : linear_action R L N.quotient := linear_action.of_endo_map _ _ _ (linear_map.comp (submodule.mapq_linear N N) lie_submodule_invariant) lemma lie_quotient_action_apply (z : L) (m : M) : linear_action.act R z (mk m : N.quotient) = mk (linear_action.act R z m) := rfl /-- The quotient of a Lie module by a Lie submodule, is a Lie module. -/ instance lie_quotient_lie_module : lie_module R L N.quotient := { lie_act := λ x y m', by { apply quotient.induction_on' m', intros m, rw is_quotient_mk, repeat { rw lie_quotient_action_apply, }, rw lie_act, refl, }, ..quotient.lie_quotient_action, } instance lie_quotient_has_bracket : has_bracket (quotient I) := ⟨by { intros x y, apply quotient.lift_on₂' x y (λ x' y', mk ⁅x', y'⁆), intros x₁ x₂ y₁ y₂ h₁ h₂, apply (submodule.quotient.eq I.to_submodule).2, have h : ⁅x₁, x₂⁆ - ⁅y₁, y₂⁆ = ⁅x₁, x₂ - y₂⁆ + ⁅x₁ - y₁, y₂⁆ := by simp [-lie_skew, sub_eq_add_neg], rw h, apply submodule.add_mem, { apply lie_mem_right R L I x₁ (x₂ - y₂) h₂, }, { apply lie_mem_left R L I (x₁ - y₁) y₂ h₁, }, }⟩ @[simp] lemma mk_bracket (x y : L) : (mk ⁅x, y⁆ : quotient I) = ⁅mk x, mk y⁆ := rfl instance lie_quotient_lie_ring : lie_ring (quotient I) := { add_lie := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply add_lie, }, lie_add := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply lie_add, }, lie_self := by { intros x', apply quotient.induction_on' x', intros x, rw [is_quotient_mk, ←mk_bracket], apply congr_arg, apply lie_self, }, jacobi := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply lie_ring.jacobi, } } instance lie_quotient_lie_algebra : lie_algebra R (quotient I) := { lie_smul := by { intros t x' y', apply quotient.induction_on₂' x' y', intros x y, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_smul, }, apply congr_arg, apply lie_smul, } } end quotient end lie_submodule /-- An important class of Lie rings are those arising from the associative algebra structure on square matrices over a commutative ring. -/ def matrix.lie_ring (n : Type u) (R : Type v) [fintype n] [decidable_eq n] [comm_ring R] : lie_ring (matrix n n R) := lie_ring.of_associative_ring (matrix n n R) local attribute [instance] matrix.lie_ring /-- An important class of Lie algebras are those arising from the associative algebra structure on square matrices over a commutative ring. -/ def matrix.lie_algebra (n : Type u) (R : Type v) [fintype n] [decidable_eq n] [comm_ring R] : lie_algebra R (matrix n n R) := lie_algebra.of_associative_algebra (matrix n n R)
b456825d1226c75efcdef843986a3bccf0d13a6d
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/topology/instances/real.lean
c7cfc8862951f19976fb0c98069492e4a574ac35
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,670
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring import topology.algebra.continuous_functions import ring_theory.subring import group_theory.archimedean /-! # Topological properties of ℝ -/ noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, abs (y - x) < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets ((is_open_lt' (abs r / 2)).preimage real.continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (((is_open_gt' (abs a₁ + 1)).preimage real.continuous_abs).prod ((is_open_gt' (abs a₂ + 1)).preimage real.continuous_abs )) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, (set.finite_lt_nat _).image _, _⟩, rintro x ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, use i, split, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : is_compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) lemma compact_pi_Icc {ι : Type*} {a b : ι → ℝ} : is_compact (Icc a b) := pi_univ_Icc a b ▸ compact_univ_pi $ λ i, compact_Icc instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (compact_Icc.image_of_continuous_on h) end instance reals_semimodule : topological_semimodule ℝ ℝ := ⟨continuous_mul⟩ instance real_maps_algebra {α : Type*} [topological_space α] : algebra ℝ C(α, ℝ) := continuous_map_algebra section subgroups /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, abs (x - g) < ε, by simpa only [real.mem_closure_iff, abs_sub], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' ε_pos a_notin, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' (by linarith : 0 < b - a) a_notin, refine ⟨b - c, add_subgroup.sub_mem G hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
16c6e8b79747a8b2abd0efcd1e55d1aac1faa1cf
17d3c61bf162bf88be633867ed4cb201378a8769
/library/init/native/default.lean
e41a3a6577d312ac4f845046e7585e463ebda6bb
[ "Apache-2.0" ]
permissive
u20024804/lean
11def01468fb4796fb0da76015855adceac7e311
d315e424ff17faf6fe096a0a1407b70193009726
refs/heads/master
1,611,388,567,561
1,485,836,506,000
1,485,836,625,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,828
lean
/- Copyright (c) 2016 Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch -/ prelude import init.meta.format import init.meta.expr import init.category.state import init.data.string import init.data.list.instances import init.native.ir import init.native.format import init.native.internal import init.native.anf import init.native.cf import init.native.pass import init.native.util import init.native.config import init.native.result namespace native inductive error : Type | string : string → error | many : list error → error meta def error.to_string : error → string | (error.string s) := s | (error.many es) := to_string $ list.map error.to_string es meta def arity_map : Type := rb_map name nat meta def get_arity : expr → nat | (expr.lam _ _ _ body) := 1 + get_arity body | _ := 0 @[reducible] def ir_result (A : Type*) := native.result error A meta def mk_arity_map : list (name × expr) → arity_map | [] := rb_map.mk name nat | ((n, body) :: rest) := rb_map.insert (mk_arity_map rest) n (get_arity body) @[reducible] meta def ir_compiler_state := (config × arity_map × nat) @[reducible] meta def ir_compiler (A : Type) := native.resultT (state ir_compiler_state) error A meta def lift {A} (action : state ir_compiler_state A) : ir_compiler A := ⟨fmap (fun (a : A), native.result.ok a) action⟩ meta def trace_ir (s : string) : ir_compiler unit := do (conf, map, counter) ← lift $ state.read, if config.debug conf then trace s (fun u, return ()) else return () -- An `exotic` monad combinator that accumulates errors. meta def run {M E A} (res : native.resultT M E A) : M (native.result E A) := match res with | ⟨action⟩ := action end meta def sequence_err : list (ir_compiler format) → ir_compiler (list format × list error) | [] := return ([], []) | (action :: remaining) := ⟨ fun s, match (run (sequence_err remaining)) s with | (native.result.err e, s') := (native.result.err e, s) | (native.result.ok (res, errs), s') := match (run action) s' with | (native.result.err e, s'') := (native.result.ok (res, e :: errs), s'') | (native.result.ok v, s'') := (native.result.ok (v :: res, errs), s'') end end ⟩ -- meta lemma sequence_err_always_ok : -- forall xs v s s', sequence_err xs s = native.result.ok (v, s') := sorry meta def lift_result {A} (action : ir_result A) : ir_compiler A := ⟨fun s, (action, s)⟩ -- TODO: fix naming here private meta def take_arguments' : expr → list name → (list name × expr) | (expr.lam n _ _ body) ns := take_arguments' body (n :: ns) | e' ns := (ns, e') meta def fresh_name : ir_compiler name := do (conf, map, counter) ← lift state.read, let fresh := name.mk_numeral (unsigned.of_nat counter) `native._ir_compiler_ in do lift $ state.write (conf, map, counter + 1), return fresh meta def take_arguments (e : expr) : ir_compiler (list name × expr) := let (arg_names, body) := take_arguments' e [] in do fresh_names ← monad.mapm (fun x, fresh_name) arg_names, let locals := list.map mk_local fresh_names in return $ (fresh_names, expr.instantiate_vars body (list.reverse locals)) -- meta def lift_state {A} (action : state arity_map A) : ir_compiler A := -- fun (s : arity_map), match action s with -- | (a, s) := (return a, s) -- end meta def mk_error {T} : string → ir_compiler T := fun s, do trace_ir "CREATEDERROR", lift_result (native.result.err $ error.string s) meta def lookup_arity (n : name) : ir_compiler nat := do (_, map, counter) ← lift state.read, if n = `nat.cases_on then pure 2 else match rb_map.find map n with | option.none := mk_error $ "could not find arity for: " ++ to_string n | option.some n := return n end meta def mk_nat_literal (n : nat) : ir_compiler ir.expr := return (ir.expr.lit $ ir.literal.nat n) def repeat {A : Type} : nat → A → list A | 0 _ := [] | (n + 1) a := a :: repeat n a def zip {A B : Type} : list A → list B → list (A × B) | [] [] := [] | [] (y :: ys) := [] | (x :: xs) [] := [] | (x :: xs) (y :: ys) := (x, y) :: zip xs ys private def upto' : ℕ → list ℕ | 0 := [] | (n + 1) := n :: upto' n def upto (n : ℕ) : list ℕ := list.reverse $ upto' n def label {A : Type} (xs : list A) : list (nat × A) := zip (upto (list.length xs)) xs -- lemma label_size_eq : -- forall A (xs : list A), -- list.length (label xs) = list.length xs := -- begin -- intros, -- induction xs, -- apply sorry -- apply sorry -- end -- HELPERS -- meta def assert_name : ir.expr → ir_compiler name | (ir.expr.locl n) := lift_result $ native.result.ok n | e := mk_error $ "expected name found: " ++ to_string (format_cpp.expr e) meta def assert_expr : ir.stmt → ir_compiler ir.expr | (ir.stmt.e exp) := return exp | s := mk_error ("internal invariant violated, found: " ++ (to_string (format_cpp.stmt s))) meta def mk_call (head : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', return (ir.expr.call head args') meta def mk_under_sat_call (head : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', return $ ir.expr.mk_native_closure head args' meta def bind_value_with_ty (val : ir.expr) (ty : ir.ty) (body : name → ir_compiler ir.stmt) : ir_compiler ir.stmt := do fresh ← fresh_name, ir.stmt.letb fresh ty val <$> (body fresh) meta def bind_value (val : ir.expr) (body : name → ir_compiler ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty val ir.ty.object body -- not in love with this --solution-- hack, revisit meta def compile_local (n : name) : ir_compiler name := return $ (mk_str_name "_$local$_" (name.to_string_with_sep "_" n)) meta def mk_invoke (loc : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', loc' ← compile_local loc, lift_result (native.result.ok $ ir.expr.invoke loc' args') meta def mk_over_sat_call (head : name) (fst snd : list ir.expr) : ir_compiler ir.expr := let fst' := list.map assert_name fst, snd' := list.map assert_name snd in do args' ← monad.sequence fst', args'' ← monad.sequence snd', fresh ← fresh_name, locl ← compile_local fresh, invoke ← ir.stmt.e <$> (mk_invoke fresh (fmap ir.expr.locl args'')), return $ ir.expr.block (ir.stmt.seq [ ir.stmt.letb locl ir.ty.object (ir.expr.call head args') ir.stmt.nop, invoke ]) meta def is_return (n : name) : bool := decidable.to_bool $ `native_compiler.return = n meta def compile_call (head : name) (arity : nat) (args : list ir.expr) : ir_compiler ir.expr := do trace_ir $ "compile_call: " ++ (to_string head), if list.length args = arity then mk_call head args else if list.length args < arity then mk_under_sat_call head args else mk_over_sat_call head (list.taken arity args) (list.dropn arity args) meta def mk_object (arity : unsigned) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', lift_result (native.result.ok $ ir.expr.mk_object (unsigned.to_nat arity) args') meta def one_or_error (args : list expr) : ir_compiler expr := match args with | ((h : expr) :: []) := lift_result $ native.result.ok h | _ := mk_error "internal invariant violated, should only have one argument" end meta def panic (msg : string) : ir_compiler ir.expr := return $ ir.expr.panic msg -- END HELPERS -- meta def bind_case_fields' (scrut : name) : list (nat × name) → ir.stmt → ir_compiler ir.stmt | [] body := return body | ((n, f) :: fs) body := do loc ← compile_local f, ir.stmt.letb f ir.ty.object (ir.expr.project scrut n) <$> (bind_case_fields' fs body) meta def bind_case_fields (scrut : name) (fs : list name) (body : ir.stmt) : ir_compiler ir.stmt := bind_case_fields' scrut (label fs) body meta def mk_cases_on (case_name scrut : name) (cases : list (nat × ir.stmt)) (default : ir.stmt) : ir.stmt := ir.stmt.seq [ ir.stmt.letb `ctor_index ir.ty.int (ir.expr.call `cidx [scrut]) ir.stmt.nop, ir.stmt.switch `ctor_index cases default ] meta def compile_cases (action : expr → ir_compiler ir.stmt) (scrut : name) : list (nat × expr) → ir_compiler (list (nat × ir.stmt)) | [] := return [] | ((n, body) :: cs) := do (fs, body') ← take_arguments body, body'' ← action body', cs' ← compile_cases cs, case ← bind_case_fields scrut fs body'', return $ (n, case) :: cs' meta def compile_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do default ← panic "default case should never be reached", match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, ir.expr.block <$> bind_value ir_scrut (fun scrut, do cs' ← compile_cases action scrut (label cs), return (mk_cases_on case_name scrut cs' (ir.stmt.e default))) end meta def bind_builtin_case_fields' (scrut : name) : list (nat × name) → ir.stmt → ir_compiler ir.stmt | [] body := return body | ((n, f) :: fs) body := do loc ← compile_local f, ir.stmt.letb loc ir.ty.object (ir.expr.project scrut n) <$> (bind_builtin_case_fields' fs body) meta def bind_builtin_case_fields (scrut : name) (fs : list name) (body : ir.stmt) : ir_compiler ir.stmt := bind_builtin_case_fields' scrut (label fs) body meta def compile_builtin_cases (action : expr → ir_compiler ir.stmt) (scrut : name) : list (nat × expr) → ir_compiler (list (nat × ir.stmt)) | [] := return [] | ((n, body) :: cs) := do (fs, body') ← take_arguments body, body'' ← action body', cs' ← compile_builtin_cases cs, case ← bind_builtin_case_fields scrut fs body'', return $ (n, case) :: cs' meta def in_lean_ns (n : name) : name := mk_simple_name ("lean::" ++ name.to_string_with_sep "_" n) meta def mk_builtin_cases_on (case_name scrut : name) (cases : list (nat × ir.stmt)) (default : ir.stmt) : ir.stmt := -- replace `ctor_index with a generated name ir.stmt.seq [ ir.stmt.letb `buffer ir.ty.object_buffer ir.expr.uninitialized ir.stmt.nop, ir.stmt.letb `ctor_index ir.ty.int (ir.expr.call (in_lean_ns case_name) [scrut, `buffer]) ir.stmt.nop, ir.stmt.switch `ctor_index cases default ] meta def compile_builtin_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do default ← panic "default case should never be reached", match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, ir.expr.block <$> bind_value ir_scrut (fun scrut, do cs' ← compile_builtin_cases action scrut (label cs), return (mk_builtin_cases_on case_name scrut cs' (ir.stmt.e default))) end meta def mk_is_simple (scrut : name) : ir.expr := ir.expr.call `is_simple [scrut] meta def mk_is_zero (n : name) : ir.expr := ir.expr.equals (ir.expr.raw_int 0) (ir.expr.locl n) meta def mk_cidx (obj : name) : ir.expr := ir.expr.call `cidx [obj] -- we should add applicative brackets meta def mk_simple_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty (mk_cidx scrut) (ir.ty.name `int) (fun cidx, bind_value_with_ty (mk_is_zero cidx) (ir.ty.name `bool) (fun is_zero, pure $ ir.stmt.ite is_zero zero_case succ_case)) meta def mk_mpz_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := ir.stmt.e <$> panic "mpz" meta def mk_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty (mk_is_simple scrut) (ir.ty.name `bool) (fun is_simple, ir.stmt.ite is_simple <$> mk_simple_nat_cases_on scrut zero_case succ_case <*> mk_mpz_nat_cases_on scrut zero_case succ_case) meta def assert_two_cases (cases : list expr) : ir_compiler (expr × expr) := match cases with | c1 :: c2 :: _ := return (c1, c2) | _ := mk_error "nat.cases_on should have exactly two cases" end meta def mk_vm_nat (n : name) : ir.expr := ir.expr.call (in_lean_ns `mk_vm_simple) [n] meta def compile_succ_case (action : expr → ir_compiler ir.stmt) (scrut : name) (succ_case : expr) : ir_compiler ir.stmt := do (fs, body') ← take_arguments succ_case, body'' ← action body', match fs with | pred :: _ := do loc ← compile_local pred, fresh ← fresh_name, bind_value_with_ty (mk_cidx scrut) (ir.ty.name `int) (fun cidx, bind_value_with_ty (ir.expr.sub (ir.expr.locl cidx) (ir.expr.raw_int 1)) (ir.ty.name `int) (fun sub, pure $ ir.stmt.letb loc ir.ty.object (mk_vm_nat sub) body'' )) | _ := mk_error "compile_succ_case too many fields" end meta def compile_nat_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, (zero_case, succ_case) ← assert_two_cases cs, trace_ir (to_string zero_case), trace_ir (to_string succ_case), ir.expr.block <$> bind_value ir_scrut (fun scrut, do zc ← action zero_case, sc ← compile_succ_case action scrut succ_case, mk_nat_cases_on scrut zc sc ) end -- this→emit_indented("if (is_simple("); -- action(scrutinee); -- this→emit_string("))"); -- this→emit_block([&] () { -- this→emit_indented("if (cidx("); -- action(scrutinee); -- this→emit_string(") == 0) "); -- this→emit_block([&] () { -- action(zero_case); -- *this→m_output_stream << ";\n"; -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- action(succ_case); -- *this→m_output_stream << ";\n"; -- }); -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- this→emit_indented("if (to_mpz("); -- action(scrutinee); -- this→emit_string(") == 0) "); -- this→emit_block([&] () { -- action(zero_case); -- *this→m_output_stream << ";\n"; -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- action(succ_case); -- }); -- }); -- this code isnt' great working around the semi-functional frontend meta def compile_expr_app_to_ir_expr (head : expr) (args : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do trace_ir (to_string head ++ to_string args), if expr.is_constant head = bool.tt then (if is_return (expr.const_name head) then do rexp ← one_or_error args, (ir.expr.block ∘ ir.stmt.return) <$> ((action rexp) >>= assert_expr) else if is_nat_cases_on (expr.const_name head) then compile_nat_cases_on_to_ir_expr (expr.const_name head) args action else match is_internal_cnstr head with | option.some n := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, mk_object n args' | option.none := match is_internal_cases head with | option.some n := compile_cases_on_to_ir_expr (expr.const_name head) args action | option.none := match get_builtin (expr.const_name head) with | option.some builtin := match builtin with | builtin.vm n := mk_error "vm" | builtin.cfun n arity := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, compile_call n arity args' | builtin.cases n arity := compile_builtin_cases_on_to_ir_expr (expr.const_name head) args action end | option.none := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, arity ← lookup_arity (expr.const_name head), compile_call (expr.const_name head) arity args' end end end) else if expr.is_local_constant head then do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, mk_invoke (expr.local_uniq_name head) args' else (mk_error ("unsupported call position" ++ (to_string head))) meta def compile_expr_macro_to_ir_expr (e : expr) : ir_compiler ir.expr := match native.get_nat_value e with | option.none := mk_error "unsupported macro" | option.some n := mk_nat_literal n end meta def compile_expr_to_ir_expr (action : expr → ir_compiler ir.stmt): expr → ir_compiler ir.expr | (expr.const n ls) := match native.is_internal_cnstr (expr.const n ls) with | option.none := -- TODO, do I need to case on arity here? I should probably always emit a call match get_builtin n with | option.some (builtin.cfun n' arity) := compile_call n arity [] | _ := if n = "_neutral_" then (pure $ ir.expr.mk_object 0 []) else do arity ← lookup_arity n, compile_call n arity [] end | option.some arity := pure $ ir.expr.mk_object (unsigned.to_nat arity) [] end | (expr.var i) := mk_error "there should be no bound variables in compiled terms" | (expr.sort _) := mk_error "found sort" | (expr.mvar _ _) := mk_error "unexpected meta-variable in expr" | (expr.local_const n _ _ _) := ir.expr.locl <$> compile_local n | (expr.app f x) := let head := expr.get_app_fn (expr.app f x), args := expr.get_app_args (expr.app f x) in compile_expr_app_to_ir_expr head args action | (expr.lam _ _ _ _) := mk_error "found lam" | (expr.pi _ _ _ _) := mk_error "found pi" | (expr.elet n _ v body) := mk_error "internal error: can not translate let binding into a ir_expr" | (expr.macro d sz args) := compile_expr_macro_to_ir_expr (expr.macro d sz args) meta def compile_expr_to_ir_stmt : expr → ir_compiler ir.stmt | (expr.pi _ _ _ _) := mk_error "found pi, should not be translating a Pi for any reason (yet ...)" | (expr.elet n _ v body) := do n' ← compile_local n, v' ← compile_expr_to_ir_expr compile_expr_to_ir_stmt v, -- this is a scoping fail, we need to fix how we compile locals body' ← compile_expr_to_ir_stmt (expr.instantiate_vars body [mk_local n]), -- not the best solution, here need to think hard about how to prevent thing, more aggressive anf? match v' with | ir.expr.block stmt := return (ir.stmt.seq [ir.stmt.letb n' ir.ty.object ir.expr.uninitialized ir.stmt.nop, body']) | _ := return (ir.stmt.letb n' ir.ty.object v' body') end | e' := ir.stmt.e <$> compile_expr_to_ir_expr compile_expr_to_ir_stmt e' meta def compile_defn_to_ir (decl_name : name) (args : list name) (body : expr) : ir_compiler ir.defn := do body' ← compile_expr_to_ir_stmt body, let params := (zip args (repeat (list.length args) (ir.ty.ref ir.ty.object))) in pure (ir.defn.mk decl_name params ir.ty.object body') def unwrap_or_else {T R : Type} : ir_result T → (T → R) → (error → R) → R | (native.result.err e) f err := err e | (native.result.ok t) f err := f t meta def replace_main (n : name) : name := if n = `main then "___lean__main" else n meta def trace_expr (e : expr) : ir_compiler unit := trace ("trace_expr: " ++ to_string e) (fun u, return ()) meta def compile_defn (decl_name : name) (e : expr) : ir_compiler format := let arity := get_arity e in do (args, body) ← take_arguments e, ir ← compile_defn_to_ir (replace_main decl_name) args body, return $ format_cpp.defn ir meta def compile' : list (name × expr) → list (ir_compiler format) | [] := [] | ((n, e) :: rest) := do let decl := (fun d, d ++ format.line ++ format.line) <$> compile_defn n e in decl :: (compile' rest) meta def format_error : error → format | (error.string s) := to_fmt s | (error.many es) := format_concat (list.map format_error es) meta def mk_lean_name (n : name) : ir.expr := ir.expr.constructor (in_lean_ns `name) (name.components n) meta def emit_declare_vm_builtins : list (name × expr) → ir_compiler (list ir.stmt) | [] := return [] | ((n, body) :: es) := do vm_name ← pure $ (mk_lean_name n), tail ← emit_declare_vm_builtins es, fresh ← fresh_name, let cpp_name := in_lean_ns `name, single_binding := ir.stmt.seq [ ir.stmt.letb fresh (ir.ty.name cpp_name) vm_name ir.stmt.nop, ir.stmt.e $ ir.expr.assign `env (ir.expr.call `add_native [`env, fresh, replace_main n]) ] in return $ single_binding :: tail meta def emit_main (procs : list (name × expr)) : ir_compiler ir.defn := do builtins ← emit_declare_vm_builtins procs, arity ← lookup_arity `main, vm_simple_obj ← fresh_name, call_main ← compile_call "___lean__main" arity [ir.expr.locl vm_simple_obj], return (ir.defn.mk `main [] ir.ty.int $ ir.stmt.seq ([ ir.stmt.e $ ir.expr.call (in_lean_ns `initialize) [], ir.stmt.letb `env (ir.ty.name (in_lean_ns `environment)) ir.expr.uninitialized ir.stmt.nop ] ++ builtins ++ [ ir.stmt.letb `ios (ir.ty.name (in_lean_ns `io_state)) (ir.expr.call (in_lean_ns `get_global_ios) []) ir.stmt.nop, ir.stmt.letb `opts (ir.ty.name (in_lean_ns `options)) (ir.expr.call (in_lean_ns `get_options_from_ios) [`ios]) ir.stmt.nop, ir.stmt.letb `S (ir.ty.name (in_lean_ns `vm_state)) (ir.expr.constructor (in_lean_ns `vm_state) [`env, `opts]) ir.stmt.nop, ir.stmt.letb `scoped (ir.ty.name (in_lean_ns `scope_vm_state)) (ir.expr.constructor (in_lean_ns `scope_vm_state) [`S]) ir.stmt.nop, ir.stmt.e $ ir.expr.assign `g_env (ir.expr.address_of `env), ir.stmt.letb vm_simple_obj ir.ty.object (ir.expr.mk_object 0 []) ir.stmt.nop, ir.stmt.e call_main ])) -- -- call_mains -- -- buffer<expr> args; -- -- auto unit = mk_neutral_expr(); -- -- args.push_back(unit); -- -- // Make sure to invoke the C call machinery since it is non-deterministic -- -- // which case we enter here. -- -- compile_to_c_call(main_fn, args, 0, name_map<unsigned>()); -- -- *this→m_output_stream << ";\n return 0;\n}" << std::endl; -- ] meta def unzip {A B} : list (A × B) → (list A × list B) | [] := ([], []) | ((x, y) :: rest) := let (xs, ys) := unzip rest in (x :: xs, y :: ys) meta def configuration : ir_compiler config := do (conf, _, _) ← lift $ state.read, pure conf meta def apply_pre_ir_passes (procs : list procedure) (conf : config) : list procedure := run_passes conf [anf, cf] procs meta def driver (procs : list (name × expr)) : ir_compiler (list format × list error) := do procs' ← apply_pre_ir_passes procs <$> configuration, (fmt_decls, errs) ← sequence_err (compile' procs'), main ← emit_main procs', return (format_cpp.defn main :: fmt_decls, errs) meta def compile (conf : config) (procs : list (name × expr)) : format := let arities := mk_arity_map procs in -- Put this in a combinator or something ... match run (driver procs) (conf, arities, 0) with | (native.result.err e, s) := error.to_string e | (native.result.ok (decls, errs), s) := if list.length errs = 0 then format_concat decls else format_error (error.many errs) end -- meta def compile (procs : list (name)) end native
3e6ab68bc1560f39f7be17d4239ed17569df62d6
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/RingoidSig.lean
73fba5aa723806f7b686d57993ad1bee6f1718f6
[]
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
8,442
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 RingoidSig structure RingoidSig (A : Type) : Type := (times : (A → (A → A))) (plus : (A → (A → A))) open RingoidSig 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)))) structure Hom {A1 : Type} {A2 : Type} (Ri1 : (RingoidSig A1)) (Ri2 : (RingoidSig A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Ri1) x1 x2)) = ((times Ri2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ri1) x1 x2)) = ((plus Ri2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (RingoidSig A1)) (Ri2 : (RingoidSig A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Ri1) x1 x2) ((times Ri2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ri1) x1 x2) ((plus Ri2) y1 y2)))))) inductive RingoidSigTerm : Type | timesL : (RingoidSigTerm → (RingoidSigTerm → RingoidSigTerm)) | plusL : (RingoidSigTerm → (RingoidSigTerm → RingoidSigTerm)) open RingoidSigTerm inductive ClRingoidSigTerm (A : Type) : Type | sing : (A → ClRingoidSigTerm) | timesCl : (ClRingoidSigTerm → (ClRingoidSigTerm → ClRingoidSigTerm)) | plusCl : (ClRingoidSigTerm → (ClRingoidSigTerm → ClRingoidSigTerm)) open ClRingoidSigTerm inductive OpRingoidSigTerm (n : ℕ) : Type | v : ((fin n) → OpRingoidSigTerm) | timesOL : (OpRingoidSigTerm → (OpRingoidSigTerm → OpRingoidSigTerm)) | plusOL : (OpRingoidSigTerm → (OpRingoidSigTerm → OpRingoidSigTerm)) open OpRingoidSigTerm inductive OpRingoidSigTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRingoidSigTerm2) | sing2 : (A → OpRingoidSigTerm2) | timesOL2 : (OpRingoidSigTerm2 → (OpRingoidSigTerm2 → OpRingoidSigTerm2)) | plusOL2 : (OpRingoidSigTerm2 → (OpRingoidSigTerm2 → OpRingoidSigTerm2)) open OpRingoidSigTerm2 def simplifyCl {A : Type} : ((ClRingoidSigTerm A) → (ClRingoidSigTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRingoidSigTerm n) → (OpRingoidSigTerm 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} : ((OpRingoidSigTerm2 n A) → (OpRingoidSigTerm2 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} : ((RingoidSig A) → (RingoidSigTerm → A)) | Ri (timesL x1 x2) := ((times Ri) (evalB Ri x1) (evalB Ri x2)) | Ri (plusL x1 x2) := ((plus Ri) (evalB Ri x1) (evalB Ri x2)) def evalCl {A : Type} : ((RingoidSig A) → ((ClRingoidSigTerm A) → A)) | Ri (sing x1) := x1 | Ri (timesCl x1 x2) := ((times Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri (plusCl x1 x2) := ((plus Ri) (evalCl Ri x1) (evalCl Ri x2)) def evalOpB {A : Type} {n : ℕ} : ((RingoidSig A) → ((vector A n) → ((OpRingoidSigTerm n) → A))) | Ri vars (v x1) := (nth vars x1) | Ri vars (timesOL x1 x2) := ((times Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars (plusOL x1 x2) := ((plus Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) def evalOp {A : Type} {n : ℕ} : ((RingoidSig A) → ((vector A n) → ((OpRingoidSigTerm2 n A) → A))) | Ri vars (v2 x1) := (nth vars x1) | Ri vars (sing2 x1) := x1 | Ri vars (timesOL2 x1 x2) := ((times Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars (plusOL2 x1 x2) := ((plus Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) def inductionB {P : (RingoidSigTerm → Type)} : ((∀ (x1 x2 : RingoidSigTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : RingoidSigTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : RingoidSigTerm) , (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 : ((ClRingoidSigTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRingoidSigTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClRingoidSigTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClRingoidSigTerm 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 : ((OpRingoidSigTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRingoidSigTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpRingoidSigTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpRingoidSigTerm 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 : ((OpRingoidSigTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRingoidSigTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpRingoidSigTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpRingoidSigTerm2 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 : (RingoidSigTerm → (Staged RingoidSigTerm)) | (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} : ((ClRingoidSigTerm A) → (Staged (ClRingoidSigTerm 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 : ℕ} : ((OpRingoidSigTerm n) → (Staged (OpRingoidSigTerm 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} : ((OpRingoidSigTerm2 n A) → (Staged (OpRingoidSigTerm2 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 RingoidSig
04ab6e5878cf366c7775e8ed5192a95de6e7b46a
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/linear_algebra/affine_space/independent.lean
8170a8ef8e90d07433d7df88469d7ad42ea290f3
[ "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
24,457
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import data.finset.sort import data.matrix.notation import linear_algebra.affine_space.combination import linear_algebra.basis /-! # Affine independence This file defines affinely independent families of points. ## Main definitions * `affine_independent` defines affinely independent families of points as those where no nontrivial weighted subtraction is 0. This is proved equivalent to two other formulations: linear independence of the results of subtracting a base point in the family from the other points in the family, or any equal affine combinations having the same weights. A bundled type `simplex` is provided for finite affinely independent families of points, with an abbreviation `triangle` for the case of three points. ## References * https://en.wikipedia.org/wiki/Affine_space -/ noncomputable theory open_locale big_operators classical affine open function section affine_independent variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} include V /-- An indexed family is said to be affinely independent if no nontrivial weighted subtractions (where the sum of weights is 0) are 0. -/ def affine_independent (p : ι → P) : Prop := ∀ (s : finset ι) (w : ι → k), ∑ i in s, w i = 0 → s.weighted_vsub p w = (0:V) → ∀ i ∈ s, w i = 0 /-- The definition of `affine_independent`. -/ lemma affine_independent_def (p : ι → P) : affine_independent k p ↔ ∀ (s : finset ι) (w : ι → k), ∑ i in s, w i = 0 → s.weighted_vsub p w = (0 : V) → ∀ i ∈ s, w i = 0 := iff.rfl /-- A family with at most one point is affinely independent. -/ lemma affine_independent_of_subsingleton [subsingleton ι] (p : ι → P) : affine_independent k p := λ s w h hs i hi, fintype.eq_of_subsingleton_of_sum_eq h i hi /-- A family indexed by a `fintype` is affinely independent if and only if no nontrivial weighted subtractions over `finset.univ` (where the sum of the weights is 0) are 0. -/ lemma affine_independent_iff_of_fintype [fintype ι] (p : ι → P) : affine_independent k p ↔ ∀ w : ι → k, ∑ i, w i = 0 → finset.univ.weighted_vsub p w = (0 : V) → ∀ i, w i = 0 := begin split, { exact λ h w hw hs i, h finset.univ w hw hs i (finset.mem_univ _) }, { intros h s w hw hs i hi, rw finset.weighted_vsub_indicator_subset _ _ (finset.subset_univ s) at hs, rw set.sum_indicator_subset _ (finset.subset_univ s) at hw, replace h := h ((↑s : set ι).indicator w) hw hs i, simpa [hi] using h } end /-- A family is affinely independent if and only if the differences from a base point in that family are linearly independent. -/ lemma affine_independent_iff_linear_independent_vsub (p : ι → P) (i1 : ι) : affine_independent k p ↔ linear_independent k (λ i : {x // x ≠ i1}, (p i -ᵥ p i1 : V)) := begin split, { intro h, rw linear_independent_iff', intros s g hg i hi, set f : ι → k := λ x, if hx : x = i1 then -∑ y in s, g y else g ⟨x, hx⟩ with hfdef, let s2 : finset ι := insert i1 (s.map (embedding.subtype _)), have hfg : ∀ x : {x // x ≠ i1}, g x = f x, { intro x, rw hfdef, dsimp only [], erw [dif_neg x.property, subtype.coe_eta] }, rw hfg, have hf : ∑ ι in s2, f ι = 0, { rw [finset.sum_insert (finset.not_mem_map_subtype_of_not_property s (not_not.2 rfl)), finset.sum_subtype_map_embedding (λ x hx, (hfg x).symm)], rw hfdef, dsimp only [], rw dif_pos rfl, exact neg_add_self _ }, have hs2 : s2.weighted_vsub p f = (0:V), { set f2 : ι → V := λ x, f x • (p x -ᵥ p i1) with hf2def, set g2 : {x // x ≠ i1} → V := λ x, g x • (p x -ᵥ p i1) with hg2def, have hf2g2 : ∀ x : {x // x ≠ i1}, f2 x = g2 x, { simp_rw [hf2def, hg2def, hfg], exact λ x, rfl }, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s2 f p hf (p i1), finset.weighted_vsub_of_point_insert, finset.weighted_vsub_of_point_apply, finset.sum_subtype_map_embedding (λ x hx, hf2g2 x)], exact hg }, exact h s2 f hf hs2 i (finset.mem_insert_of_mem (finset.mem_map.2 ⟨i, hi, rfl⟩)) }, { intro h, rw linear_independent_iff' at h, intros s w hw hs i hi, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s w p hw (p i1), ←s.weighted_vsub_of_point_erase w p i1, finset.weighted_vsub_of_point_apply] at hs, let f : ι → V := λ i, w i • (p i -ᵥ p i1), have hs2 : ∑ i in (s.erase i1).subtype (λ i, i ≠ i1), f i = 0, { rw [←hs], convert finset.sum_subtype_of_mem f (λ x, finset.ne_of_mem_erase) }, have h2 := h ((s.erase i1).subtype (λ i, i ≠ i1)) (λ x, w x) hs2, simp_rw [finset.mem_subtype] at h2, have h2b : ∀ i ∈ s, i ≠ i1 → w i = 0 := λ i his hi, h2 ⟨i, hi⟩ (finset.mem_erase_of_ne_of_mem hi his), exact finset.eq_zero_of_sum_eq_zero hw h2b i hi } end /-- A set is affinely independent if and only if the differences from a base point in that set are linearly independent. -/ lemma affine_independent_set_iff_linear_independent_vsub {s : set P} {p₁ : P} (hp₁ : p₁ ∈ s) : affine_independent k (λ p, p : s → P) ↔ linear_independent k (λ v, v : (λ p, (p -ᵥ p₁ : V)) '' (s \ {p₁}) → V) := begin rw affine_independent_iff_linear_independent_vsub k (λ p, p : s → P) ⟨p₁, hp₁⟩, split, { intro h, have hv : ∀ v : (λ p, (p -ᵥ p₁ : V)) '' (s \ {p₁}), (v : V) +ᵥ p₁ ∈ s \ {p₁} := λ v, (set.mem_image_of_injective (vsub_left_injective p₁)).1 ((vadd_vsub (v : V) p₁).symm ▸ v.property), let f : (λ p : P, (p -ᵥ p₁ : V)) '' (s \ {p₁}) → {x : s // x ≠ ⟨p₁, hp₁⟩} := λ x, ⟨⟨(x : V) +ᵥ p₁, set.mem_of_mem_diff (hv x)⟩, λ hx, set.not_mem_of_mem_diff (hv x) (subtype.ext_iff.1 hx)⟩, convert h.comp f (λ x1 x2 hx, (subtype.ext (vadd_right_cancel p₁ (subtype.ext_iff.1 (subtype.ext_iff.1 hx))))), ext v, exact (vadd_vsub (v : V) p₁).symm }, { intro h, let f : {x : s // x ≠ ⟨p₁, hp₁⟩} → (λ p : P, (p -ᵥ p₁ : V)) '' (s \ {p₁}) := λ x, ⟨((x : s) : P) -ᵥ p₁, ⟨x, ⟨⟨(x : s).property, λ hx, x.property (subtype.ext hx)⟩, rfl⟩⟩⟩, convert h.comp f (λ x1 x2 hx, subtype.ext (subtype.ext (vsub_left_cancel (subtype.ext_iff.1 hx)))) } end /-- A set of nonzero vectors is linearly independent if and only if, given a point `p₁`, the vectors added to `p₁` and `p₁` itself are affinely independent. -/ lemma linear_independent_set_iff_affine_independent_vadd_union_singleton {s : set V} (hs : ∀ v ∈ s, v ≠ (0 : V)) (p₁ : P) : linear_independent k (λ v, v : s → V) ↔ affine_independent k (λ p, p : {p₁} ∪ ((λ v, v +ᵥ p₁) '' s) → P) := begin rw affine_independent_set_iff_linear_independent_vsub k (set.mem_union_left _ (set.mem_singleton p₁)), have h : (λ p, (p -ᵥ p₁ : V)) '' (({p₁} ∪ (λ v, v +ᵥ p₁) '' s) \ {p₁}) = s, { simp_rw [set.union_diff_left, set.image_diff (vsub_left_injective p₁), set.image_image, set.image_singleton, vsub_self, vadd_vsub, set.image_id'], exact set.diff_singleton_eq_self (λ h, hs 0 h rfl) }, rw h end /-- A family is affinely independent if and only if any affine combinations (with sum of weights 1) that evaluate to the same point have equal `set.indicator`. -/ lemma affine_independent_iff_indicator_eq_of_affine_combination_eq (p : ι → P) : affine_independent k p ↔ ∀ (s1 s2 : finset ι) (w1 w2 : ι → k), ∑ i in s1, w1 i = 1 → ∑ i in s2, w2 i = 1 → s1.affine_combination p w1 = s2.affine_combination p w2 → set.indicator ↑s1 w1 = set.indicator ↑s2 w2 := begin split, { intros ha s1 s2 w1 w2 hw1 hw2 heq, ext i, by_cases hi : i ∈ (s1 ∪ s2), { rw ←sub_eq_zero, rw set.sum_indicator_subset _ (finset.subset_union_left s1 s2) at hw1, rw set.sum_indicator_subset _ (finset.subset_union_right s1 s2) at hw2, have hws : ∑ i in s1 ∪ s2, (set.indicator ↑s1 w1 - set.indicator ↑s2 w2) i = 0, { simp [hw1, hw2] }, rw [finset.affine_combination_indicator_subset _ _ (finset.subset_union_left s1 s2), finset.affine_combination_indicator_subset _ _ (finset.subset_union_right s1 s2), ←@vsub_eq_zero_iff_eq V, finset.affine_combination_vsub] at heq, exact ha (s1 ∪ s2) (set.indicator ↑s1 w1 - set.indicator ↑s2 w2) hws heq i hi }, { rw [←finset.mem_coe, finset.coe_union] at hi, simp [mt (set.mem_union_left ↑s2) hi, mt (set.mem_union_right ↑s1) hi] } }, { intros ha s w hw hs i0 hi0, let w1 : ι → k := function.update (function.const ι 0) i0 1, have hw1 : ∑ i in s, w1 i = 1, { rw [finset.sum_update_of_mem hi0, finset.sum_const_zero, add_zero] }, have hw1s : s.affine_combination p w1 = p i0 := s.affine_combination_of_eq_one_of_eq_zero w1 p hi0 (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), let w2 := w + w1, have hw2 : ∑ i in s, w2 i = 1, { simp [w2, finset.sum_add_distrib, hw, hw1] }, have hw2s : s.affine_combination p w2 = p i0, { simp [w2, ←finset.weighted_vsub_vadd_affine_combination, hs, hw1s] }, replace ha := ha s s w2 w1 hw2 hw1 (hw1s.symm ▸ hw2s), have hws : w2 i0 - w1 i0 = 0, { rw ←finset.mem_coe at hi0, rw [←set.indicator_of_mem hi0 w2, ←set.indicator_of_mem hi0 w1, ha, sub_self] }, simpa [w2] using hws } end variables {k} /-- An affinely independent family is injective, if the underlying ring is nontrivial. -/ lemma injective_of_affine_independent [nontrivial k] {p : ι → P} (ha : affine_independent k p) : function.injective p := begin intros i j hij, rw affine_independent_iff_linear_independent_vsub _ _ j at ha, by_contra hij', exact ha.ne_zero ⟨i, hij'⟩ (vsub_eq_zero_iff_eq.mpr hij) end /-- If a family is affinely independent, so is any subfamily given by composition of an embedding into index type with the original family. -/ lemma affine_independent_embedding_of_affine_independent {ι2 : Type*} (f : ι2 ↪ ι) {p : ι → P} (ha : affine_independent k p) : affine_independent k (p ∘ f) := begin intros fs w hw hs i0 hi0, let fs' := fs.map f, let w' := λ i, if h : ∃ i2, f i2 = i then w h.some else 0, have hw' : ∀ i2 : ι2, w' (f i2) = w i2, { intro i2, have h : ∃ i : ι2, f i = f i2 := ⟨i2, rfl⟩, have hs : h.some = i2 := f.injective h.some_spec, simp_rw [w', dif_pos h, hs] }, have hw's : ∑ i in fs', w' i = 0, { rw [←hw, finset.sum_map], simp [hw'] }, have hs' : fs'.weighted_vsub p w' = (0:V), { rw [←hs, finset.weighted_vsub_map], congr' with i, simp [hw'] }, rw [←ha fs' w' hw's hs' (f i0) ((finset.mem_map' _).2 hi0), hw'] end /-- If a family is affinely independent, so is any subfamily indexed by a subtype of the index type. -/ lemma affine_independent_subtype_of_affine_independent {p : ι → P} (ha : affine_independent k p) (s : set ι) : affine_independent k (λ i : s, p i) := affine_independent_embedding_of_affine_independent (embedding.subtype _) ha /-- If an indexed family of points is affinely independent, so is the corresponding set of points. -/ lemma affine_independent_set_of_affine_independent {p : ι → P} (ha : affine_independent k p) : affine_independent k (λ x, x : set.range p → P) := begin let f : set.range p → ι := λ x, x.property.some, have hf : ∀ x, p (f x) = x := λ x, x.property.some_spec, let fe : set.range p ↪ ι := ⟨f, λ x₁ x₂ he, subtype.ext (hf x₁ ▸ hf x₂ ▸ he ▸ rfl)⟩, convert affine_independent_embedding_of_affine_independent fe ha, ext, simp [hf] end /-- If a set of points is affinely independent, so is any subset. -/ lemma affine_independent_of_subset_affine_independent {s t : set P} (ha : affine_independent k (λ x, x : t → P)) (hs : s ⊆ t) : affine_independent k (λ x, x : s → P) := affine_independent_embedding_of_affine_independent (set.embedding_of_subset s t hs) ha /-- If the range of an injective indexed family of points is affinely independent, so is that family. -/ lemma affine_independent_of_affine_independent_set_of_injective {p : ι → P} (ha : affine_independent k (λ x, x : set.range p → P)) (hi : function.injective p) : affine_independent k p := affine_independent_embedding_of_affine_independent (⟨λ i, ⟨p i, set.mem_range_self _⟩, λ x y h, hi (subtype.mk_eq_mk.1 h)⟩ : ι ↪ set.range p) ha /-- If a family is affinely independent, and the spans of points indexed by two subsets of the index type have a point in common, those subsets of the index type have an element in common, if the underlying ring is nontrivial. -/ lemma exists_mem_inter_of_exists_mem_inter_affine_span_of_affine_independent [nontrivial k] {p : ι → P} (ha : affine_independent k p) {s1 s2 : set ι} {p0 : P} (hp0s1 : p0 ∈ affine_span k (p '' s1)) (hp0s2 : p0 ∈ affine_span k (p '' s2)): ∃ (i : ι), i ∈ s1 ∩ s2 := begin rw set.image_eq_range at hp0s1 hp0s2, rw [mem_affine_span_iff_eq_affine_combination, ←finset.eq_affine_combination_subset_iff_eq_affine_combination_subtype] at hp0s1 hp0s2, rcases hp0s1 with ⟨fs1, hfs1, w1, hw1, hp0s1⟩, rcases hp0s2 with ⟨fs2, hfs2, w2, hw2, hp0s2⟩, rw affine_independent_iff_indicator_eq_of_affine_combination_eq at ha, replace ha := ha fs1 fs2 w1 w2 hw1 hw2 (hp0s1 ▸ hp0s2), have hnz : ∑ i in fs1, w1 i ≠ 0 := hw1.symm ▸ one_ne_zero, rcases finset.exists_ne_zero_of_sum_ne_zero hnz with ⟨i, hifs1, hinz⟩, simp_rw [←set.indicator_of_mem (finset.mem_coe.2 hifs1) w1, ha] at hinz, use [i, hfs1 hifs1, hfs2 (set.mem_of_indicator_ne_zero hinz)] end /-- If a family is affinely independent, the spans of points indexed by disjoint subsets of the index type are disjoint, if the underlying ring is nontrivial. -/ lemma affine_span_disjoint_of_disjoint_of_affine_independent [nontrivial k] {p : ι → P} (ha : affine_independent k p) {s1 s2 : set ι} (hd : s1 ∩ s2 = ∅) : (affine_span k (p '' s1) : set P) ∩ affine_span k (p '' s2) = ∅ := begin by_contradiction hne, change (affine_span k (p '' s1) : set P) ∩ affine_span k (p '' s2) ≠ ∅ at hne, rw set.ne_empty_iff_nonempty at hne, rcases hne with ⟨p0, hp0s1, hp0s2⟩, cases exists_mem_inter_of_exists_mem_inter_affine_span_of_affine_independent ha hp0s1 hp0s2 with i hi, exact set.not_mem_empty i (hd ▸ hi) end /-- If a family is affinely independent, a point in the family is in the span of some of the points given by a subset of the index type if and only if that point's index is in the subset, if the underlying ring is nontrivial. -/ @[simp] lemma mem_affine_span_iff_mem_of_affine_independent [nontrivial k] {p : ι → P} (ha : affine_independent k p) (i : ι) (s : set ι) : p i ∈ affine_span k (p '' s) ↔ i ∈ s := begin split, { intro hs, have h := exists_mem_inter_of_exists_mem_inter_affine_span_of_affine_independent ha hs (mem_affine_span k (set.mem_image_of_mem _ (set.mem_singleton _))), rwa [←set.nonempty_def, set.inter_singleton_nonempty] at h }, { exact λ h, mem_affine_span k (set.mem_image_of_mem p h) } end /-- If a family is affinely independent, a point in the family is not in the affine span of the other points, if the underlying ring is nontrivial. -/ lemma not_mem_affine_span_diff_of_affine_independent [nontrivial k] {p : ι → P} (ha : affine_independent k p) (i : ι) (s : set ι) : p i ∉ affine_span k (p '' (s \ {i})) := by simp [ha] end affine_independent section field variables {k : Type*} {V : Type*} {P : Type*} [field k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} include V /-- An affinely independent set of points can be extended to such a set that spans the whole space. -/ lemma exists_subset_affine_independent_affine_span_eq_top {s : set P} (h : affine_independent k (λ p, p : s → P)) : ∃ t : set P, s ⊆ t ∧ affine_independent k (λ p, p : t → P) ∧ affine_span k t = ⊤ := begin rcases s.eq_empty_or_nonempty with rfl | ⟨p₁, hp₁⟩, { have p₁ : P := add_torsor.nonempty.some, rcases exists_is_basis k V with ⟨sv, hsvi, hsvt⟩, have h0 : ∀ v : V, v ∈ sv → v ≠ 0, { intros v hv, change ((⟨v, hv⟩ : sv) : V) ≠ 0, exact hsvi.ne_zero _ }, rw linear_independent_set_iff_affine_independent_vadd_union_singleton k h0 p₁ at hsvi, use [{p₁} ∪ (λ v, v +ᵥ p₁) '' sv, set.empty_subset _, hsvi, affine_span_singleton_union_vadd_eq_top_of_span_eq_top p₁ hsvt] }, { rw affine_independent_set_iff_linear_independent_vsub k hp₁ at h, rcases exists_subset_is_basis h with ⟨sv, hsv, hsvi, hsvt⟩, have h0 : ∀ v : V, v ∈ sv → v ≠ 0, { intros v hv, change ((⟨v, hv⟩ : sv) : V) ≠ 0, exact hsvi.ne_zero _ }, rw linear_independent_set_iff_affine_independent_vadd_union_singleton k h0 p₁ at hsvi, use {p₁} ∪ (λ v, v +ᵥ p₁) '' sv, split, { refine set.subset.trans _ (set.union_subset_union_right _ (set.image_subset _ hsv)), simp [set.image_image] }, { use [hsvi, affine_span_singleton_union_vadd_eq_top_of_span_eq_top p₁ hsvt] } } end variables (k) /-- Two different points are affinely independent. -/ lemma affine_independent_of_ne {p₁ p₂ : P} (h : p₁ ≠ p₂) : affine_independent k ![p₁, p₂] := begin rw affine_independent_iff_linear_independent_vsub k ![p₁, p₂] 0, let i₁ : {x // x ≠ (0 : fin 2)} := ⟨1, dec_trivial⟩, have he' : ∀ i, i = i₁, { rintro ⟨i, hi⟩, ext, fin_cases i, { simpa using hi } }, haveI : unique {x // x ≠ (0 : fin 2)} := ⟨⟨i₁⟩, he'⟩, have hz : (![p₁, p₂] ↑(default {x // x ≠ (0 : fin 2)}) -ᵥ ![p₁, p₂] 0 : V) ≠ 0, { rw he' (default _), intro he, rw vsub_eq_zero_iff_eq at he, exact h he.symm }, exact linear_independent_unique hz end end field namespace affine variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- A `simplex k P n` is a collection of `n + 1` affinely independent points. -/ structure simplex (n : ℕ) := (points : fin (n + 1) → P) (independent : affine_independent k points) /-- A `triangle k P` is a collection of three affinely independent points. -/ abbreviation triangle := simplex k P 2 namespace simplex variables {P} /-- Construct a 0-simplex from a point. -/ def mk_of_point (p : P) : simplex k P 0 := ⟨λ _, p, affine_independent_of_subsingleton k _⟩ /-- The point in a simplex constructed with `mk_of_point`. -/ @[simp] lemma mk_of_point_points (p : P) (i : fin 1) : (mk_of_point k p).points i = p := rfl instance [inhabited P] : inhabited (simplex k P 0) := ⟨mk_of_point k $ default P⟩ instance nonempty : nonempty (simplex k P 0) := ⟨mk_of_point k $ add_torsor.nonempty.some⟩ variables {k V} /-- Two simplices are equal if they have the same points. -/ @[ext] lemma ext {n : ℕ} {s1 s2 : simplex k P n} (h : ∀ i, s1.points i = s2.points i) : s1 = s2 := begin cases s1, cases s2, congr' with i, exact h i end /-- Two simplices are equal if and only if they have the same points. -/ lemma ext_iff {n : ℕ} (s1 s2 : simplex k P n): s1 = s2 ↔ ∀ i, s1.points i = s2.points i := ⟨λ h _, h ▸ rfl, ext⟩ /-- A face of a simplex is a simplex with the given subset of points. -/ def face {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : simplex k P m := ⟨s.points ∘ fs.order_emb_of_fin h, affine_independent_embedding_of_affine_independent (fs.order_emb_of_fin h).to_embedding s.independent⟩ /-- The points of a face of a simplex are given by `mono_of_fin`. -/ lemma face_points {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) (i : fin (m + 1)) : (s.face h).points i = s.points (fs.order_emb_of_fin h i) := rfl /-- The points of a face of a simplex are given by `mono_of_fin`. -/ lemma face_points' {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : (s.face h).points = s.points ∘ (fs.order_emb_of_fin h) := rfl /-- A single-point face equals the 0-simplex constructed with `mk_of_point`. -/ @[simp] lemma face_eq_mk_of_point {n : ℕ} (s : simplex k P n) (i : fin (n + 1)) : s.face (finset.card_singleton i) = mk_of_point k (s.points i) := by { ext, simp [face_points] } /-- The set of points of a face. -/ @[simp] lemma range_face_points {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : set.range (s.face h).points = s.points '' ↑fs := by rw [face_points', set.range_comp, finset.range_order_emb_of_fin] end simplex end affine namespace affine namespace simplex variables {k : Type*} {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The centroid of a face of a simplex as the centroid of a subset of the points. -/ @[simp] lemma face_centroid_eq_centroid {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : finset.univ.centroid k (s.face h).points = fs.centroid k s.points := begin convert (finset.univ.centroid_map k (fs.order_emb_of_fin h).to_embedding s.points).symm, rw [← finset.coe_inj, finset.coe_map, finset.coe_univ, set.image_univ], simp end /-- Over a characteristic-zero division ring, the centroids given by two subsets of the points of a simplex are equal if and only if those faces are given by the same subset of points. -/ @[simp] lemma centroid_eq_iff [char_zero k] {n : ℕ} (s : simplex k P n) {fs₁ fs₂ : finset (fin (n + 1))} {m₁ m₂ : ℕ} (h₁ : fs₁.card = m₁ + 1) (h₂ : fs₂.card = m₂ + 1) : fs₁.centroid k s.points = fs₂.centroid k s.points ↔ fs₁ = fs₂ := begin split, { intro h, rw [finset.centroid_eq_affine_combination_fintype, finset.centroid_eq_affine_combination_fintype] at h, have ha := (affine_independent_iff_indicator_eq_of_affine_combination_eq k s.points).1 s.independent _ _ _ _ (fs₁.sum_centroid_weights_indicator_eq_one_of_card_eq_add_one k h₁) (fs₂.sum_centroid_weights_indicator_eq_one_of_card_eq_add_one k h₂) h, simp_rw [finset.coe_univ, set.indicator_univ, function.funext_iff, finset.centroid_weights_indicator_def, finset.centroid_weights, h₁, h₂] at ha, ext i, replace ha := ha i, split, all_goals { intro hi, by_contradiction hni, simp [hi, hni] at ha, norm_cast at ha } }, { intro h, have hm : m₁ = m₂, { subst h, simpa [h₁] using h₂ }, subst hm, congr, exact h } end /-- Over a characteristic-zero division ring, the centroids of two faces of a simplex are equal if and only if those faces are given by the same subset of points. -/ lemma face_centroid_eq_iff [char_zero k] {n : ℕ} (s : simplex k P n) {fs₁ fs₂ : finset (fin (n + 1))} {m₁ m₂ : ℕ} (h₁ : fs₁.card = m₁ + 1) (h₂ : fs₂.card = m₂ + 1) : finset.univ.centroid k (s.face h₁).points = finset.univ.centroid k (s.face h₂).points ↔ fs₁ = fs₂ := begin rw [face_centroid_eq_centroid, face_centroid_eq_centroid], exact s.centroid_eq_iff h₁ h₂ end /-- Two simplices with the same points have the same centroid. -/ lemma centroid_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex k P n} (h : set.range s₁.points = set.range s₂.points) : finset.univ.centroid k s₁.points = finset.univ.centroid k s₂.points := begin rw [←set.image_univ, ←set.image_univ, ←finset.coe_univ] at h, exact finset.univ.centroid_eq_of_inj_on_of_image_eq k _ (λ _ _ _ _ he, injective_of_affine_independent s₁.independent he) (λ _ _ _ _ he, injective_of_affine_independent s₂.independent he) h end end simplex end affine
45d535e5eacf8af09c6c2f814fe73901ab1ad189
9fbfc7e84d479e54de3c77b32724433407ea166b
/08_Disjunction/00_intro.lean
cc22a3cf0e6d61027a85c2b313ae72c17898abb6
[]
no_license
ryangreen1234/cs-dm
86843939250350455a45e5b508e9d6906e6d4ac9
2fed37a845894188ce855b277b7fecda9b0e097d
refs/heads/master
1,585,441,631,595
1,537,270,760,000
1,537,270,760,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,284
lean
-- UNDER CONSTRUCTION variables P Q R X Y Z: Prop variable pfP : P variable pfQ : Q variable pfR : R /- If P and Q are propositions, then P ∨ Q is also a proposition. It is read as "P or Q" and is called a disjunction. P and Q are called the disjuncts. In constructive logic, P ∨ Q, is judged to be true if either a proof of P or a proof of Q can be given. Having a proof of both of course allows one to give either proof to construct a proof of P ∨ Q. Here are the introduction rules. { P } Q : Prop, pfP: P ---------------------- (or.intro_left) P ∨ Q P { Q } : Prop, pfQ: Q ----------------------- (or.intro_right) P ∨ Q -/ /- ************************** *** INTRODUCTION RULES *** ************************** -/ /- The or.intro_left rule takes a proof of P along with a proposition Q and builds a proof of P ∨ Q. (No proof of Q is needed so any Q will do, even false.) The or.intro_right rule takes a proof of Q along with a proposition P and constructs a proof of P ∨ Q. No proof of P is required, so any P will do, even false. We have to provide the proposition for the "side" of the disjunction for which we're not providing a proof so that Lean knows the type of both propositions and thus the full type of the disjunction to be proved. -/ /- We can use example to state a theorem without giving it a name. -/ example : P ∨ false := or.intro_left false pfP example : false ∨ P := or.intro_right false pfP /- EXERCISE: Prove 0=0 ∨ 0 = 1. -/ /- Here's a proof that true is a right identity for or. -/ theorem id_right_or : forall P : Prop, P ∨ true := λ P, or.intro_right P true.intro /- EXERCISE: Prove that it's also a left identity. -/ /- ************************** **** Elimination RULE **** ************************** -/ /- The elimination rule for ∨ at first seems slightly involved. Here's what it says: If P ∨ Q, and if both P → R and Q → R, then R. pfPQ: P ∨ Q, pfPR: P → R, pfQR: Q → R -------------------------------------- ∨-elim R For example, suppose that (1) when it is raining the grass is wet (P → R); when the sprinkler is on, the grass is wet (Q → R); and it is raining or the sprinkler is on (P ∨ Q). Then the grass must be wet (R). The reasoning is by cases. P ∨ Q means at least one of them is true. If it's P, then we can show that R is true using P → R. If it's Q, then we can show from R using Q → R. So in either case, we can show R, so R must be true. -/ variable porq : P ∨ Q variable p2r : P → R variable q2r : Q → R #check or.elim porq p2r q2r /- Here's the same example using more suggestive proposition names. -/ variables Raining Sprinkling Wet : Prop variable r2w: Raining → Wet variable s2w: Sprinkling → Wet variable rors: Raining ∨ Sprinkling theorem wet : Wet := or.elim rors r2w s2w theorem wet' : forall R S W: Prop, (R ∨ S) → (R → W) → (S → W) → W := begin assume R S W pfRorS r2w s2w, show W, from or.elim pfRorS r2w s2w end /- This rule gives us an indirect way to prove a proposition W by showing that one or another condition must be true (P ∨ Q), and in either case W must be true because both (P → R) and (Q → R). -/
bf50ec884d8d1fa2ba338e272c81ef3872ca14ed
bd12a817ba941113eb7fdb7ddf0979d9ed9386a0
/src/tactic/interactive.lean
71271597ae5d07d2993c99ebe8d151b8d1f46103
[ "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
22,317
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import tactic.core data.list.defs open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- Move goal `n` to the front. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h meta def apply_iff_congr_core : tactic unit := applyc ``iff_of_eq meta def congr_core' : tactic unit := do tgt ← target, apply_eq_congr_core tgt <|> apply_heq_congr_core <|> apply_iff_congr_core <|> fail "congr tactic failed" /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/ meta def congr' : parse (with_desc "n" small_nat)? → tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core' >> all_goals (reflexivity <|> `[apply proof_irrel_heq] <|> `[apply proof_irrel] <|> try (congr' (nat.pred <$> o))))) /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end /-- Make every propositions in the context decidable -/ meta def classical := tactic.classical private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end /-- Similar to `refine` but generates equality proof obligations for every discrepancy between the goal and the type of the rule. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], try (congr' n), gs' ← get_goals, set_goals $ gs' ++ gs meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ``` refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p /-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast to `guard_expr`, this tests strict (syntactic) equality. We use this tactic for writing tests. -/ meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (t = e) /-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`. We use this tactic for writing tests. -/ meta def guard_target_strict (p : parse texpr) : tactic unit := do t ← target, guard_expr_strict t p /-- `guard_hyp_strict h := t` fails if the hypothesis `h` does not have type syntactically equal to `t`. We use this tactic for writing tests. -/ meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ``` refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ``` refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc /--`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. `n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. example, with or without user attribute: ``` @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules mono_rules -- any of the following lines would also work: -- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 -- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] -- by apply_rules [mono_rules] ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit := tactic.apply_rules hs n meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)], t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`. `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`. `h_generalize! Hx : e == x` reverts `Hx`. when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) /-- `choose a b h using hyp` takes an hypothesis `hyp` of the form `∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating `∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions. Example: ```lean example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := ℕ → ℕ → ℕ, guard_hyp j := ℕ → ℕ → ℕ, guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n, trivial end ``` -/ meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) : tactic unit := do tgt ← match tgt with | none := get_local `this | some e := tactic.i_to_expr_strict e end, tactic.choose tgt (first :: names), try (tactic.clear tgt) meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ meta def triv : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed" /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := tactic.use l >> try triv /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. -/ meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl meta def loc.get_local_pp_names : loc → tactic (list name) | loc.wildcard := list.map expr.local_pp_name <$> local_context | (loc.ns l) := return l.reduce_option meta def loc.get_local_uniq_names (l : loc) : tactic (list name) := list.map expr.local_uniq_name <$> l.get_locals /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do l' ← loc.get_local_pp_names l, l'.mmap' (λ e, try (change_with_at q w e)), when l.include_goal $ change q w (loc.ns [none]) private meta def opt_dir_with : parser (option (bool × name)) := (do tk "with", arrow ← (tk "<-")?, h ← ident, return (arrow.is_some, h)) <|> return none /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. -/ meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr) (rev_name : parse opt_dir_with) := do let vt := match tp with | some t := t | none := pexpr.mk_placeholder end, let pv := ``(%%pv : %%vt), v ← to_expr pv, tp ← infer_type v, definev a tp v, when h_simp.is_none $ change' pv (some (expr.const a [])) loc.wildcard, match rev_name with | some (flip, id) := do nv ← get_local a, pf ← to_expr (cond flip ``(%%pv = %%nv) ``(%%nv = %%pv)) >>= assert id, reflexivity | none := skip end /-- `clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`. -/ meta def clear_except (xs : parse ident *) : tactic unit := do let ns := name_set.of_list xs, local_context >>= mmap' (λ h : expr, when (¬ ns.contains h.local_pp_name) $ try $ tactic.clear h) ∘ list.reverse end interactive end tactic
292727c7c83552eff9285a433d9d6561c91d8f0a
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Elab/PreDefinition/Structural.lean
8d6dd15403515298c316546c676a9f85050b7eb9
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,698
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.Util.ForEachExpr import Lean.Meta.ForEachExpr import Lean.Meta.RecursorInfo import Lean.Meta.Match.Match import Lean.Elab.PreDefinition.Basic namespace Lean namespace Elab open Meta private def getFixedPrefix (declName : Name) (xs : Array Expr) (value : Expr) : Nat := let visitor {ω} : StateRefT Nat (ST ω) Unit := value.forEach' fun e => if e.isAppOf declName then do let args := e.getAppArgs; modify fun numFixed => if args.size < numFixed then args.size else numFixed; -- we continue searching if the e's arguments are not a prefix of `xs` pure !args.isPrefixOf xs else pure true; runST fun _ => do (_, numFixed) ← visitor.run xs.size; pure numFixed structure RecArgInfo := /- `fixedParams ++ ys` are the arguments of the function we are trying to justify termination using structural recursion. -/ (fixedParams : Array Expr) (ys : Array Expr) -- recursion arguments (pos : Nat) -- position in `ys` of the argument we are recursing on (indicesPos : Array Nat) -- position in `ys` of the inductive datatype indices we are recursing on (indName : Name) -- inductive datatype name of the argument we are recursing on (indLevels : List Level) -- inductice datatype universe levels of the argument we are recursing on (indParams : Array Expr) -- inductive datatype parameters of the argument we are recursing on (indIndices : Array Expr) -- inductive datatype indices of the argument we are recursing on, it is equal to `indicesPos.map fun i => ys.get! i` (reflexive : Bool) -- true if we are recursing over a reflexive inductive datatype private def getIndexMinPos (xs : Array Expr) (indices : Array Expr) : Nat := indices.foldl (fun minPos index => match xs.indexOf? index with | some pos => if pos.val < minPos then pos.val else minPos | _ => minPos) xs.size -- Indices can only depend on other indices private def hasBadIndexDep? (ys : Array Expr) (indices : Array Expr) : MetaM (Option (Expr × Expr)) := indices.findSomeM? fun index => do indexType ← inferType index; ys.findSomeM? fun y => if indices.contains y then pure none else condM (dependsOn indexType y.fvarId!) (pure (some (index, y))) (pure none) -- Inductive datatype parameters cannot depend on ys private def hasBadParamDep? (ys : Array Expr) (indParams : Array Expr) : MetaM (Option (Expr × Expr)) := indParams.findSomeM? fun p => do pType ← inferType p; ys.findSomeM? fun y => condM (dependsOn pType y.fvarId!) (pure (some (p, y))) (pure none) private def throwStructuralFailed {α} : MetaM α := throwError "structural recursion cannot be used" private partial def findRecArgAux {α} (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo → MetaM α) : Nat → MetaM α | i => if h : i < xs.size then do let x := xs.get ⟨i, h⟩; localDecl ← getFVarLocalDecl x; if localDecl.isLet then throwStructuralFailed else do xType ← whnfD localDecl.type; matchConstInduct xType.getAppFn (fun _ => findRecArgAux (i+1)) fun indInfo us => do condM (not <$> hasConst (mkBRecOnFor indInfo.name)) (findRecArgAux (i+1)) do condM (do hasBInductionOn ← hasConst (mkBInductionOnFor indInfo.name); pure $ indInfo.isReflexive && !hasBInductionOn) (findRecArgAux (i+1)) do let indArgs := xType.getAppArgs; let indParams := indArgs.extract 0 indInfo.nparams; let indIndices := indArgs.extract indInfo.nparams indArgs.size; if !indIndices.all Expr.isFVar then orelseMergeErrors (throwError $ "argument #" ++ toString (i+1) ++ " was not used because its type is an inductive family and indices are not variables" ++ indentExpr xType) (findRecArgAux (i+1)) else if !indIndices.allDiff then orelseMergeErrors (throwError $ "argument #" ++ toString (i+1) ++ " was not used because its type is an inductive family and indices are not pairwise distinct" ++ indentExpr xType) (findRecArgAux (i+1)) else do let indexMinPos := getIndexMinPos xs indIndices; let numFixed := if indexMinPos < numFixed then indexMinPos else numFixed; let fixedParams := xs.extract 0 numFixed; let ys := xs.extract numFixed xs.size; badDep? ← hasBadIndexDep? ys indIndices; match badDep? with | some (index, y) => orelseMergeErrors (throwError $ "argument #" ++ toString (i+1) ++ " was not used because its type is an inductive family" ++ indentExpr xType ++ Format.line ++ "and index" ++ indentExpr index ++ Format.line ++ "depends on the non index" ++ indentExpr y) (findRecArgAux (i+1)) | none => do badDep? ← hasBadParamDep? ys indParams; match badDep? with | some (indParam, y) => orelseMergeErrors (throwError $ "argument #" ++ toString (i+1) ++ " was not used because its type is an inductive datatype" ++ indentExpr xType ++ Format.line ++ "and parameter" ++ indentExpr indParam ++ Format.line ++ "depends on" ++ indentExpr y) (findRecArgAux (i+1)) | none => do let indicesPos := indIndices.map fun index => match ys.indexOf? index with | some i => i.val | none => unreachable!; orelseMergeErrors (k { fixedParams := fixedParams, ys := ys, pos := i - fixedParams.size, indicesPos := indicesPos, indName := indInfo.name, indLevels := us, indParams := indParams, indIndices := indIndices, reflexive := indInfo.isReflexive }) (findRecArgAux (i+1)) else throwStructuralFailed @[inline] private def findRecArg {α} (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo → MetaM α) : MetaM α := findRecArgAux numFixed xs k numFixed private def containsRecFn (recFnName : Name) (e : Expr) : Bool := (e.find? fun e => e.isConstOf recFnName).isSome private def ensureNoRecFn (recFnName : Name) (e : Expr) : MetaM Expr := do if containsRecFn recFnName e then do Meta.forEachExpr e fun e => when (e.isAppOf recFnName) $ throwError $ "unexpected occurrence of recursive application" ++ indentExpr e; pure e else pure e private def throwToBelowFailed {α} : MetaM α := throwError "toBelow failed" /- See toBelow -/ private partial def toBelowAux (C : Expr) : Expr → Expr → Expr → MetaM Expr | belowDict, arg, F => do belowDict ← whnf belowDict; trace! `Elab.definition.structural ("belowDict: " ++ belowDict ++ ", arg: " ++ arg); match belowDict with | Expr.app (Expr.app (Expr.const `PProd _ _) d1 _) d2 _ => (do F ← mkAppM `PProd.fst #[F]; toBelowAux d1 arg F) <|> (do F ← mkAppM `PProd.snd #[F]; toBelowAux d2 arg F) | Expr.app (Expr.app (Expr.const `And _ _) d1 _) d2 _ => (do F ← mkAppM `And.left #[F]; toBelowAux d1 arg F) <|> (do F ← mkAppM `And.right #[F]; toBelowAux d2 arg F) | _ => forallTelescopeReducing belowDict fun xs belowDict => do let argArgs := arg.getAppArgs; unless (argArgs.size >= xs.size) throwToBelowFailed; let n := argArgs.size; let argTailArgs := argArgs.extract (n - xs.size) n; let belowDict := belowDict.replaceFVars xs argTailArgs; match belowDict with | Expr.app belowDictFun belowDictArg _ => do unless (belowDictFun.getAppFn == C) throwToBelowFailed; unlessM (isDefEq belowDictArg arg) throwToBelowFailed; pure (mkAppN F argTailArgs) | _ => throwToBelowFailed /- See toBelow -/ private def withBelowDict {α} (below : Expr) (numIndParams : Nat) (k : Expr → Expr → MetaM α) : MetaM α := do belowType ← inferType below; trace! `Elab.definition.structural ("belowType: " ++ belowType); belowType.withApp fun f args => do let motivePos := numIndParams + 1; unless (motivePos < args.size) $ throwError $ "unexpected 'below' type" ++ indentExpr belowType; let pre := mkAppN f (args.extract 0 numIndParams); preType ← inferType pre; forallBoundedTelescope preType (some 1) fun x _ => do motiveType ← inferType (x.get! 0); C ← mkFreshUserName `C; withLocalDeclD C motiveType fun C => let belowDict := mkApp pre C; let belowDict := mkAppN belowDict (args.extract (numIndParams + 1) args.size); k C belowDict /- `below` is a free variable with type of the form `I.below indParams motive indices major`, where `I` is the name of an inductive datatype. For example, when trying to show that the following function terminates using structural recursion ```lean def addAdjacent : List Nat → List Nat | [] => [] | [a] => [a] | a::b::as => (a+b) :: addAdjacent as ``` when we are visiting `addAdjacent as` at `replaceRecApps`, `below` has type `@List.below Nat (fun (x : List Nat) => List Nat) (a::b::as)` The motive `fun (x : List Nat) => List Nat` depends on the actual function we are trying to compute. So, we first replace it with a fresh variable `C` at `withBelowDict`. Recall that `brecOn` implements course-of-values recursion, and `below` can be viewed as a dictionary of the "previous values". We search this dictionary using the auxiliary function `toBelowAux`. The dictionary is built using the `PProd` (`And` for inductive predicates). We keep searching it until we find `C recArg`, where `C` is the auxiliary fresh variable created at `withBelowDict`. -/ private partial def toBelow (below : Expr) (numIndParams : Nat) (recArg : Expr) : MetaM Expr := do withBelowDict below numIndParams fun C belowDict => toBelowAux C belowDict recArg below private partial def replaceRecApps (recFnName : Name) (recArgInfo : RecArgInfo) : Expr → Expr → MetaM Expr | below, e@(Expr.lam n d b c) => do d ← replaceRecApps below d; withLocalDecl n c.binderInfo d fun x => do b ← replaceRecApps below (b.instantiate1 x); mkLambdaFVars #[x] b | below, e@(Expr.forallE n d b c) => do d ← replaceRecApps below d; withLocalDecl n c.binderInfo d fun x => do b ← replaceRecApps below (b.instantiate1 x); mkForallFVars #[x] b | below, Expr.letE n type val body _ => do type ← replaceRecApps below type; val ← replaceRecApps below val; withLetDecl n type val fun x => do body ← replaceRecApps below (body.instantiate1 x); mkLetFVars #[x] body | below, Expr.mdata d e _ => do e ← replaceRecApps below e; pure $ mkMData d e | below, Expr.proj n i e _ => do e ← replaceRecApps below e; pure $ mkProj n i e | below, e@(Expr.app _ _ _) => do let processApp (e : Expr) : MetaM Expr := e.withApp fun f args => do { if f.isConstOf recFnName then do let numFixed := recArgInfo.fixedParams.size; let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos; when (recArgPos >= args.size) $ throwError ("insufficient number of parameters at recursive application " ++ indentExpr e); let recArg := args.get! recArgPos; f ← catch (toBelow below recArgInfo.indParams.size recArg) (fun _ => throwError $ "failed to eliminate recursive application" ++ indentExpr e); -- Recall that the fixed parameters are not in the scope of the `brecOn`. So, we skip them. let argsNonFixed := args.extract numFixed args.size; -- The function `f` does not explicitly take `recArg` and its indices as arguments. So, we skip them too. let fArgs := argsNonFixed.iterate #[] fun i a fArgs => if recArgInfo.pos == i.val || recArgInfo.indicesPos.contains i.val then fArgs else fArgs.push a; pure $ mkAppN f fArgs else do f ← replaceRecApps below f; args ← args.mapM (replaceRecApps below); pure $ mkAppN f args }; matcherApp? ← matchMatcherApp? e; match matcherApp? with | some matcherApp => if !containsRecFn recFnName e then processApp e else do matcherApp ← mapError (matcherApp.addArg below) (fun msg => "failed to add `below` argument to 'matcher' application" ++ indentD msg); altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun ⟨alt, numParams⟩ => lambdaTelescope alt fun xs altBody => do { trace! `Elab.definition.structural ("altNumParams: " ++ toString numParams ++ ", xs: " ++ xs); unless (xs.size >= numParams) $ throwError $ "unexpected matcher application alternative " ++ indentExpr alt ++ Format.line ++ "at application" ++ indentExpr e; let belowForAlt := xs.get! (numParams - 1); altBodyNew ← replaceRecApps belowForAlt altBody; mkLambdaFVars xs altBodyNew }; pure { matcherApp with alts := altsNew }.toExpr | none => processApp e | _, e => ensureNoRecFn recFnName e private def mkBRecOn (recFnName : Name) (recArgInfo : RecArgInfo) (value : Expr) : MetaM Expr := do type ← inferType value; let type := type.headBeta; let major := recArgInfo.ys.get! recArgInfo.pos; let otherArgs := recArgInfo.ys.filter fun y => y != major && !recArgInfo.indIndices.contains y; motive ← mkForallFVars otherArgs type; brecOnUniv ← getLevel motive; trace! `Elab.definition.structural ("brecOn univ: " ++ brecOnUniv); let useBInductionOn := recArgInfo.reflexive && brecOnUniv == levelZero; brecOnUniv ← if recArgInfo.reflexive && brecOnUniv != levelZero then decLevel brecOnUniv else pure brecOnUniv; motive ← mkLambdaFVars (recArgInfo.indIndices.push major) motive; trace! `Elab.definition.structural ("brecOn motive: " ++ motive); let brecOn := if useBInductionOn then Lean.mkConst (mkBInductionOnFor recArgInfo.indName) recArgInfo.indLevels else Lean.mkConst (mkBRecOnFor recArgInfo.indName) (brecOnUniv :: recArgInfo.indLevels); let brecOn := mkAppN brecOn recArgInfo.indParams; let brecOn := mkApp brecOn motive; let brecOn := mkAppN brecOn recArgInfo.indIndices; let brecOn := mkApp brecOn major; check brecOn; brecOnType ← inferType brecOn; trace! `Elab.definition.structural ("brecOn " ++ brecOn); trace! `Elab.definition.structural ("brecOnType " ++ brecOnType); forallBoundedTelescope brecOnType (some 1) fun F _ => do let F := F.get! 0; FType ← inferType F; let numIndices := recArgInfo.indIndices.size; forallBoundedTelescope FType (some $ numIndices + 1 /- major -/ + 1 /- below -/ + otherArgs.size) fun Fargs _ => do let indicesNew := Fargs.extract 0 numIndices; let majorNew := Fargs.get! numIndices; let below := Fargs.get! (numIndices+1); let otherArgsNew := Fargs.extract (numIndices+2) Fargs.size; let valueNew := value.replaceFVars recArgInfo.indIndices indicesNew; let valueNew := valueNew.replaceFVar major majorNew; let valueNew := valueNew.replaceFVars otherArgs otherArgsNew; valueNew ← replaceRecApps recFnName recArgInfo below valueNew; Farg ← mkLambdaFVars Fargs valueNew; let brecOn := mkApp brecOn Farg; pure $ mkAppN brecOn otherArgs private def elimRecursion (preDef : PreDefinition) : MetaM PreDefinition := withoutModifyingEnv do lambdaTelescope preDef.value fun xs value => do addAsAxiom preDef; trace! `Elab.definition.structural (preDef.declName ++ " " ++ xs ++ " :=\n" ++ value); let numFixed := getFixedPrefix preDef.declName xs value; findRecArg numFixed xs fun recArgInfo => do -- when (recArgInfo.indName == `Nat) throwStructuralFailed; -- HACK to skip Nat argument valueNew ← mkBRecOn preDef.declName recArgInfo value; valueNew ← mkLambdaFVars xs valueNew; trace! `Elab.definition.structural ("result: " ++ valueNew); -- Recursive applications may still occur in expressions that were not visited by replaceRecApps (e.g., in types) valueNew ← ensureNoRecFn preDef.declName valueNew; pure { preDef with value := valueNew } def structuralRecursion (preDefs : Array PreDefinition) : TermElabM Unit := if preDefs.size != 1 then throwError "structural recursion does not handle mutually recursive functions" else do preDefNonRec ← liftMetaM $ elimRecursion (preDefs.get! 0); addNonRec preDefNonRec; addAndCompileUnsafeRec preDefs @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.definition.structural; pure () end Elab end Lean
2f3124f5a5c4fd153687993595e2717660724a3c
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport.lean
8bda7104b275f9a393e95100cdf49aa0077ab7bf
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
1,986
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Daniel Selsam -/ import Mathport.Binary import Mathport.Syntax namespace Mathport open Lean Lean.Elab.Command def mathport1 (config : Config) (path : Path) : IO Unit := do let pcfg := config.pathConfig createDirectoriesIfNotExists (path.toLean4olean pcfg).toString createDirectoriesIfNotExists (path.toLean4src pcfg).toString IO.eprintln s!"porting {path.mod4}" println! s!"\n[mathport] START {path.mod3}\n" let imports3 ← parseTLeanImports (path.toLean3 pcfg ".tlean") path.mod3 let mut imports : Array Import ← imports3.mapM fun mod3 => do let ipath : Path ← resolveMod3 pcfg mod3 pure { module := ipath.package ++ ipath.mod4 : Import } if imports.isEmpty then imports := config.baseModules.map ({ module := · : Import }) imports := imports ++ config.extraModules.map ({ module := · : Import }) let opts := ({} : Options) |>.setNat `maxRecDepth 2000 |>.setNat `maxHeartbeats 50000 |>.setBool `pp.rawOnError true try withImportModulesConst imports.toList (opts := opts) (trustLevel := 0) $ λ env => do let env := env.setMainModule path.mod4 let cmdCtx : Elab.Command.Context := { fileName := path.toLean3 pcfg ".lean" |>.toString fileMap := dummyFileMap tacticCache? := none } let cmdState : Elab.Command.State := Lean.Elab.Command.mkState (env := env) (opts := opts) CommandElabM.toIO (ctx := cmdCtx) (s := cmdState) do -- let _ ← IO.FS.withIsolatedStreams' $ binport1 config path binport1 config path synport1 config path imports3 writeModule (← getEnv) $ path.toLean4olean pcfg println! "\n[mathport] END {path.mod3}\n" catch err => throw $ IO.userError s!"failed to port {path.package}:{path.mod4} with imports {imports.toList}:\n{err}" end Mathport
c8a10e99e7c20c72ec88d49dac1bc3e3db388dad
618003631150032a5676f229d13a079ac875ff77
/test/apply_fun.lean
5f37122d01d13e622f024091135ed863ec771304
[ "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
827
lean
import tactic.apply_fun open function example (X Y Z : Type) (f : X → Y) (g : Y → Z) (H : injective $ g ∘ f) : injective f := begin intros x x' h, apply_fun g at h, exact H h end example (f : ℕ → ℕ) (a b : ℕ) (monof : monotone f) (h : a ≤ b) : f a ≤ f b := begin apply_fun f at h, assumption, assumption end example (a b : ℤ) (h : a = b) : a + 1 = b + 1 := begin apply_fun (λ n, n+1) at h, -- check that `h` was β-reduced guard_hyp' h := a + 1 = b + 1, exact h end example (f : ℕ → ℕ) (a b : ℕ) (monof : monotone f) (h : a ≤ b) : f a ≤ f b := begin apply_fun f at h using monof, assumption end -- monotonicity will be proved by `mono` in the next example example (a b : ℕ) (h : a ≤ b) : a + 1 ≤ b + 1 := begin apply_fun (λ n, n+1) at h, exact h end
c62bfdc6409bbccc434609750b85453b8b4d5692
94e33a31faa76775069b071adea97e86e218a8ee
/src/geometry/manifold/algebra/left_invariant_derivation.lean
69567e95ed6eb881cba88d7adfffbde746b69384
[ "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,872
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.derivation_bundle /-! # Left invariant derivations In this file we define the concept of left invariant derivation for a Lie group. The concept is analogous to the more classical concept of left invariant vector fields, and it holds that the derivation associated to a vector field is left invariant iff the field is. Moreover we prove that `left_invariant_derivation I G` has the structure of a Lie algebra, hence implementing one of the possible definitions of the Lie algebra attached to a Lie group. -/ noncomputable theory open_locale lie_group manifold derivation variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (G : Type*) [topological_space G] [charted_space H G] [monoid G] [has_smooth_mul I G] (g h : G) -- Generate trivial has_sizeof instance. It prevents weird type class inference timeout problems local attribute [nolint instance_priority, instance, priority 10000] private def disable_has_sizeof {α} : has_sizeof α := ⟨λ _, 0⟩ /-- Left-invariant global derivations. A global derivation is left-invariant if it is equal to its pullback along left multiplication by an arbitrary element of `G`. -/ structure left_invariant_derivation extends derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯ := (left_invariant'' : ∀ g, 𝒅ₕ(smooth_left_mul_one I g) (derivation.eval_at 1 to_derivation) = derivation.eval_at g to_derivation) variables {I G} namespace left_invariant_derivation instance : has_coe (left_invariant_derivation I G) (derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) := ⟨λ X, X.to_derivation⟩ instance : has_coe_to_fun (left_invariant_derivation I G) (λ _, C^∞⟮I, G; 𝕜⟯ → C^∞⟮I, G; 𝕜⟯) := ⟨λ X, X.to_derivation.to_fun⟩ variables {M : Type*} [topological_space M] [charted_space H M] {x : M} {r : 𝕜} {X Y : left_invariant_derivation I G} {f f' : C^∞⟮I, G; 𝕜⟯} lemma to_fun_eq_coe : X.to_fun = ⇑X := rfl lemma coe_to_linear_map : ⇑(X : C^∞⟮I, G; 𝕜⟯ →ₗ[𝕜] C^∞⟮I, G; 𝕜⟯) = X := rfl @[simp] lemma to_derivation_eq_coe : X.to_derivation = X := rfl lemma coe_injective : @function.injective (left_invariant_derivation I G) (_ → C^⊤⟮I, G; 𝕜⟯) coe_fn := λ X Y h, by { cases X, cases Y, congr', exact derivation.coe_injective h } @[ext] theorem ext (h : ∀ f, X f = Y f) : X = Y := coe_injective $ funext h variables (X Y f) lemma coe_derivation : ⇑(X : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = (X : C^∞⟮I, G; 𝕜⟯ → C^∞⟮I, G; 𝕜⟯) := rfl lemma coe_derivation_injective : function.injective (coe : left_invariant_derivation I G → derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) := λ X Y h, by { cases X, cases Y, congr, exact h } /-- Premature version of the lemma. Prefer using `left_invariant` instead. -/ lemma left_invariant' : 𝒅ₕ (smooth_left_mul_one I g) (derivation.eval_at (1 : G) ↑X) = derivation.eval_at g ↑X := left_invariant'' X g @[simp] lemma map_add : X (f + f') = X f + X f' := derivation.map_add X f f' @[simp] lemma map_zero : X 0 = 0 := derivation.map_zero X @[simp] lemma map_neg : X (-f) = -X f := derivation.map_neg X f @[simp] lemma map_sub : X (f - f') = X f - X f' := derivation.map_sub X f f' @[simp] lemma map_smul : X (r • f) = r • X f := derivation.map_smul X r f @[simp] lemma leibniz : X (f * f') = f • X f' + f' • X f := X.leibniz' _ _ instance : has_zero (left_invariant_derivation I G) := ⟨⟨0, λ g, by simp only [linear_map.map_zero, derivation.coe_zero]⟩⟩ instance : inhabited (left_invariant_derivation I G) := ⟨0⟩ instance : has_add (left_invariant_derivation I G) := { add := λ X Y, ⟨X + Y, λ g, by simp only [linear_map.map_add, derivation.coe_add, left_invariant', pi.add_apply]⟩ } instance : has_neg (left_invariant_derivation I G) := { neg := λ X, ⟨-X, λ g, by simp [left_invariant']⟩ } instance : has_sub (left_invariant_derivation I G) := { sub := λ X Y, ⟨X - Y, λ g, by simp [left_invariant']⟩ } @[simp] lemma coe_add : ⇑(X + Y) = X + Y := rfl @[simp] lemma coe_zero : ⇑(0 : left_invariant_derivation I G) = 0 := rfl @[simp] lemma coe_neg : ⇑(-X) = -X := rfl @[simp] lemma coe_sub : ⇑(X - Y) = X - Y := rfl @[simp, norm_cast] lemma lift_add : (↑(X + Y) : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = X + Y := rfl @[simp, norm_cast] lemma lift_zero : (↑(0 : left_invariant_derivation I G) : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = 0 := rfl instance has_nat_scalar : has_smul ℕ (left_invariant_derivation I G) := { smul := λ r X, ⟨r • X, λ g, by simp_rw [linear_map.map_smul_of_tower, left_invariant']⟩ } instance has_int_scalar : has_smul ℤ (left_invariant_derivation I G) := { smul := λ r X, ⟨r • X, λ g, by simp_rw [linear_map.map_smul_of_tower, left_invariant']⟩ } instance : add_comm_group (left_invariant_derivation I G) := coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance : has_smul 𝕜 (left_invariant_derivation I G) := { smul := λ r X, ⟨r • X, λ g, by simp_rw [linear_map.map_smul, left_invariant']⟩ } variables (r X) @[simp] lemma coe_smul : ⇑(r • X) = r • X := rfl @[simp] lemma lift_smul (k : 𝕜) : (↑(k • X) : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = k • X := rfl variables (I G) /-- The coercion to function is a monoid homomorphism. -/ @[simps] def coe_fn_add_monoid_hom : (left_invariant_derivation I G) →+ (C^∞⟮I, G; 𝕜⟯ → C^∞⟮I, G; 𝕜⟯) := ⟨λ X, X.to_derivation.to_fun, coe_zero, coe_add⟩ variables {I G} instance : module 𝕜 (left_invariant_derivation I G) := coe_injective.module _ (coe_fn_add_monoid_hom I G) coe_smul /-- Evaluation at a point for left invariant derivation. Same thing as for generic global derivations (`derivation.eval_at`). -/ def eval_at : (left_invariant_derivation I G) →ₗ[𝕜] (point_derivation I g) := { to_fun := λ X, derivation.eval_at g ↑X, map_add' := λ X Y, rfl, map_smul' := λ k X, rfl } lemma eval_at_apply : eval_at g X f = (X f) g := rfl @[simp] lemma eval_at_coe : derivation.eval_at g ↑X = eval_at g X := rfl lemma left_invariant : 𝒅ₕ(smooth_left_mul_one I g) (eval_at (1 : G) X) = eval_at g X := (X.left_invariant'' g) lemma eval_at_mul : eval_at (g * h) X = 𝒅ₕ(L_apply I g h) (eval_at h X) := by { ext f, rw [←left_invariant, apply_hfdifferential, apply_hfdifferential, L_mul, fdifferential_comp, apply_fdifferential, linear_map.comp_apply, apply_fdifferential, ←apply_hfdifferential, left_invariant] } lemma comp_L : (X f).comp (𝑳 I g) = X (f.comp (𝑳 I g)) := by ext h; rw [cont_mdiff_map.comp_apply, L_apply, ←eval_at_apply, eval_at_mul, apply_hfdifferential, apply_fdifferential, eval_at_apply] instance : has_bracket (left_invariant_derivation I G) (left_invariant_derivation I G) := { bracket := λ X Y, ⟨⁅(X : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯), Y⁆, λ g, begin ext f, have hX := derivation.congr_fun (left_invariant' g X) (Y f), have hY := derivation.congr_fun (left_invariant' g Y) (X f), rw [apply_hfdifferential, apply_fdifferential, derivation.eval_at_apply] at hX hY ⊢, rw comp_L at hX hY, rw [derivation.commutator_apply, smooth_map.coe_sub, pi.sub_apply, coe_derivation], rw coe_derivation at hX hY ⊢, rw [hX, hY], refl end⟩ } @[simp] lemma commutator_coe_derivation : ⇑⁅X, Y⁆ = (⁅(X : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯), Y⁆ : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) := rfl lemma commutator_apply : ⁅X, Y⁆ f = X (Y f) - Y (X f) := rfl instance : lie_ring (left_invariant_derivation I G) := { add_lie := λ X Y Z, by { ext1, simp only [commutator_apply, coe_add, pi.add_apply, linear_map.map_add, left_invariant_derivation.map_add], ring }, lie_add := λ X Y Z, by { ext1, simp only [commutator_apply, coe_add, pi.add_apply, linear_map.map_add, left_invariant_derivation.map_add], ring }, lie_self := λ X, by { ext1, simp only [commutator_apply, sub_self], refl }, leibniz_lie := λ X Y Z, by { ext1, simp only [commutator_apply, coe_add, coe_sub, map_sub, pi.add_apply], ring, } } instance : lie_algebra 𝕜 (left_invariant_derivation I G) := { lie_smul := λ r Y Z, by { ext1, simp only [commutator_apply, map_smul, smul_sub, coe_smul, pi.smul_apply] } } end left_invariant_derivation
7184dfd79a4ff0647316fb5bc2e719baba44f734
ad3e8f15221a986da27c99f371922c0b3f5792b6
/src/week-03/solutions/e01-languages.lean
dc478a2a3b0e99969bee180e0c21c8d9ca32a133
[]
no_license
VArtem/lean-itmo
a0e1424c8cc4c2de2ac85ab6fd4a12d80e9b85f1
dc44cd06f9f5b984d051831b3aaa7364e64c2dc4
refs/heads/main
1,683,761,214,467
1,622,821,295,000
1,622,821,295,000
357,236,048
12
0
null
null
null
null
UTF-8
Lean
false
false
15,417
lean
import data.set.basic import data.list.basic import tactic open set list -- Будем рассматривать языкы над алфавитом α -- Язык это просто set (list α) namespace languages variables {α : Type} {L M : set (list α)} -- Несколько удобных сокращений: ε = пустой список, 0 = ∅, 1 = {ε}, A + B = A ∪ B def ε {α} : list α := [] instance : has_zero (set (list α)) := ⟨(∅ : set _)⟩ instance : has_one (set (list α)) := ⟨({[]} : set _)⟩ instance : has_add (set (list α)) := ⟨set.union⟩ -- Конкатенация языков состоит из таких слов `w`, что существуют слова `left ∈ L` и `right ∈ M`, что `w = left ++ right`) def append (L M: set (list α)) := { w : list α | ∃ (left ∈ L) (right ∈ M), w = left ++ right} -- Будем обозначать умножение как `L * M` instance : has_mul (set (list α)) := ⟨append⟩ -- И вспомогательные леммы def zero_def : (0 : set (list α)) = ∅ := rfl def one_def : (1 : set (list α)) = {[]} := rfl @[simp] def mem_zero {w : list α} : w ∉ (0 : set (list α)) := by simp [zero_def] @[simp] def mem_one {w : list α} : w ∈ (1 : set (list α)) ↔ w = [] := by refl @[simp] def nil_mem_one : [] ∈ (1 : set (list α)) := by simp -- Умелое использование `rcases` и `rintro` сильно вам поможет! @[simp] lemma zero_mul (L : set (list α)) : 0 * L = 0 := begin ext w, split, { rintro ⟨left, hleft, right, hright, rfl⟩, simpa only using hleft, }, { intro h, exact absurd h mem_zero, } end @[simp] lemma mul_zero (L : set (list α)) : L * 0 = 0 := begin ext w, split, { rintro ⟨left, hleft, right, hright, rfl⟩, simpa only using hright, }, { intro h, exact absurd h mem_zero, } end @[simp] lemma append_one (A : set (list α)) : A * 1 = A := begin apply subset.antisymm, { rintro _ ⟨left, right, hleft, hright, rfl⟩, rw mem_one at hright, rwa [hright, list.append_nil], }, { rintro x xa, use [x, xa], use [[], nil_mem_one], exact (append_nil x).symm, }, end @[simp] lemma one_append (A : set (list α)) : 1 * A = A := begin apply subset.antisymm, { rintro _ ⟨ left, hleft, right, hright, rfl ⟩, rw mem_one at hleft, rwa [hleft, list.nil_append], }, { rintro x xa, use [[], nil_mem_one, x, xa], exact (nil_append x).symm, }, end lemma append_assoc (A B C : set (list α)): (A * B) * C = A * (B * C) := begin apply subset.antisymm, { rintro _ ⟨_, ⟨left, hleft, mid, hmid, rfl ⟩, right, hright, rfl ⟩, use [left, hleft], use [mid ++ right], use [mid, hmid, right, hright], exact append_assoc left mid right, }, { rintro _ ⟨left, hleft, _, ⟨mid, hmid, right, hright, rfl⟩, rfl ⟩, refine ⟨left ++ mid, ⟨left, hleft, mid, hmid, rfl⟩, right, hright, _⟩, exact (append_assoc left mid right).symm, }, end @[simp] lemma left_distrib (A B C : set (list α)) : A * (B + C) = A * B + A * C := begin ext w, split, { rintro ⟨left, hleft, right, (hB | hC), rfl⟩, { left, exact ⟨left, hleft, right, hB, rfl⟩ }, { right, exact ⟨left, hleft, right, hC, rfl⟩ }, }, { rintro (⟨left, hleft, right, hB, rfl⟩ | ⟨left, hleft, right, hC, rfl⟩), { exact ⟨left, hleft, right, (or.inl hB), rfl⟩, }, { exact ⟨left, hleft, right, (or.inr hC), rfl⟩, }, } end @[simp] lemma right_distrib (A B C : set (list α)) : (A + B) * C = A * C + B * C := begin ext w, split, { rintro ⟨left, (hA | hB), right, hright, rfl⟩, { left, exact ⟨left, hA, right, hright, rfl⟩ }, { right, exact ⟨left, hB, right, hright, rfl⟩ }, }, { rintro (⟨left, hA, right, hright, rfl⟩ | ⟨left, hB, right, hright, rfl⟩), { exact ⟨left, (or.inl hA), right, hright, rfl⟩, }, { exact ⟨left, (or.inr hB), right, hright, rfl⟩, }, } end -- Докажем, что множество языков с операциями + = ∪ и * = append образуют полукольцо: -- A + B - коммутативный моноид: 0, ассоциативность, коммутативность -- A * B - полугруппа: 1, ассоциативность -- Дистрибутивность и умножение на 0 -- Свойства (+) можно достать из стандартной библиотеки про `set.union`, а свойства (*) пришлось доказать instance : semiring (set (list α)) := { add := (+), add_assoc := set.union_assoc, zero := 0, zero_add := set.empty_union, add_zero := set.union_empty, add_comm := set.union_comm, mul := (*), mul_assoc := append_assoc, zero_mul := zero_mul, mul_zero := mul_zero, one := 1, one_mul := one_append, mul_one := append_one, left_distrib := left_distrib, right_distrib := right_distrib, } -- Теперь можно использовать L^n = L * L * ... * L (n раз) -- Полезные леммы: `pow_zero`, `pow_succ`, `pow_add`, ... lemma append_subset_of_subset {A B C D : set (list α)} : A ⊆ C → B ⊆ D → A * B ⊆ C * D := begin rintro hAC hBD x ⟨left, hleft, right, hright, rfl⟩, use [left, hAC hleft, right, hBD hright], end lemma pow_subset_of_subset {A B : set (list α)} {n : ℕ} : A ⊆ B → A^n ⊆ B^n := begin intro hAB, induction n with n ih, { simp only [pow_zero], }, { rw [pow_succ, pow_succ], refine append_subset_of_subset hAB ih, }, end lemma contain_eps_subset_power {A : set (list α)} {n : ℕ} (h : 1 ⊆ A) : A ⊆ A^(n.succ) := begin induction n with n ih, { rw pow_one, }, { rw pow_succ, nth_rewrite 0 ←one_append A, refine append_subset_of_subset h ih, } end -- Замыкание Клини языка L равно объединению L^n по всем натуральным n def star (L : set (list α)) := {w : list α | ∃ (n : ℕ), w ∈ L^n} @[simp] lemma mem_star {w : list α} : w ∈ star L ↔ ∃ (n : ℕ), w ∈ L^n := by refl lemma star_eq_Union : star L = ⋃ (n : ℕ), L^n := begin ext w, simp only [mem_Union, mem_star], end @[simp] lemma nil_mem_star : [] ∈ star L := begin use 0, simp only [nil_mem_one, pow_zero], end @[simp] lemma one_subset_star : 1 ⊆ star L := begin simp [one_def], end @[simp] lemma pow_subset_star (n : ℕ) : L^n ⊆ star L := begin rw star_eq_Union, refine subset_Union _ _, end @[simp] lemma subset_star : L ⊆ star L := begin -- сделает `rw` только в левой части -- conv_lhs {rw ← pow_one L}, nth_rewrite 0 [←pow_one L], exact pow_subset_star 1, end lemma star_subset_star : L ⊆ M → star L ⊆ star M := begin rintro hAB w ⟨n, ha⟩, use n, exact pow_subset_of_subset hAB ha, end lemma append_subset_star {A B L : set (list α)} : A ⊆ star L → B ⊆ star L → (A * B) ⊆ star L := begin rintro al bl _ ⟨left, hleft, right, hright, rfl⟩, rcases al hleft with ⟨an, ah⟩, rcases bl hright with ⟨bn, bh⟩, use an + bn, rw pow_add, use [left, ah, right, bh], end lemma star_append_star_eq_star : star L * star L = star L := begin apply subset.antisymm, { apply append_subset_star (set.subset.refl _) (set.subset.refl _), }, { conv_lhs {rw ← mul_one (star L)}, apply append_subset_of_subset, { refl }, { exact one_subset_star }, } end lemma pow_star_eq_star (n : ℕ) : (star L)^n.succ = star L := begin induction n with n ih, { rw [pow_one], }, { apply subset.antisymm, { rw [pow_succ, ih, star_append_star_eq_star], }, { apply contain_eps_subset_power, exact one_subset_star, }, }, end -- Это было в ДЗ по дискретке! theorem star_star_eq_star : star (star L) = star L := begin apply subset.antisymm, { rintro x ⟨n, hx⟩, cases n, { rw [pow_zero] at hx, apply one_subset_star hx }, { rwa pow_star_eq_star at hx } }, { exact subset_star, }, end -- L^n равен множеству слов, которые можно получить, как конкатенацию `n` слов из `L`. -- Как записать, что `w` представляется как конкатенация `n` слов из `L`? -- `∃ (l : list (list α)) (h : ∀ x ∈ l, x ∈ L), w = list.join l ∧ l.length = n` -- Буквально: существует список слов `l`, что все слова в `l` принадлежат `L`, `w` равен `list.join l`, и длина `l` равна `n` -- Начались сложные задания! Изучите подробнее API `list`, `list.has_mem`, `list.join` и прочие полезные вещи, или увереннее используйте `simp` :) #check list.mem #check mem_cons_self #check list.join #check join_append lemma pow_eq_list_join {n : ℕ} : L^n = {w | ∃ (l : list (list α)) (h : ∀ x ∈ l, x ∈ L), w = list.join l ∧ l.length = n} := begin apply subset.antisymm, { induction n with n ih, { simp [one_def], use [[]], simp, }, { rw pow_succ, rintro _ ⟨left, hleft, right, hright, rfl⟩, obtain ⟨tail, hmem, rfl, rfl⟩ := ih hright, clear ih, simp, refine ⟨left :: tail, _, _, _⟩, -- Стало 3 цели: 1. все элементы списка лежат в L -- 2. join ведет себя по определению - `refl` -- 3. длина списка на 1 больше - `refl` { rintro x (rfl | xtail), { exact hleft, }, { exact hmem _ xtail, }, }, { refl }, { refl }, } }, { induction n with n ih, { simp [one_def], rintro w l h rfl hlen, rw [length_eq_zero] at hlen, subst hlen, refl, }, { rintro w ⟨l, hmem, rfl, hlen⟩, rw pow_succ, -- Докажем, что l не пустой, потому что l.length = n.succ cases l with head tail, { exfalso, exact (ne_nil_of_length_eq_succ hlen) rfl, }, rw [join], -- Осталось показать, что `head ∈ L` и `tail.join ∈ L^n` refine ⟨head, _, tail.join, _, rfl⟩, { apply hmem, apply mem_cons_self, }, { apply ih, simp, refine ⟨tail, _, _, _⟩, { rintro x xtail, apply hmem x, exact mem_cons_of_mem _ xtail, }, { refl, }, { simpa [nat.add_one] using hlen, }, } } } end lemma mem_pow_iff_list_join {w : list α} {n : ℕ} : w ∈ L^n ↔ ∃ l (h : ∀ x ∈ l, x ∈ L), w = list.join l ∧ l.length = n := begin rw pow_eq_list_join, refl, end -- Замыкание Клини - все слова, которые можно представить как конкатенацию слов из L (без ограничения на количество) lemma star_eq_list_join : star L = {w | ∃ l (h : ∀ x, x ∈ l → x ∈ L), w = list.join l} := begin ext w, split, { rintro ⟨n, hw⟩, rw pow_eq_list_join at hw, rcases hw with ⟨l, h, rfl, rfl⟩, use [l, h], }, { rintro ⟨l, h, rfl⟩, apply pow_subset_star l.length, rw [pow_eq_list_join], refine ⟨l, h, rfl, rfl⟩, } end lemma mem_star_iff_list_join {w : list α} : w ∈ star L ↔ ∃ l (h : ∀ x ∈ l, x ∈ L), w = list.join l := begin rw star_eq_list_join, refl, end -- Еще одно ДЗ lemma union_star_eq_star_mul_star_star : star (L + M) = star (star L * star M) := begin apply subset.antisymm, { apply star_subset_star, apply union_subset, { conv_lhs {rw ←mul_one L}, apply append_subset_of_subset (subset_star) (one_subset_star), }, { conv_lhs {rw ←one_mul M}, apply append_subset_of_subset (one_subset_star) (subset_star), } }, { rw ← @star_star_eq_star _ (L + M), apply star_subset_star, conv_rhs { rw ← star_append_star_eq_star}, apply append_subset_of_subset, { exact star_subset_star (subset_union_left _ _)}, { exact star_subset_star (subset_union_right _ _)}, } end lemma mul_star_subset_star : L * star L ⊆ star L := begin rintro _ ⟨left, hleft, right, ⟨n, hright⟩, rfl⟩, apply pow_subset_star (1 + n), rw [pow_add, pow_one], exact ⟨left, hleft, right, hright, rfl⟩, end lemma one_add_mul_star_eq_star : 1 + L * star L = star L := begin apply subset.antisymm, { exact union_subset one_subset_star mul_star_subset_star, }, { rintro w ⟨n, hw⟩, cases n, { left, exact hw, }, { right, rw [pow_succ] at hw, exact append_subset_of_subset (set.subset.refl _) (pow_subset_star n) hw, } } end lemma mul_star_mul_subset_star_mul : L * ((star L) * M) ⊆ (star L) * M := begin rw ← append_assoc, exact append_subset_of_subset (mul_star_subset_star) (set.subset.refl _), end -- Решаем уравнения в языках: если [] ∉ A, то L = A * L + B ↔ L = star A * b lemma linear_eq_iff {A B : set (list α)} (hnil : [] ∉ A) : L = A * L + B ↔ L = star A * B := begin split, { intro h, ext w, suffices hn : ∀ (n : ℕ), ∀ (w : list α) (hn : n = w.length), (w ∈ L ↔ w ∈ star A * B), { refine hn w.length _ rfl, }, clear w, intro n, induction n using nat.strong_induction_on with n ih, dsimp only at ih, rintro w rfl, split, { intro wL, rw h at wL, rcases wL with ⟨left, hleft, right, hright, rfl⟩ | wL, { have right_length : right.length < (left ++ right).length := begin rw [length_append], have left_neq_nil : left ≠ [] := λ hln, by {subst hln, exact hnil hleft}, have left_length_pos : left.length > 0 := length_pos_of_ne_nil left_neq_nil, simpa only [lt_add_iff_pos_left] using left_length_pos, end, specialize ih right.length right_length right rfl, rw ih at hright, apply mul_star_mul_subset_star_mul, exact ⟨left, hleft, right, hright, rfl⟩, }, { rw ←one_mul B at wL, apply append_subset_of_subset (one_subset_star) (set.subset.refl _) wL, }, }, { rintro ⟨left, hleft, right, hright, rfl⟩, rw mem_star_iff_list_join at hleft, rcases hleft with ⟨l, hlist, rfl⟩, clear ih, induction l with head tail ih, { simp, rw h, exact or.inr hright, }, { simp, rw h, left, refine ⟨head, _, tail.join ++ right, _, rfl⟩, { apply hlist, exact mem_cons_self head tail}, { apply ih, simp only [mem_cons_iff, forall_eq_or_imp] at hlist, exact hlist.2,}, } } }, { rintro rfl, rw ←append_assoc, -- rw ←one_add_mul_star_eq_star, -- nth_rewrite 0 ←one_add_mul_star_eq_star, conv_lhs {rw [←one_add_mul_star_eq_star, right_distrib, one_append]}, -- https://leanprover-community.github.io/mathlib_docs/tactics.html#abel abel, -- Также сработает ac_refl: https://leanprover-community.github.io/mathlib_docs/tactics.html#ac_refl } end end languages
12b8462872a76d062d69fa1f8e9b4a9233c9e37c
0ddf2dd8409bcb923d11603846800bd9699616ea
/exercises.lean
91f8d1f7f09b5c9fa57251981958eb417101fe19
[]
no_license
tounaishouta/Lean
0cbaaa9340e7f8f884504ea170243e07a54f0566
1d75311f5506ca2bfd8b7ccec0b7d70c3319d555
refs/heads/master
1,610,229,383,935
1,459,950,226,000
1,459,950,226,000
50,836,185
0
0
null
null
null
null
UTF-8
Lean
false
false
23,065
lean
import standard namespace sec_2_4 open nat definition double (x : nat) : nat := x + x definition do_twice (f : nat → nat) (x : nat) : nat := f (f x) definition quadruple : nat → nat := do_twice double -- eval quadruple 8 -- 32 definition Do_Twice : ((nat → nat) → (nat → nat)) → ((nat → nat) → (nat → nat)) | Do_Twice F f := F (F f) -- eval Do_Twice do_twice double 2 -- 32 open prod definition curry {A B C : Type} : (A × B → C) → (A → B → C) | curry f a b := f (a, b) definition uncurry {A B C : Type} : (A → B → C) → (A × B → C) | uncurry f (a, b) := f a b end sec_2_4 namespace sec_3_5 open function example (em : ∀ p : Prop, p ∨ ¬p) : ∀ p : Prop, ¬¬p → p := take p, suppose ¬¬p, or.elim (em p) id (not.elim `¬¬p`) example (dne : ∀ p : Prop, ¬¬p → p) : ∀ p : Prop, p ∨ ¬p := take p, dne (p ∨ ¬p) (not.intro (assume H : ¬(p ∨ ¬p), have ¬p, from not.intro (not.elim H ∘ or.inl), absurd (or.inr `¬p`) H)) end sec_3_5 namespace sec_3_6 open classical open function variables p q r s : Prop example : p ∧ q ↔ q ∧ p := iff.intro (and.rec (suppose p, suppose q, and.intro `q` `p`)) (and.rec (suppose q, suppose p, and.intro `p` `q`)) example : p ∨ q ↔ q ∨ p := iff.intro (or.rec or.inr or.inl) (or.rec or.inr or.inl) example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := iff.intro (and.rec (and.rec (suppose p, suppose q, suppose r, and.intro `p` (and.intro `q` `r`)))) (and.rec (suppose p, and.rec (suppose q, suppose r, and.intro (and.intro `p` `q`) `r`))) example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := iff.intro (or.rec (or.rec or.inl (or.inr ∘ or.inl)) (or.inr ∘ or.inr)) (or.rec (or.inl ∘ or.inl) (or.rec (or.inl ∘ or.inr) or.inr)) example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := iff.intro (and.rec (suppose p, or.rec (suppose q, or.inl (and.intro `p` `q`)) (suppose r, or.inr (and.intro `p` `r`)))) (or.rec (and.rec (suppose p, suppose q, and.intro `p` (or.inl `q`))) (and.rec (suppose p, suppose r, and.intro `p` (or.inr `r`)))) example : (p → q → r) ↔ (p ∧ q → r) := iff.intro and.rec (assume H, suppose p, suppose q, H (and.intro `p` `q`)) example : (p ∨ q → r) ↔ (p → r) ∧ (q → r) := iff.intro (assume H, and.intro (H ∘ or.inl) (H ∘ or.inr)) (and.rec or.rec) example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := iff.intro (assume H, (and.intro (not.intro (not.elim H ∘ or.inl)) (not.intro (not.elim H ∘ or.inr)))) (and.rec (suppose ¬p, suppose ¬q, not.intro (or.rec (not.elim `¬p`) (not.elim `¬q`)))) example : ¬p ∨ ¬q → ¬(p ∧ q) := or.rec (suppose ¬p, not.intro (not.elim `¬p` ∘ and.left)) (suppose ¬q, not.intro (not.elim `¬q` ∘ and.right)) example : ¬(p ∧ ¬p) := not.intro (and.rec absurd) example : p ∧ ¬q → ¬(p → q) := and.rec (suppose p, suppose ¬q, not.intro (assume H, absurd (H `p`) `¬q`)) example : ¬p → p → q := not.elim example : (¬p ∨ q) → p → q := or.rec not.elim (suppose q, suppose p, `q`) example : p ∨ false ↔ p := iff.intro (or.rec id false.elim) or.inl example : p ∧ false ↔ false := iff.intro and.right false.elim example : ¬(p ↔ ¬p) := not.intro (assume H, have ¬p, from not.intro (suppose p, absurd `p` (iff.mp H `p`)), absurd (iff.mpr H `¬p`) `¬p`) example : (p → q) → (¬q → ¬p) := assume H, suppose ¬q, not.intro (not.elim `¬q` ∘ H) example : (p → r ∨ s) → (p → r) ∨ (p → s) := assume H, or.elim (em r) (suppose r, or.inl (suppose p, `r`)) (suppose ¬r, or.inr (suppose p, or.elim (H `p`) (not.elim `¬r`) id)) example : ¬(p ∧ q) → ¬p ∨ ¬q := assume H, or.elim (em p) (suppose p, or.inr (not.intro (not.elim H ∘ and.intro `p`))) or.inl example : ¬(p → q) → p ∧ ¬q := assume H, or.elim (em p) (suppose p, have ¬q, from not.intro (suppose q, have p → q, from suppose p, `q`, absurd `p → q` H), and.intro `p` `¬q`) (suppose ¬p, have p → q, from suppose p, absurd `p` `¬p`, absurd `p → q` H) example : (p → q) → ¬p ∨ q := assume H, or.elim (em p) (or.inr ∘ H) or.inl example : (¬q → ¬p) → (p → q) := assume H, suppose p, or.elim (em q) id (absurd `p` ∘ H) example : p ∨ ¬p := em p example : ((p → q) → p) → p := assume H : (p → q) → p, or.elim (em p) id (suppose ¬p, have p → q, from not.elim `¬p`, absurd (H `p → q`) `¬p`) end sec_3_6 namespace sec_4_1 open classical variables (A : Type) (p q : A → Prop) (r : Prop) example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (assume H, and.intro (take x, and.left (H x)) (take x, and.right (H x))) (and.rec (assume Hp Hq, take x, and.intro (Hp x) (Hq x))) example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := assume H, assume Hp, take x, H x (Hp x) example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := or.rec (assume H, take x, or.inl (H x)) (assume H, take x, or.inr (H x)) example : A → ((∀ x : A, r) ↔ r) := take a, iff.intro (assume H, H a) (suppose r, take x, `r`) example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := iff.intro (assume H, or.elim (em r) or.inr (suppose ¬r, or.inl (take x, or.elim (H x) id (not.elim `¬r`)))) (or.rec (assume H, take x, or.inl (H x)) (suppose r, take x, or.inr `r`)) example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := iff.intro (assume H, suppose r, take x, H x `r`) (assume H, take x, suppose r, H `r` x) variables (men : Type) (barber : men) (shaves : men → men → Prop) example (H : ∀ x : men, shaves barber x ↔ ¬(shaves x x)) : false := have lem : ∀ {P : Prop}, (P ↔ ¬P) → false, from take P, assume H, have ¬P, from not.intro (suppose P, not.elim (iff.mp H `P`) `P`), not.elim `¬P` (iff.mpr H `¬P`), lem (H barber) end sec_4_1 namespace sec_4_3 open nat -- check nat.left_distrib -- check nat.mul_comm -- check nat.add_comm -- check nat.mul_sub_right_distrib -- check nat.add_sub_add_left example (x y : ℕ) : (x - y) * (x + y) = x * x - y * y := calc (x - y) * (x + y) = x * (x + y) - y * (x + y) : nat.mul_sub_right_distrib ... = (x * x + x * y) - y * (x + y) : nat.left_distrib ... = (x * x + x * y) - (y * x + y * y) : nat.left_distrib ... = (x * x + x * y) - (x * y + y * y) : nat.mul_comm ... = (x * y + x * x) - (x * y + y * y) : nat.add_comm ... = x * x - y * y : nat.add_sub_add_left end sec_4_3 namespace sec_4_5 open function open classical variables (A : Type) (p q : A → Prop) (a : A) (r : Prop) example : (∃ x : A, r) → r := Exists.rec (take x, suppose r, `r`) example : r → (∃ x : A, r) := Exists.intro a example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := iff.intro (Exists.rec (take x, (and.rec (suppose p x, suppose r, and.intro (Exists.intro x `p x`) `r`)))) (and.rec (Exists.rec (take x, suppose p x, suppose r, Exists.intro x (and.intro `p x` `r`)))) example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := iff.intro (Exists.rec (take x, or.rec (or.inl ∘ Exists.intro x) (or.inr ∘ Exists.intro x))) (or.rec (Exists.rec (take x, Exists.intro x ∘ or.inl)) (Exists.rec (take x, Exists.intro x ∘ or.inr))) -- use classical for ← example : (∀ x, p x) ↔ (¬ ∃ x, ¬ p x) := iff.intro (assume H, not.intro (Exists.rec (take x, absurd (H x)))) (assume H, take x, by_contradiction (not.elim H ∘ Exists.intro x)) -- use classical fro ← example : (∃ x, p x) ↔ (¬ ∀ x, ¬ p x) := iff.intro (Exists.rec (take x, suppose p x, not.intro (assume H, not.elim (H x) `p x`))) (assume H : ¬ ∀ x, ¬ p x, by_contradiction (assume G : ¬ ∃ x, p x, have K : ∀ x, ¬ p x, from take x, not.intro (not.elim G ∘ Exists.intro x), not.elim H K)) example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := iff.intro (assume H : ¬ ∃ x, p x, take x, not.intro (not.elim H ∘ Exists.intro x)) (assume H : ∀ x, ¬ p x, not.intro (Exists.rec (take x, suppose p x, not.elim (H x) `p x`))) -- use classical for → example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := iff.intro (assume H : ¬ ∀ x, p x, by_contradiction (assume G : ¬ ∃ x, ¬ p x, have K : ∀ x, p x, from take x, by_contradiction (not.elim G ∘ Exists.intro x), not.elim H K)) (Exists.rec (take x, suppose ¬ p x, not.intro (assume H : ∀ x, p x, not.elim `¬ p x` (H x)))) example : (∀ x, p x → r) ↔ (∃ x, p x) → r := iff.intro Exists.rec (assume H : (∃ x, p x) → r, take x, H ∘ Exists.intro x) -- use classical and (a : A) example : (∃ x, p x → r) ↔ (∀ x, p x) → r := iff.intro (Exists.rec take x, assume H : p x → r, assume G : ∀ x, p x, H (G x)) (assume H : (∀ x, p x) → r, or.elim (em (∃ x, ¬ p x)) (Exists.rec (take x, suppose ¬ p x, Exists.intro x (suppose p x, not.elim `¬ p x` `p x`))) (assume G : ¬ ∃ x, ¬ p x, have K : ∀ x, p x, from take x, by_contradiction (not.elim G ∘ Exists.intro x), have r, from H K, Exists.intro a (suppose p a, `r`))) -- use classical and (a : A) example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := iff.intro (Exists.rec (take x, assume H : r → p x, Exists.intro x ∘ H)) (assume H : r → ∃ x, p x, or.elim (em r) (suppose r, exists.elim (H `r`) (take x, suppose p x, exists.intro x (suppose r, `p x`))) (suppose ¬ r, exists.intro a (not.elim `¬ r`))) end sec_4_5 namespace sec_6_1 inductive bool : Type := | ff : bool | tt : bool namespace bool definition band : bool → bool → bool | band tt tt := tt | band _ _ := ff example : band ff ff = ff := rfl example : band ff tt = ff := rfl example : band tt ff = ff := rfl example : band tt ff = ff := rfl definition bor : bool → bool → bool | bor ff ff := ff | bor _ _ := tt example : bor ff ff = ff := rfl example : bor ff tt = tt := rfl example : bor tt ff = tt := rfl example : bor tt tt = tt := rfl definition bnot : bool → bool | bnot ff := tt | bnot tt := ff example : bnot ff = tt := rfl example : bnot tt = ff := rfl end bool end sec_6_1 namespace sec_6_2 open function inductive option (A : Type) : Type := | none {} : option A | some : A → option A namespace option definition maybe {A B : Type} : B → (A → B) → option A → B | maybe b f oa := option.rec_on oa b f definition bind {A B : Type} : (A → option B) → option A → option B := maybe none definition return {A : Type} : A → option A := some definition mcomp {A B C : Type} : (B → option C) → (A → option B) → (A → option C) | mcomp g f := λ a : A, bind g (f a) notation f `=<<` m := bind f m notation g `<=<` f := mcomp g f -- モナド則 example (A B : Type) (f : A → option B) (x : A) : (f =<< return x) = f x := rfl example (A : Type) (m : option A) : (return =<< m) = m := match m with | none := rfl | some a := rfl end example (A B C : Type) (f : A → option B) (g : B → option C) (m : option A) : ((g <=< f) =<< m) = (g =<< (f =<< m)) := match m with | none := rfl | some a := rfl end definition pfunc (A B : Type) : Type := A → option B definition pcomp {A B C : Type} : pfunc B C → pfunc A B → pfunc A C := mcomp variables A B C : Type variables (f : pfunc A B) (g : pfunc B C) (a : A) (b : B) (c : C) example : f a = none → pcomp g f a = none := assume H : f a = none, calc pcomp g f a = maybe none g (f a) : rfl ... = maybe none g none : {H} -- なぜ brace が必要? ... = none : rfl example : f a = some b → pcomp g f a = g b := assume H : f a = some b, calc pcomp g f a = maybe none g (f a) : rfl ... = maybe none g (some b) : {H} ... = g b : rfl end option inductive inhabited (A : Type) : Type := | mk : A → inhabited A example : inhabited bool := inhabited.mk bool.ff example : inhabited nat := inhabited.mk zero end sec_6_2 namespace sec_6_4 open function open eq inductive nat : Type := | zero : nat | succ : nat → nat namespace nat notation 0 := zero definition add : nat → nat → nat | add n 0 := n | add n (succ m) := succ (add n m) infix `+` := add theorem add_zero : ∀ n : nat, n + 0 = n | add_zero n := rfl theorem add_succ : ∀ n m : nat, n + succ m = succ (n + m) | add_succ n m := rfl theorem add_assoc : ∀ n m k : nat, (n + m) + k = n + (m + k) | add_assoc n m 0 := calc (n + m) + 0 = n + m : add_zero ... = n + (m + 0) : add_zero | add_assoc n m (succ k) := calc (n + m) + succ k = succ ((n + m) + k) : add_succ ... = succ (n + (m + k)) : add_assoc ... = n + succ (m + k) : add_succ ... = n + (m + succ k) : add_succ theorem zero_add : ∀ m : nat, 0 + m = m | zero_add 0 := calc 0 + 0 = 0 : add_zero | zero_add (succ m) := calc 0 + succ m = succ (0 + m) : add_succ ... = succ m : zero_add theorem succ_add : ∀ n m : nat, succ n + m = succ (n + m) | succ_add n 0 := calc succ n + 0 = succ n : add_zero ... = succ (n + 0) : add_zero | succ_add n (succ m) := calc succ n + succ m = succ (succ n + m) : add_succ ... = succ (succ (n + m)) : succ_add ... = succ (n + succ m) : add_succ theorem add_comm : ∀ n m : nat, n + m = m + n | add_comm n 0 := calc n + 0 = n : add_zero ... = 0 + n : zero_add | add_comm n (succ m) := calc n + succ m = succ (n + m) : add_succ ... = succ (m + n) : add_comm ... = succ m + n : succ_add definition mul : nat → nat → nat | mul n 0 := 0 | mul n (succ m) := mul n m + n infix `*` := mul theorem mul_zero : ∀ n : nat, n * 0 = 0 | mul_zero n := rfl theorem mul_succ : ∀ n m : nat, n * (succ m) = n * m + n | mul_succ n m := rfl theorem zero_mul : ∀ m : nat, 0 * m = 0 | zero_mul 0 := calc 0 * 0 = 0 : mul_zero | zero_mul (succ m) := calc 0 * succ m = 0 * m + 0 : mul_succ ... = 0 + 0 : zero_mul ... = 0 : add_zero theorem mul_distrib : ∀ n m k : nat, n * (m + k) = n * m + n * k | mul_distrib n m 0 := calc n * (m + 0) = n * m : add_zero ... = n * m + 0 : add_zero ... = n * m + n * 0 : mul_zero | mul_distrib n m (succ k) := calc n * (m + succ k) = n * succ (m + k) : add_succ ... = n * (m + k) + n : mul_succ ... = (n * m + n * k) + n : mul_distrib ... = n * m + (n * k + n) : add_assoc ... = n * m + n * succ k : mul_succ theorem mul_assoc : ∀ n m k : nat, (n * m) * k = n * (m * k) | mul_assoc n m 0 := calc (n * m) * 0 = 0 : mul_zero ... = n * 0 : mul_zero ... = n * (m * 0) : mul_zero | mul_assoc n m (succ k) := calc (n * m) * succ k = (n * m) * k + n * m : mul_succ ... = n * (m * k) + n * m : mul_assoc ... = n * (m * k + m) : mul_distrib ... = n * (m * succ k) : mul_succ theorem succ_mul : ∀ n m : nat, succ n * m = n * m + m | succ_mul n 0 := calc succ n * 0 = 0 : mul_zero ... = 0 + 0 : add_zero ... = n * 0 + 0 : mul_zero | succ_mul n (succ m) := calc succ n * succ m = succ n * m + succ n : mul_succ ... = (n * m + m) + succ n : succ_mul ... = n * m + (m + succ n) : add_assoc ... = n * m + succ (m + n) : add_succ ... = n * m + succ (n + m) : add_comm ... = n * m + (n + succ m) : add_succ ... = (n * m + n) + succ m : add_assoc ... = n * succ m + succ m : mul_succ theorem mul_comm : ∀ n m : nat, n * m = m * n | mul_comm n 0 := calc n * 0 = 0 : mul_zero ... = 0 * n : zero_mul | mul_comm n (succ m) := calc n * succ m = n * m + n : mul_succ ... = m * n + n : mul_comm ... = succ m * n : succ_mul definition pred : nat → nat | pred 0 := 0 | pred (succ n) := n theorem pred_succ : ∀ n : nat, pred (succ n) = n | pred_succ n := rfl theorem succ_pred : ∀ n : nat, n ≠ 0 → succ (pred n) = n | succ_pred 0 := assume `0 ≠ 0`, absurd rfl `0 ≠ 0` | succ_pred (succ n) := assume `succ n ≠ 0`, -- 使わない calc succ (pred (succ n)) = succ n : pred_succ definition sub : nat → nat → nat | sub n 0 := 0 | sub n (succ m) := pred (sub n m) notation 1 := succ zero definition pow : nat → nat → nat | pow n 0 := 1 | pow n (succ m) := pow n m * n infix `^` := pow theorem pow_zero : ∀ n : nat, n ^ 0 = 1 | pow_zero n := rfl theorem pow_succ : ∀ n m : nat, n ^ (succ m) = n ^ m * n | pow_succ n m := rfl theorem mul_one : ∀ n : nat, n * 1 = n | mul_one n := calc n * 1 = n * 0 + n : mul_succ ... = 0 + n : mul_zero ... = n : zero_add theorem pow_add : ∀ n m k : nat, n ^ (m + k) = n ^ m * n ^ k | pow_add n m 0 := calc n ^ (m + 0) = n ^ m : add_zero ... = n ^ m * 1 : mul_one ... = n ^ m * n ^ 0 : pow_zero | pow_add n m (succ k) := calc n ^ (m + succ k) = n ^ succ (m + k) : add_succ ... = n ^ (m + k) * n : pow_succ ... = (n ^ m * n ^ k) * n : pow_add ... = n ^ m * (n ^ k * n) : mul_assoc ... = n ^ m * n ^ succ k : pow_succ end nat end sec_6_4 namespace sec_6_5 inductive list (A : Type) : Type := | nil {} : list A | cons : A → list A → list A namespace list variable {A : Type} notation x :: xs := cons x xs definition append : list A → list A → list A | append nil ys := ys | append (x :: xs) ys := x :: (append xs ys) notation xs ++ ys := append xs ys theorem nil_append : ∀ xs : list A, nil ++ xs = xs | nil_append xs := rfl theorem cons_append : ∀ x : A, ∀ xs ys : list A, (x :: xs) ++ ys = x :: (xs ++ ys) | cons_append x xs ys := rfl theorem append_nil : ∀ t : list A, t ++ nil = t | append_nil nil := calc nil ++ nil = nil : nil_append | append_nil (x :: xs) := calc (x :: xs) ++ nil = x :: (xs ++ nil) : cons_append ... = x :: xs : append_nil theorem append_assoc : ∀ xs ys zs : list A, (xs ++ ys) ++ zs = xs ++ (ys ++ zs) | append_assoc nil ys zs := calc (nil ++ ys) ++ zs = ys ++ zs : nil_append ... = nil ++ (ys ++ zs) : nil_append | append_assoc (x :: xs) ys zs := calc ((x :: xs) ++ ys) ++ zs = (x :: (xs ++ ys)) ++ zs : cons_append ... = x :: ((xs ++ ys) ++ zs) : cons_append ... = x :: (xs ++ (ys ++ zs)) : append_assoc ... = (x :: xs) ++ (ys ++ zs) : cons_append end list end sec_6_5 namespace sec_6_6 theorem cast {A B : Type} : A = B → A → B := eq.rec_on theorem subst {A : Type} {a b : A} {P : A → Prop} : a = b → P a → P b := suppose a = b, suppose P a, eq.rec `P a` `a = b` theorem symm {A : Type} {a b : A} : a = b → b = a := suppose a = b, subst `a = b` (eq.refl a) theorem trans {A : Type} {a b c : A} : a = b → b = c → a = c := suppose a = b, suppose b = c, subst `b = c` `a = b` theorem congr {A B : Type} {a a' : A} (f : A → B) : a = a' → f a = f a' := suppose a = a', subst `a = a'` (eq.refl (f a)) end sec_6_6 namespace sec_6_8 open function inductive tree (A : Type) : Type := | leaf : A → tree A | node : tree A → tree A → tree A open tree variable {A : Type} theorem leaf_ne_node {a : A} {l r : tree A} : leaf a ≠ node l r := not.intro tree.no_confusion theorem leaf_inj {a b : A} : leaf a = leaf b → a = b := assume H, tree.no_confusion H id theorem node_inj {l r l' r' : tree A} : node l r = node l' r' → l = l' ∧ r = r' := assume H, tree.no_confusion H and.intro theorem node_inj_left {l r l' r' : tree A} : node l r = node l' r' → l = l' := and.left ∘ node_inj theorem node_inj_right {l r l' r' : tree A} : node l r = node l' r' → r = r' := and.right ∘ node_inj end sec_6_8 namespace induction_on_vector open nat (zero succ) inductive vector (A : Type) : nat → Type := | nil {} : vector A zero | cons : Π {n : nat}, A → vector A n → vector A (succ n) open vector (nil cons) definition uncons {A : Type} : Π {n : nat}, vector A (succ n) → A × vector A n := have uncons' : Π (m : nat), vector A m → Π n : nat, m = succ n → A × vector A n, from take m xxs, vector.cases_on xxs (take n' H, nat.no_confusion H) (take n' x xs n H, pair x (eq.rec xs (nat.succ.inj H))), take n xxs, uncons' (succ n) xxs n rfl open function prod definition head {A : Type} {n : nat} : vector A (succ n) → A := pr1 ∘ uncons definition tail {A : Type} {n : nat} : vector A (succ n) → vector A n := pr2 ∘ uncons definition map {A B : Type} (f : A → B) : Π {n : nat}, vector A n → vector B n := nat.rec (take xs, nil) (take n map_f_n xs, cons (f (head xs)) (map_f_n (tail xs))) definition zipWith {A B C : Type} (f : A → B → C) : Π {n : nat}, vector A n → vector B n → vector C n := nat.rec (take xs ys, nil) (take n zipWith_f_n xs ys, cons (f (head xs) (head ys)) (zipWith_f_n (tail xs) (tail ys))) definition zip {A B : Type} {n : nat} : vector A n → vector B n → vector (A × B) n := zipWith pair end induction_on_vector
909660a7347d79ba7e8c0933be7bab238e92a012
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/category/Kleisli.lean
470d94c082d851285cdb36f90fb76eeb79691238
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,337
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon The Kleisli construction on the Type category TODO: generalise this to work with category_theory.monad -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.category.default import Mathlib.PostPort universes u v u_1 u_2 namespace Mathlib namespace category_theory def Kleisli (m : Type u → Type v) [Monad m] := Type u def Kleisli.mk (m : Type u → Type v) [Monad m] (α : Type u) : Kleisli m := α protected instance Kleisli.category_struct {m : Type u_1 → Type u_2} [Monad m] : category_struct (Kleisli m) := category_struct.mk (fun (α : Kleisli m) (x : α) => pure x) fun (X Y Z : Kleisli m) (f : X ⟶ Y) (g : Y ⟶ Z) => f >=> g protected instance Kleisli.category {m : Type u_1 → Type u_2} [Monad m] [is_lawful_monad m] : category (Kleisli m) := category.mk @[simp] theorem Kleisli.id_def {m : Type u_1 → Type u_2} [Monad m] [is_lawful_monad m] (α : Kleisli m) : 𝟙 = pure := rfl theorem Kleisli.comp_def {m : Type u_1 → Type u_2} [Monad m] [is_lawful_monad m] (α : Kleisli m) (β : Kleisli m) (γ : Kleisli m) (xs : α ⟶ β) (ys : β ⟶ γ) (a : α) : category_struct.comp xs ys a = xs a >>= ys := rfl
01ce1a281a28d1754f9261c4b89ef6d0623d7d80
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/transitiveInferenceAggregate.lean
4a1b790afa47f399315a686d5da22bf03e8ee812
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,891
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..cosette_tactics open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int constant integer_1 : const int constant integer_7 : const int lemma rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_deptno)) (COUNT(uvariable (right⋅emp_slacker)))) FROM1 ((table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt)) GROUP BY (right⋅emp_deptno))) (table rel_emp)) WHERE (equal (uvariable (right⋅left⋅left)) (uvariable (right⋅right⋅emp_deptno)))) : SQL Γ _ ) = denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_deptno)) (COUNT(uvariable (right⋅emp_slacker)))) FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt) GROUP BY (right⋅emp_deptno))) ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt)))) WHERE (equal (uvariable (right⋅left⋅left)) (uvariable (right⋅right⋅emp_deptno)))) : SQL Γ _) := begin intros, unfold_all_denotations, funext, dsimp, print_size, simp, print_size, congr, funext, apply congr_arg _, funext, apply congr_arg _, funext, congr, sorry -- TODO: here push predicate into squashed expressions and SDP is required end
adb9b591f956fdae3a5909f42e72cab95b78ac5d
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/Safe.lean
a1e2a8a320dd07c41057622ec53e7715e77dcd31
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
626
lean
-- Safe /- [Safe] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Dependable]. An instance of type [SystemType] is deemed [Safe] if and only if all the requirements are satisfied. -/ import SystemModel.System inductive Safe (sys_type: SystemType): Prop | intro : (exists safe: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, safe c p s st) -> Safe
972d2758d4a0c9765d47047d6d5180ab0d957cbd
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/pfun.lean
94cb1ea8ca99822a2f83da079ef037ea1bfc70a1
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
24,926
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon -/ import data.rel /-- `roption α` is the type of "partial values" of type `α`. It is similar to `option α` except the domain condition can be an arbitrary proposition, not necessarily decidable. -/ structure {u} roption (α : Type u) : Type u := (dom : Prop) (get : dom → α) namespace roption variables {α : Type*} {β : Type*} {γ : Type*} /-- Convert an `roption α` with a decidable domain to an option -/ def to_option (o : roption α) [decidable o.dom] : option α := if h : dom o then some (o.get h) else none /-- `roption` extensionality -/ theorem ext' : ∀ {o p : roption α} (H1 : o.dom ↔ p.dom) (H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p | ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1, by cases t; rw [show o = p, from funext $ λp, H2 p p] /-- `roption` eta expansion -/ @[simp] theorem eta : Π (o : roption α), (⟨o.dom, λ h, o.get h⟩ : roption α) = o | ⟨h, f⟩ := rfl /-- `a ∈ o` means that `o` is defined and equal to `a` -/ protected def mem (a : α) (o : roption α) : Prop := ∃ h, o.get h = a instance : has_mem α (roption α) := ⟨roption.mem⟩ theorem mem_eq (a : α) (o : roption α) : (a ∈ o) = (∃ h, o.get h = a) := rfl theorem dom_iff_mem : ∀ {o : roption α}, o.dom ↔ ∃y, y ∈ o | ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩ theorem get_mem {o : roption α} (h) : get o h ∈ o := ⟨_, rfl⟩ /-- `roption` extensionality -/ @[ext] theorem ext {o p : roption α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p := ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst, λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $ λ a b, ((H _).2 ⟨_, rfl⟩).snd /-- The `none` value in `roption` has a `false` domain and an empty function. -/ def none : roption α := ⟨false, false.rec _⟩ instance : inhabited (roption α) := ⟨none⟩ @[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst /-- The `some a` value in `roption` has a `true` domain and the function returns `a`. -/ def some (a : α) : roption α := ⟨true, λ_, a⟩ theorem mem_unique : ∀ {a b : α} {o : roption α}, a ∈ o → b ∈ o → a = b | _ _ ⟨p, f⟩ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl theorem mem.left_unique : relator.left_unique ((∈) : α → roption α → Prop) := ⟨λ a o b, mem_unique⟩ theorem get_eq_of_mem {o : roption α} {a} (h : a ∈ o) (h') : get o h' = a := mem_unique ⟨_, rfl⟩ h @[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩ @[simp] theorem mem_some_iff {a b} : b ∈ (some a : roption α) ↔ b = a := ⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩ theorem eq_some_iff {a : α} {o : roption α} : o = some a ↔ a ∈ o := ⟨λ e, e.symm ▸ mem_some _, λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩ theorem eq_none_iff {o : roption α} : o = none ↔ ∀ a, a ∉ o := ⟨λ e, e.symm ▸ not_mem_none, λ h, ext (by simpa [not_mem_none])⟩ theorem eq_none_iff' {o : roption α} : o = none ↔ ¬ o.dom := ⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩ lemma some_ne_none (x : α) : some x ≠ none := by { intro h, change none.dom, rw [← h], trivial } lemma ne_none_iff {o : roption α} : o ≠ none ↔ ∃x, o = some x := begin split, { rw [ne, eq_none_iff], intro h, push_neg at h, cases h with x hx, use x, rwa [eq_some_iff] }, { rintro ⟨x, rfl⟩, apply some_ne_none } end lemma eq_none_or_eq_some (o : roption α) : o = none ∨ ∃ x, o = some x := begin classical, by_cases h : o.dom, { rw dom_iff_mem at h, right, apply exists_imp_exists _ h, simp [eq_some_iff] }, { rw eq_none_iff', exact or.inl h }, end @[simp] lemma some_inj {a b : α} : roption.some a = some b ↔ a = b := function.injective.eq_iff (λ a b h, congr_fun (eq_of_heq (roption.mk.inj h).2) trivial) @[simp] lemma some_get {a : roption α} (ha : a.dom) : roption.some (roption.get a ha) = a := eq.symm (eq_some_iff.2 ⟨ha, rfl⟩) lemma get_eq_iff_eq_some {a : roption α} {ha : a.dom} {b : α} : a.get ha = b ↔ a = some b := ⟨λ h, by simp [h.symm], λ h, by simp [h]⟩ lemma get_eq_get_of_eq (a : roption α) (ha : a.dom) {b : roption α} (h : a = b) : a.get ha = b.get (h ▸ ha) := by { congr, exact h } instance none_decidable : decidable (@none α).dom := decidable.false instance some_decidable (a : α) : decidable (some a).dom := decidable.true def get_or_else (a : roption α) [decidable a.dom] (d : α) := if ha : a.dom then a.get ha else d @[simp] lemma get_or_else_none (d : α) : get_or_else none d = d := dif_neg id @[simp] lemma get_or_else_some (a : α) (d : α) : get_or_else (some a) d = a := dif_pos trivial @[simp] theorem mem_to_option {o : roption α} [decidable o.dom] {a : α} : a ∈ to_option o ↔ a ∈ o := begin unfold to_option, by_cases h : o.dom; simp [h], { exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ }, { exact mt Exists.fst h } end /-- Convert an `option α` into an `roption α` -/ def of_option : option α → roption α | option.none := none | (option.some a) := some a @[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o | option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩ | (option.some b) := ⟨λ h, congr_arg option.some h.snd, λ h, ⟨trivial, option.some.inj h⟩⟩ @[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some | option.none := by simp [of_option, none] | (option.some a) := by simp [of_option] theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ := roption.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl] instance : has_coe (option α) (roption α) := ⟨of_option⟩ @[simp] theorem mem_coe {a : α} {o : option α} : a ∈ (o : roption α) ↔ a ∈ o := mem_of_option @[simp] theorem coe_none : (@option.none α : roption α) = none := rfl @[simp] theorem coe_some (a : α) : (option.some a : roption α) = some a := rfl @[elab_as_eliminator] protected lemma induction_on {P : roption α → Prop} (a : roption α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a := (classical.em a.dom).elim (λ h, roption.some_get h ▸ hsome _) (λ h, (eq_none_iff'.2 h).symm ▸ hnone) instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom | option.none := roption.none_decidable | (option.some a) := roption.some_decidable a @[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o := by cases o; refl @[simp] theorem of_to_option (o : roption α) [decidable o.dom] : of_option (to_option o) = o := ext $ λ a, mem_of_option.trans mem_to_option noncomputable def equiv_option : roption α ≃ option α := by haveI := classical.dec; exact ⟨λ o, to_option o, of_option, λ o, of_to_option o, λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩ instance : order_bot (roption α) := { le := λ x y, ∀ i, i ∈ x → i ∈ y, le_refl := λ x y, id, le_trans := λ x y z f g i, g _ ∘ f _, le_antisymm := λ x y f g, roption.ext $ λ z, ⟨f _, g _⟩, bot := none, bot_le := by { introv x, rintro ⟨⟨_⟩,_⟩, } } instance : preorder (roption α) := by apply_instance lemma le_total_of_le_of_le {x y : roption α} (z : roption α) (hx : x ≤ z) (hy : y ≤ z) : x ≤ y ∨ y ≤ x := begin rcases roption.eq_none_or_eq_some x with h | ⟨b, h₀⟩, { rw h, left, apply order_bot.bot_le _ }, right, intros b' h₁, rw roption.eq_some_iff at h₀, replace hx := hx _ h₀, replace hy := hy _ h₁, replace hx := roption.mem_unique hx hy, subst hx, exact h₀ end /-- `assert p f` is a bind-like operation which appends an additional condition `p` to the domain and uses `f` to produce the value. -/ def assert (p : Prop) (f : p → roption α) : roption α := ⟨∃h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩ /-- The bind operation has value `g (f.get)`, and is defined when all the parts are defined. -/ protected def bind (f : roption α) (g : α → roption β) : roption β := assert (dom f) (λb, g (f.get b)) /-- The map operation for `roption` just maps the value and maintains the same domain. -/ def map (f : α → β) (o : roption α) : roption β := ⟨o.dom, f ∘ o.get⟩ theorem mem_map (f : α → β) {o : roption α} : ∀ {a}, a ∈ o → f a ∈ map f o | _ ⟨h, rfl⟩ := ⟨_, rfl⟩ @[simp] theorem mem_map_iff (f : α → β) {o : roption α} {b} : b ∈ map f o ↔ ∃ a ∈ o, f a = b := ⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end, λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩ @[simp] theorem map_none (f : α → β) : map f none = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) := eq_some_iff.2 $ mem_map f $ mem_some _ theorem mem_assert {p : Prop} {f : p → roption α} : ∀ {a} (h : p), a ∈ f h → a ∈ assert p f | _ x ⟨h, rfl⟩ := ⟨⟨x, h⟩, rfl⟩ @[simp] theorem mem_assert_iff {p : Prop} {f : p → roption α} {a} : a ∈ assert p f ↔ ∃ h : p, a ∈ f h := ⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end, λ ⟨a, h⟩, mem_assert _ h⟩ lemma assert_pos {p : Prop} {f : p → roption α} (h : p) : assert p f = f h := begin dsimp [assert], cases h' : f h, simp only [h', h, true_and, iff_self, exists_prop_of_true, eq_iff_iff], apply function.hfunext, { simp only [h,h',exists_prop_of_true] }, { cc } end lemma assert_neg {p : Prop} {f : p → roption α} (h : ¬ p) : assert p f = none := begin dsimp [assert,none], congr, { simp only [h, not_false_iff, exists_prop_of_false] }, { apply function.hfunext, { simp only [h, not_false_iff, exists_prop_of_false] }, cc }, end theorem mem_bind {f : roption α} {g : α → roption β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g | _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨h, h₂⟩, rfl⟩ @[simp] theorem mem_bind_iff {f : roption α} {g : α → roption β} {b} : b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a := ⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end, λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩ @[simp] theorem bind_none (f : α → roption β) : none.bind f = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem bind_some (a : α) (f : α → roption β) : (some a).bind f = f a := ext $ by simp theorem bind_some_eq_map (f : α → β) (x : roption α) : x.bind (some ∘ f) = map f x := ext $ by simp [eq_comm] theorem bind_assoc {γ} (f : roption α) (g : α → roption β) (k : β → roption γ) : (f.bind g).bind k = f.bind (λ x, (g x).bind k) := ext $ λ a, by simp; exact ⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩, λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩ @[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → roption γ) : (map f x).bind g = x.bind (λ y, g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp @[simp] theorem map_bind {γ} (f : α → roption β) (x : roption α) (g : β → γ) : map g (x.bind f) = x.bind (λ y, map g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map] theorem map_map (g : β → γ) (f : α → β) (o : roption α) : map g (map f o) = map (g ∘ f) o := by rw [← bind_some_eq_map, bind_map, bind_some_eq_map] instance : monad roption := { pure := @some, map := @map, bind := @roption.bind } instance : is_lawful_monad roption := { bind_pure_comp_eq_map := @bind_some_eq_map, id_map := λ β f, by cases f; refl, pure_bind := @bind_some, bind_assoc := @bind_assoc } theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o := by rw [show f = id, from funext H]; exact id_map o @[simp] theorem bind_some_right (x : roption α) : x.bind some = x := by rw [bind_some_eq_map]; simp [map_id'] @[simp] theorem pure_eq_some (a : α) : pure a = some a := rfl @[simp] theorem ret_eq_some (a : α) : return a = some a := rfl @[simp] theorem map_eq_map {α β} (f : α → β) (o : roption α) : f <$> o = map f o := rfl @[simp] theorem bind_eq_bind {α β} (f : roption α) (g : α → roption β) : f >>= g = f.bind g := rfl lemma bind_le {α} (x : roption α) (f : α → roption β) (y : roption β) : x >>= f ≤ y ↔ (∀ a, a ∈ x → f a ≤ y) := begin split; intro h, { intros a h' b, replace h := h b, simp only [and_imp, exists_prop, bind_eq_bind, mem_bind_iff, exists_imp_distrib] at h, apply h _ h' }, { intros b h', simp only [exists_prop, bind_eq_bind, mem_bind_iff] at h', rcases h' with ⟨a,h₀,h₁⟩, apply h _ h₀ _ h₁ }, end instance : monad_fail roption := { fail := λ_ _, none, ..roption.monad } /- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when `p` implies `o` is defined. -/ def restrict (p : Prop) : ∀ (o : roption α), (p → o.dom) → roption α | ⟨d, f⟩ H := ⟨p, λh, f (H h)⟩ @[simp] theorem mem_restrict (p : Prop) (o : roption α) (h : p → o.dom) (a : α) : a ∈ restrict p o h ↔ p ∧ a ∈ o := begin cases o, dsimp [restrict, mem_eq], split, { rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ }, rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩ end /-- `unwrap o` gets the value at `o`, ignoring the condition. (This function is unsound.) -/ meta def unwrap (o : roption α) : α := o.get undefined theorem assert_defined {p : Prop} {f : p → roption α} : ∀ (h : p), (f h).dom → (assert p f).dom := exists.intro theorem bind_defined {f : roption α} {g : α → roption β} : ∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined @[simp] theorem bind_dom {f : roption α} {g : α → roption β} : (f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl end roption /-- `pfun α β`, or `α →. β`, is the type of partial functions from `α` to `β`. It is defined as `α → roption β`. -/ def pfun (α : Type*) (β : Type*) := α → roption β infixr ` →. `:25 := pfun namespace pfun variables {α : Type*} {β : Type*} {γ : Type*} instance : inhabited (α →. β) := ⟨λ a, roption.none⟩ /-- The domain of a partial function -/ def dom (f : α →. β) : set α := {a | (f a).dom} theorem mem_dom (f : α →. β) (x : α) : x ∈ dom f ↔ ∃ y, y ∈ f x := by simp [dom, roption.dom_iff_mem] theorem dom_eq (f : α →. β) : dom f = {x | ∃ y, y ∈ f x} := set.ext (mem_dom f) /-- Evaluate a partial function -/ def fn (f : α →. β) (x) (h : dom f x) : β := (f x).get h /-- Evaluate a partial function to return an `option` -/ def eval_opt (f : α →. β) [D : decidable_pred (∈ dom f)] (x : α) : option β := @roption.to_option _ _ (D x) /-- Partial function extensionality -/ theorem ext' {f g : α →. β} (H1 : ∀ a, a ∈ dom f ↔ a ∈ dom g) (H2 : ∀ a p q, f.fn a p = g.fn a q) : f = g := funext $ λ a, roption.ext' (H1 a) (H2 a) theorem ext {f g : α →. β} (H : ∀ a b, b ∈ f a ↔ b ∈ g a) : f = g := funext $ λ a, roption.ext (H a) /-- Turn a partial function into a function out of a subtype -/ def as_subtype (f : α →. β) (s : f.dom) : β := f.fn s s.2 /-- The set of partial functions `α →. β` is equivalent to the set of pairs `(p : α → Prop, f : subtype p → β)`. -/ def equiv_subtype : (α →. β) ≃ (Σ p : α → Prop, subtype p → β) := ⟨λ f, ⟨λ a, (f a).dom, as_subtype f⟩, λ f x, ⟨f.1 x, λ h, f.2 ⟨x, h⟩⟩, λ f, funext $ λ a, roption.eta _, λ ⟨p, f⟩, by dsimp; congr; funext a; cases a; refl⟩ theorem as_subtype_eq_of_mem {f : α →. β} {x : α} {y : β} (fxy : y ∈ f x) (domx : x ∈ f.dom) : f.as_subtype ⟨x, domx⟩ = y := roption.mem_unique (roption.get_mem _) fxy /-- Turn a total function into a partial function -/ protected def lift (f : α → β) : α →. β := λ a, roption.some (f a) instance : has_coe (α → β) (α →. β) := ⟨pfun.lift⟩ @[simp] theorem lift_eq_coe (f : α → β) : pfun.lift f = f := rfl @[simp] theorem coe_val (f : α → β) (a : α) : (f : α →. β) a = roption.some (f a) := rfl /-- The graph of a partial function is the set of pairs `(x, f x)` where `x` is in the domain of `f`. -/ def graph (f : α →. β) : set (α × β) := {p | p.2 ∈ f p.1} def graph' (f : α →. β) : rel α β := λ x y, y ∈ f x /-- The range of a partial function is the set of values `f x` where `x` is in the domain of `f`. -/ def ran (f : α →. β) : set β := {b | ∃a, b ∈ f a} /-- Restrict a partial function to a smaller domain. -/ def restrict (f : α →. β) {p : set α} (H : p ⊆ f.dom) : α →. β := λ x, roption.restrict (x ∈ p) (f x) (@H x) @[simp] theorem mem_restrict {f : α →. β} {s : set α} (h : s ⊆ f.dom) (a : α) (b : β) : b ∈ restrict f h a ↔ a ∈ s ∧ b ∈ f a := by simp [restrict] def res (f : α → β) (s : set α) : α →. β := restrict (pfun.lift f) (set.subset_univ s) theorem mem_res (f : α → β) (s : set α) (a : α) (b : β) : b ∈ res f s a ↔ (a ∈ s ∧ f a = b) := by simp [res, @eq_comm _ b] theorem res_univ (f : α → β) : pfun.res f set.univ = f := rfl theorem dom_iff_graph (f : α →. β) (x : α) : x ∈ f.dom ↔ ∃y, (x, y) ∈ f.graph := roption.dom_iff_mem theorem lift_graph {f : α → β} {a b} : (a, b) ∈ (f : α →. β).graph ↔ f a = b := show (∃ (h : true), f a = b) ↔ f a = b, by simp /-- The monad `pure` function, the total constant `x` function -/ protected def pure (x : β) : α →. β := λ_, roption.some x /-- The monad `bind` function, pointwise `roption.bind` -/ def bind (f : α →. β) (g : β → α →. γ) : α →. γ := λa, roption.bind (f a) (λb, g b a) /-- The monad `map` function, pointwise `roption.map` -/ def map (f : β → γ) (g : α →. β) : α →. γ := λa, roption.map f (g a) instance : monad (pfun α) := { pure := @pfun.pure _, bind := @pfun.bind _, map := @pfun.map _ } instance : is_lawful_monad (pfun α) := { bind_pure_comp_eq_map := λ β γ f x, funext $ λ a, roption.bind_some_eq_map _ _, id_map := λ β f, by funext a; dsimp [functor.map, pfun.map]; cases f a; refl, pure_bind := λ β γ x f, funext $ λ a, roption.bind_some.{u_1 u_2} _ (f x), bind_assoc := λ β γ δ f g k, funext $ λ a, roption.bind_assoc (f a) (λ b, g b a) (λ b, k b a) } theorem pure_defined (p : set α) (x : β) : p ⊆ (@pfun.pure α _ x).dom := set.subset_univ p theorem bind_defined {α β γ} (p : set α) {f : α →. β} {g : β → α →. γ} (H1 : p ⊆ f.dom) (H2 : ∀x, p ⊆ (g x).dom) : p ⊆ (f >>= g).dom := λa ha, (⟨H1 ha, H2 _ ha⟩ : (f >>= g).dom a) def fix (f : α →. β ⊕ α) : α →. β := λ a, roption.assert (acc (λ x y, sum.inr x ∈ f y) a) $ λ h, @well_founded.fix_F _ (λ x y, sum.inr x ∈ f y) _ (λ a IH, roption.assert (f a).dom $ λ hf, by cases e : (f a).get hf with b a'; [exact roption.some b, exact IH _ ⟨hf, e⟩]) a h theorem dom_of_mem_fix {f : α →. β ⊕ α} {a : α} {b : β} (h : b ∈ fix f a) : (f a).dom := let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in by rw well_founded.fix_F_eq at h₂; exact h₂.fst.fst theorem mem_fix_iff {f : α →. β ⊕ α} {a : α} {b : β} : b ∈ fix f a ↔ sum.inl b ∈ f a ∨ ∃ a', sum.inr a' ∈ f a ∧ b ∈ fix f a' := ⟨λ h, let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in begin rw well_founded.fix_F_eq at h₂, simp at h₂, cases h₂ with h₂ h₃, cases e : (f a).get h₂ with b' a'; simp [e] at h₃, { subst b', refine or.inl ⟨h₂, e⟩ }, { exact or.inr ⟨a', ⟨_, e⟩, roption.mem_assert _ h₃⟩ } end, λ h, begin simp [fix], rcases h with ⟨h₁, h₂⟩ | ⟨a', h, h₃⟩, { refine ⟨⟨_, λ y h', _⟩, _⟩, { injection roption.mem_unique ⟨h₁, h₂⟩ h' }, { rw well_founded.fix_F_eq, simp [h₁, h₂] } }, { simp [fix] at h₃, cases h₃ with h₃ h₄, refine ⟨⟨_, λ y h', _⟩, _⟩, { injection roption.mem_unique h h' with e, exact e ▸ h₃ }, { cases h with h₁ h₂, rw well_founded.fix_F_eq, simp [h₁, h₂, h₄] } } end⟩ @[elab_as_eliminator] def fix_induction {f : α →. β ⊕ α} {b : β} {C : α → Sort*} {a : α} (h : b ∈ fix f a) (H : ∀ a, b ∈ fix f a → (∀ a', b ∈ fix f a' → sum.inr a' ∈ f a → C a') → C a) : C a := begin replace h := roption.mem_assert_iff.1 h, have := h.snd, revert this, induction h.fst with a ha IH, intro h₂, refine H a (roption.mem_assert_iff.2 ⟨⟨_, ha⟩, h₂⟩) (λ a' ha' fa', _), have := (roption.mem_assert_iff.1 ha').snd, exact IH _ fa' ⟨ha _ fa', this⟩ this end end pfun namespace pfun variables {α : Type*} {β : Type*} (f : α →. β) def image (s : set α) : set β := rel.image f.graph' s lemma image_def (s : set α) : image f s = {y | ∃ x ∈ s, y ∈ f x} := rfl lemma mem_image (y : β) (s : set α) : y ∈ image f s ↔ ∃ x ∈ s, y ∈ f x := iff.rfl lemma image_mono {s t : set α} (h : s ⊆ t) : f.image s ⊆ f.image t := rel.image_mono _ h lemma image_inter (s t : set α) : f.image (s ∩ t) ⊆ f.image s ∩ f.image t := rel.image_inter _ s t lemma image_union (s t : set α) : f.image (s ∪ t) = f.image s ∪ f.image t := rel.image_union _ s t def preimage (s : set β) : set α := rel.preimage (λ x y, y ∈ f x) s lemma preimage_def (s : set β) : preimage f s = {x | ∃ y ∈ s, y ∈ f x} := rfl lemma mem_preimage (s : set β) (x : α) : x ∈ preimage f s ↔ ∃ y ∈ s, y ∈ f x := iff.rfl lemma preimage_subset_dom (s : set β) : f.preimage s ⊆ f.dom := assume x ⟨y, ys, fxy⟩, roption.dom_iff_mem.mpr ⟨y, fxy⟩ lemma preimage_mono {s t : set β} (h : s ⊆ t) : f.preimage s ⊆ f.preimage t := rel.preimage_mono _ h lemma preimage_inter (s t : set β) : f.preimage (s ∩ t) ⊆ f.preimage s ∩ f.preimage t := rel.preimage_inter _ s t lemma preimage_union (s t : set β) : f.preimage (s ∪ t) = f.preimage s ∪ f.preimage t := rel.preimage_union _ s t lemma preimage_univ : f.preimage set.univ = f.dom := by ext; simp [mem_preimage, mem_dom] def core (s : set β) : set α := rel.core f.graph' s lemma core_def (s : set β) : core f s = {x | ∀ y, y ∈ f x → y ∈ s} := rfl lemma mem_core (x : α) (s : set β) : x ∈ core f s ↔ (∀ y, y ∈ f x → y ∈ s) := iff.rfl lemma compl_dom_subset_core (s : set β) : f.domᶜ ⊆ f.core s := assume x hx y fxy, absurd ((mem_dom f x).mpr ⟨y, fxy⟩) hx lemma core_mono {s t : set β} (h : s ⊆ t) : f.core s ⊆ f.core t := rel.core_mono _ h lemma core_inter (s t : set β) : f.core (s ∩ t) = f.core s ∩ f.core t := rel.core_inter _ s t lemma mem_core_res (f : α → β) (s : set α) (t : set β) (x : α) : x ∈ core (res f s) t ↔ (x ∈ s → f x ∈ t) := by simp [mem_core, mem_res] section open_locale classical lemma core_res (f : α → β) (s : set α) (t : set β) : core (res f s) t = sᶜ ∪ f ⁻¹' t := by { ext, rw mem_core_res, by_cases h : x ∈ s; simp [h] } end lemma core_restrict (f : α → β) (s : set β) : core (f : α →. β) s = set.preimage f s := by ext x; simp [core_def] lemma preimage_subset_core (f : α →. β) (s : set β) : f.preimage s ⊆ f.core s := assume x ⟨y, ys, fxy⟩ y' fxy', have y = y', from roption.mem_unique fxy fxy', this ▸ ys lemma preimage_eq (f : α →. β) (s : set β) : f.preimage s = f.core s ∩ f.dom := set.eq_of_subset_of_subset (set.subset_inter (preimage_subset_core f s) (preimage_subset_dom f s)) (assume x ⟨xcore, xdom⟩, let y := (f x).get xdom in have ys : y ∈ s, from xcore _ (roption.get_mem _), show x ∈ preimage f s, from ⟨(f x).get xdom, ys, roption.get_mem _⟩) lemma core_eq (f : α →. β) (s : set β) : f.core s = f.preimage s ∪ f.domᶜ := by rw [preimage_eq, set.union_distrib_right, set.union_comm (dom f), set.compl_union_self, set.inter_univ, set.union_eq_self_of_subset_right (compl_dom_subset_core f s)] lemma preimage_as_subtype (f : α →. β) (s : set β) : f.as_subtype ⁻¹' s = subtype.val ⁻¹' pfun.preimage f s := begin ext x, simp only [set.mem_preimage, set.mem_set_of_eq, pfun.as_subtype, pfun.mem_preimage], show pfun.fn f (x.val) _ ∈ s ↔ ∃ y ∈ s, y ∈ f (x.val), exact iff.intro (assume h, ⟨_, h, roption.get_mem _⟩) (assume ⟨y, ys, fxy⟩, have f.fn x.val x.property ∈ f x.val := roption.get_mem _, roption.mem_unique fxy this ▸ ys) end end pfun
bd822474f3eed662d8e4e9bb8ac91426d1e72d4d
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Init/Data/List/BasicAux.lean
645b095ecd8c96e5c1d2c4ac62dc3dad07723c48
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
2,195
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.List.Basic import Init.Util universe u namespace List /- The following functions can't be defined at `Init.Data.List.Basic`, because they depend on `Init.Util`, and `Init.Util` depends on `Init.Data.List.Basic`. -/ def get! [Inhabited α] : Nat → List α → α | 0, a::as => a | n+1, a::as => get! n as | _, _ => panic! "invalid index" def get? : Nat → List α → Option α | 0, a::as => some a | n+1, a::as => get? n as | _, _ => none def getD (idx : Nat) (as : List α) (a₀ : α) : α := (as.get? idx).getD a₀ def head! [Inhabited α] : List α → α | [] => panic! "empty list" | a::_ => a def head? : List α → Option α | [] => none | a::_ => some a def headD : List α → α → α | [], a₀ => a₀ | a::_, _ => a def tail! : List α → List α | [] => panic! "empty list" | a::as => as def tail? : List α → Option (List α) | [] => none | a::as => some as def tailD : List α → List α → List α | [], as₀ => as₀ | a::as, _ => as def getLast : ∀ (as : List α), as ≠ [] → α | [], h => absurd rfl h | [a], h => a | a::b::as, h => getLast (b::as) (fun h => List.noConfusion h) def getLast! [Inhabited α] : List α → α | [] => panic! "empty list" | a::as => getLast (a::as) (fun h => List.noConfusion h) def getLast? : List α → Option α | [] => none | a::as => some (getLast (a::as) (fun h => List.noConfusion h)) def getLastD : List α → α → α | [], a₀ => a₀ | a::as, _ => getLast (a::as) (fun h => List.noConfusion h) def rotateLeft (xs : List α) (n : Nat := 1) : List α := let len := xs.length if len ≤ 1 then xs else let n := n % len let b := xs.take n let e := xs.drop n e ++ b def rotateRight (xs : List α) (n : Nat := 1) : List α := let len := xs.length if len ≤ 1 then xs else let n := len - n % len let b := xs.take n let e := xs.drop n e ++ b end List
032c9b221f45f9a5c8dd7aaeedc77f420c978c5d
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/algebra/power_series.lean
383d09b4547ce5cc1b735076b713bf157763b457
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,197
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Given a semiring `R`, this file defines the power series semiring `R[[x]]` -/ import data.fintype data.finsupp algebra.big_operators algebra.pi_instances import data.list_extra algebra.biadditive algebra.prod_equiv algebra.convolution import tactic.squeeze tactic.pi_instances def power_series (R : Type*) := convolution.map ℕ R namespace power_series open finset variable {R : Type*} def coeff : ℕ → (power_series R) → R := λ n f, f n @[extensionality] lemma ext : ∀ {f g : power_series R}, (∀ n, coeff n f = coeff n g) → f = g := @funext _ _ instance [has_zero R] : has_zero (power_series R) := by {dsimp[power_series], apply_instance} instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by {dsimp[power_series], apply_instance} instance [semiring R] : semiring (power_series R) := by {dsimp[power_series], apply_instance} instance [comm_semiring R] : comm_semiring (power_series R) := by {dsimp[power_series], apply_instance} instance [ring R] : ring (power_series R) := by {dsimp[power_series], apply_instance} instance [comm_ring R] : comm_ring (power_series R) := by {dsimp[power_series], apply_instance} /- `C a` is the constant power series with value `a`, so the zeroth coefficient is `a` and the other coefficients are zero. -/ def C [has_zero R] : R → power_series R := convolution.map.delta instance C_hom [semiring R] : is_semiring_hom (C : R → power_series R) := { map_zero := convolution.map.delta_zero, map_one := by {dsimp[power_series,C,has_one.one,monoid.one,semiring.one],refl}, map_add := λ x y, by {dsimp[C],apply convolution.map.delta_add}, map_mul := λ x y, by {dsimp[C],symmetry,apply convolution.delta_convolve_delta}, } /- `X` denotes the standard generator of the power series semiring `R[[X]]`. -/ def X [semiring R] : power_series R := convolution.map.single (1 : ℕ) (1 : R) lemma coeff_n_zero [has_zero R] (n : ℕ) : coeff n (0 : power_series R) = (0 : R) := rfl lemma coeff_n_one [semiring R] (n : ℕ) : coeff n (1 : power_series R) = ite (0 = n) 1 0 := rfl lemma coeff_zero_one [semiring R] : coeff 0 (1 : power_series R) = 1 := rfl lemma coeff_succ_one [semiring R] (n : ℕ) : coeff (n + 1) (1 : power_series R) = 0 := rfl lemma coeff_n_C [semiring R] (n : ℕ) (a : R) : coeff n (C a) = ite (0 = n) a 0 := rfl lemma coeff_zero_C [semiring R] (a : R) : coeff 0 (C a) = a := rfl lemma coeff_succ_C [semiring R] (n : ℕ) (a : R) : coeff (n + 1) (C a) = 0 := rfl lemma coeff_n_X [semiring R] (n : ℕ) : coeff n (X : power_series R) = ite (1 = n) 1 0 := rfl lemma coeff_zero_X [semiring R] : coeff 0 (X : power_series R) = 0 := rfl lemma coeff_one_X [semiring R] : coeff 1 (X : power_series R) = 1 := rfl lemma coeff_ss_X [semiring R] (n : ℕ) : coeff (n + 2) (X : power_series R) = 0 := rfl lemma coeff_add [add_comm_monoid R] (n : ℕ) (f g : power_series R) : coeff n (f + g) = coeff n f + coeff n g := rfl instance coeff_hom [add_comm_monoid R] (n : ℕ) : is_add_monoid_hom (coeff n : power_series R → R) := { map_zero := coeff_n_zero n, map_add := coeff_add n } lemma coeff_mul [semiring R] (n : ℕ) (f g : power_series R) : coeff n (f * g) = (range n.succ).sum (λ i, (coeff i f) * (coeff (n - i) g)) := begin change convolution.convolve ((*) : R → R → R) f g n = (range n.succ).sum (λ i, (coeff i f) * (coeff (n - i) g)), dsimp[convolution.convolve,convolution.sum_set.els,coeff], let h_inj : ∀ (i₁ : ℕ) (h₁ : i₁ ∈ range n.succ) (i₂ : ℕ) (h₂ : i₂ ∈ range n.succ) (e : prod.mk i₁ (n - i₁) = prod.mk i₂ (n - i₂)), i₁ = i₂ := by { intros,injection e, }, have := @sum_image (ℕ × ℕ) R ℕ (λ x, (f x.1) * (g x.2)) _ _ (range n.succ) (λ i, prod.mk i (n - i)) h_inj, simp only [] at this ⊢, rw[← this],congr, end /- Left multiplication by `C a` is termwise left multiplication by `a` -/ lemma coeff_C_mul [semiring R] (n : ℕ) (a : R) (f : power_series R) : coeff n ((C a) * f) = a * coeff n f := begin rw[coeff_mul], let h := @sum_eq_single ℕ R _ (range (n + 1)) (λ i, coeff i (C a) * coeff (n - i) f) 0 (λ i _ h, by { simp only[], rw[coeff_n_C i a,if_neg h.symm,zero_mul], }) (λ h, by { exfalso, exact h (mem_range_succ.mpr (nat.zero_le n)) }), rw[h],simp only[],rw[coeff_n_C,if_pos rfl,nat.sub_zero], end /- Right multiplication by `C a` is termwise right multiplication by `a` -/ lemma coeff_mul_C [semiring R] (n : ℕ) (f : power_series R) (a : R) : coeff n (f * (C a)) = (coeff n f) * a := begin rw[coeff_mul], let h := @sum_eq_single ℕ R _ (range (n + 1)) (λ i, coeff i f * coeff (n - i) (C a)) n (λ i h_le h_ne, by { replace h_le : i ≤ n := mem_range_succ.mp h_le, have h_lt : i < n := lt_of_le_of_ne h_le h_ne, have : n - i ≠ 0 := λ e, not_lt_of_ge (nat.sub_eq_zero_iff_le.mp e) h_lt, simp only[], rw[coeff_n_C (n - i),if_neg this.symm,mul_zero], }) (λ h, by { exfalso, exact h (mem_range_succ.mpr (le_refl n)),}), rw[h],simp only[],rw[nat.sub_self,coeff_n_C,if_pos rfl], end lemma coeff_X_mul_zero [semiring R] (f : power_series R) : coeff 0 (X * f) = 0 := begin rw[coeff_mul,sum_range_one,coeff_n_X,if_neg (dec_trivial : 1 ≠ 0),zero_mul], end lemma coeff_X_mul_succ [semiring R] (n : ℕ) (f : power_series R) : coeff (n + 1) (X * f) = coeff n f := begin rw[coeff_mul], let h₀ := @sum_eq_single ℕ R _ (range (n + 2)) (λ i, coeff i X * coeff (n + 1 - i) f) 1 (λ i _ h, by { simp only[], rw[coeff_n_X i,if_neg h.symm,zero_mul], }) (λ h, by { have : 1 < n + 2 := nat.succ_lt_succ (nat.zero_lt_succ n), have : 1 ∈ range (n + 2) := mem_range.mpr this, exact (h this).elim}), rw[h₀],simp only[coeff_one_X],rw[one_mul],refl, end /- `E` is the homomorphism sending a power series to its constant term. -/ def E [semiring R] : (power_series R) → R := λ f, coeff 0 f lemma E_C [semiring R] (a : R) : E (C a) = a := rfl lemma E_zero [semiring R] : E (0 : power_series R) = 0 := rfl lemma E_one [semiring R] : E (1 : power_series R) = 1 := rfl lemma E_add [semiring R] (f g : power_series R) : E (f + g) = E f + E g := rfl lemma E_mul [semiring R] (f g : power_series R) : E (f * g) = (E f) * (E g) := by {dsimp[E],rw[coeff_mul,sum_range_one],} instance E_hom [semiring R] : is_semiring_hom (E : power_series R → R) := { map_zero := E_zero, map_one := E_one, map_add := E_add, map_mul := E_mul } /- `val_ge n f` means that `f` has valuation at least `n`, or in other words that `f` is divisible by `X ^ n`. -/ @[irreducible] def val_ge [has_zero R] (n : ℕ) (f : power_series R) : Prop := ∀ {i : ℕ} (hi : i < n), coeff i f = 0 lemma val_ge_zero_all [has_zero R] (f : power_series R) : val_ge 0 f := begin dsimp[val_ge],intros i hi, exact (nat.not_lt_zero i hi).elim end lemma val_ge_all_zero [has_zero R] (n : ℕ) : val_ge n (0 : power_series R) := by {dsimp[val_ge], intros i hi, refl} lemma val_ge_one_iff [has_zero R] (f : power_series R) : val_ge 1 f ↔ coeff 0 f = 0 := by { dsimp[val_ge], split, {intro h,exact h (nat.lt_succ_self 0)}, {intros h i i_lt,cases i with i,{exact h}, {exact (nat.not_lt_zero i (nat.lt_of_succ_lt_succ i_lt)).elim,}} } lemma val_ge_add [add_comm_monoid R] {n : ℕ} {f g : power_series R} : val_ge n f → val_ge n g → val_ge n (f + g) := by {dsimp[val_ge], intros hf hg i i_is_lt, show coeff i f + coeff i g = 0,rw[hf i_is_lt,hg i_is_lt,zero_add],} lemma val_ge_mul [semiring R] {n m : ℕ} {f g : power_series R} : val_ge n f → val_ge m g → val_ge (n + m) (f * g) := λ hf hg, begin dsimp[val_ge] at hf hg ⊢, intros k k_is_lt, change (convolution.sum_set.els k).sum (λ ij, (f ij.1) * (g ij.2)) = 0, have : (convolution.sum_set.els k).sum (λ ij, (0 : R)) = (0 : R) := sum_const_zero, rw[← this],apply sum_congr rfl, rintros ⟨i,j⟩ ij_sum, replace ij_sum : i + j = k := (convolution.sum_set.mem_els _ _).mp ij_sum, change (coeff i f) * (coeff j g) = 0, by_cases hi : i < n, {rw[hf hi,zero_mul],}, by_cases hj : j < m, {rw[hg hj,mul_zero],}, let hk : n + m ≤ k := ij_sum ▸ (add_le_add (le_of_not_gt hi) (le_of_not_gt hj)), exact (not_le_of_gt k_is_lt hk).elim, end lemma val_ge_pow [semiring R] {n : ℕ} {f : power_series R} (hf : val_ge n f) (k : ℕ) : val_ge (k * n) (f ^ k) := begin induction k with k ih, {rw[zero_mul],apply val_ge_zero_all}, {rw[nat.succ_eq_add_one,pow_add,pow_one,add_mul,one_mul], exact val_ge_mul ih hf, } end lemma val_ge_pow' [semiring R] {f : power_series R} (hf : coeff 0 f = 0) (k : ℕ) : val_ge k (f ^ k) := by {have := val_ge_pow ((val_ge_one_iff f).mpr hf) k, rw[mul_one] at this, exact this,} lemma val_ge_X [semiring R] : val_ge 1 (X : power_series R) := by {dsimp[val_ge,X,coeff],intros i hi, apply convolution.map.single_eq_of_ne (ne_of_lt hi).symm,} lemma coeff_X_pow [semiring R] (n i : ℕ) : coeff i ((X : power_series R) ^ n) = ite (n = i) 1 0 := begin induction n with n ih generalizing i, {rw[pow_zero,coeff_n_one]}, {rw[pow_succ],cases i with i, {rw[coeff_X_mul_zero],rw[if_neg (nat.succ_ne_zero n)],}, {rw[coeff_X_mul_succ,ih i],by_cases h : n = i, {rw[if_pos h,if_pos (congr_arg nat.succ h)]}, {have : n.succ ≠ i.succ := λ e, h (nat.succ_inj e), rw[if_neg h,if_neg this]}}} end section compose variable [comm_semiring R] /- Note: this definition is only sensible with the side condition `coeff 0 g = 0` -/ def compose (f g : power_series R) : power_series R := λ n, ((range n.succ).sum (λ j, C (coeff j f) * (g ^ j))) n lemma coeff_compose (n : ℕ) (f g : power_series R) : coeff n (compose f g) = (range n.succ).sum (λ j, (coeff j f) * (coeff n (g ^ j))) := begin haveI : is_add_monoid_hom ((coeff n) : power_series R → R) := power_series.coeff_hom n, let hh := sum_hom (coeff n : power_series R → R), have := calc coeff n (compose f g) = coeff n ((range n.succ).sum (λ j, C (coeff j f) * (g ^ j))) : rfl ... = (range n.succ).sum (λ j, coeff n (C (coeff j f) * (g ^ j))) : by {rw[← hh]}, rw[this],congr,funext j,rw[coeff_C_mul], end lemma coeff_compose_extra {n m : ℕ} (f g : power_series R) (hg : coeff 0 g = 0) (hnm : n ≤ m) : coeff n (compose f g) = (range m.succ).sum (λ j, (coeff j f) * (coeff n (g ^ j))) := begin rw[coeff_compose], have : range n.succ = (range m.succ).filter (λ i, i ≤ n) := by {ext i,rw[mem_filter,mem_range_succ,mem_range_succ],split, {intro hn,exact ⟨le_trans hn hnm,hn⟩,},{exact λ h,h.2}}, rw[this,sum_filter],congr,ext j,split_ifs with h,refl, replace h : n < j := lt_of_not_ge h, have hv := val_ge_pow' hg j, dsimp[val_ge] at hv, rw[hv h,mul_zero], end lemma zero_compose (g : power_series R) : compose 0 g = 0 := begin ext n,rw[coeff_compose,coeff_n_zero], apply sum_eq_zero_of_terms_eq_zero, intros i _,rw[coeff_n_zero,zero_mul], end /- `f ∘ g` is an additive function of `f`. -/ lemma add_compose (f₁ f₂ g : power_series R) : compose (f₁ + f₂) g = compose f₁ g + compose f₂ g := begin ext n,rw[coeff_add,coeff_compose,coeff_compose,coeff_compose], rw[← sum_add_distrib],congr,ext j, rw[coeff_add,add_mul], end /- `f ∘ g` is a multiplicative function of `f`. -/ lemma mul_compose (f₁ f₂ g : power_series R) (hg : coeff 0 g = 0): compose (f₁ * f₂) g = compose f₁ g * compose f₂ g := begin ext n, let r := range n.succ, let r2 := r.product r, let r3 := r.product r2, let r3' := r2.product r, let t₁ : (ℕ × ℕ × ℕ) → R := λ jpq, coeff jpq.2.1 f₁ * coeff jpq.2.2 f₂ * coeff jpq.1 (g ^ jpq.2.1) * coeff (n - jpq.1) (g ^ jpq.2.2), let t'₁ := λ pqj : ((ℕ × ℕ) × ℕ), t₁ ⟨pqj.2,pqj.1⟩, let inc₁ : ∀ (k : ℕ), ℕ ↪ (ℕ × ℕ) := λ k, { to_fun := λ p, ⟨p,k - p⟩, inj := λ p₁ p₂ e, congr_arg prod.fst e, }, let r2' := r.bind (λ k, (range k.succ).map (inc₁ k)), have r2_filter : r2' = r2.filter (λ pq, pq.1 + pq.2 ≤ n) := by { ext ⟨p,q⟩,rw[mem_bind,mem_filter,mem_product,mem_range_succ,mem_range_succ], simp only [],split, {rintro ⟨k,k_le,hk⟩,rcases mem_map.mp hk with ⟨p',p_le,hpq⟩, injection hpq with hp hq,rw[hp] at p_le hq, replace k_le := mem_range_succ.mp k_le, replace p_le := mem_range_succ.mp p_le, repeat {split}; apply le_trans _ k_le, {exact p_le}, {rw[← hq],apply nat.sub_le_self}, {rw[← hq,nat.add_sub_of_le p_le]} }, {rintro ⟨⟨p_le,q_le⟩,k_le⟩, use p + q,use mem_range_succ.mpr k_le, apply mem_map.mpr,use p,use mem_range_succ.mpr (nat.le_add_right p q), show prod.mk p ((p + q) - p) = prod.mk p q, congr,rw[add_comm,nat.add_sub_cancel], } }, let e₁ := calc coeff n (compose (f₁ * f₂) g) = r.sum (λ k, coeff k (f₁ * f₂) * (coeff n (g ^ k))) : by rw[coeff_compose] ... = r.sum (λ k, (range k.succ).sum (λ p, coeff p f₁ * coeff (k - p) f₂ * coeff n (g ^ k))) : by {apply sum_congr rfl,intros k k_le,rw[coeff_mul,sum_mul],} ... = r2'.sum (λ pq, coeff pq.1 f₁ * coeff pq.2 f₂ * coeff n (g ^ (pq.1 + pq.2))) : by {rw[sum_bind],apply sum_congr rfl,intros k k_le, rw[sum_map],{ apply sum_congr rfl,intros p p_le,dsimp[inc₁], replace p_le : p ≤ k := mem_range_succ.mp p_le, rw[nat.add_sub_of_le p_le], },{-- side condition for sum_map intros k₁ k₁_le k₂ k₂_le k_ne, apply eq_empty_iff_forall_not_mem.mpr,rintros ⟨p,q⟩ hpq, rw[mem_inter] at hpq, rcases mem_map.mp hpq.1 with ⟨p₁,p₁_le,hpq₁⟩,injection hpq₁ with hp₁ hq₁, rcases mem_map.mp hpq.2 with ⟨p₂,p₂_le,hpq₂⟩,injection hpq₂ with hp₂ hq₂, replace p₁_le := mem_range_succ.mp p₁_le, replace p₂_le := mem_range_succ.mp p₂_le, rw[← nat.add_sub_of_le p₁_le,← nat.add_sub_of_le p₂_le,hq₁,hq₂,hp₁,hp₂] at k_ne, exact k_ne rfl, } } ... = r2.sum (λ pq, coeff pq.1 f₁ * coeff pq.2 f₂ * coeff n (g ^ (pq.1 + pq.2))) : by { rw[r2_filter,sum_filter],apply sum_congr rfl,rintros ⟨p,q⟩ hpq, split_ifs,refl, replace h : n < p + q := lt_of_not_ge h, have := val_ge_pow' hg (p + q),dsimp[val_ge] at this,rw[this h,mul_zero], } ... = r2.sum (λ pq,r.sum (λ j, t₁ ⟨j,pq⟩)) : by {dsimp[t₁], apply finset.sum_congr rfl,rintros ⟨p,q⟩ hpq,rw[pow_add,coeff_mul,mul_sum], apply finset.sum_congr rfl,rintros j hj,repeat {rw[mul_assoc]},} ... = r3'.sum t'₁ : by {dsimp[r3'],rw[@sum_product _ _ _ _ r2 r],} ,rw[e₁],clear e₁, let e₂ := calc coeff n (compose f₁ g * compose f₂ g) = r.sum (λ j, coeff j (compose f₁ g) * coeff (n - j) (compose f₂ g)) : by rw[coeff_mul] ... = r.sum (λ j, r.sum (λ p, coeff p f₁ * coeff j (g ^ p)) * r.sum (λ q, coeff q f₂ * coeff (n - j) (g ^ q))) : by {apply sum_congr rfl,intros j j_le, replace j_le := mem_range_succ.mp j_le, rw[coeff_compose_extra f₁ g hg j_le], have : n - j ≤ n := nat.sub_le_self n j, rw[coeff_compose_extra f₂ g hg this], } ... = r.sum (λ j, r.sum (λ p, coeff p f₁ * coeff j (g ^ p) * r.sum (λ q, coeff q f₂ * coeff (n - j) (g ^ q)))) : by {apply sum_congr rfl,intros j j_le,rw[sum_mul]} ... = r.sum (λ j, r.sum (λ p, r.sum (λ q, coeff p f₁ * coeff j (g ^ p) * (coeff q f₂ * coeff (n - j) (g ^ q))))) : by {apply sum_congr rfl,intros j j_le, apply sum_congr rfl,intros k k_le,rw[mul_sum]} ... = r.sum (λ j, r.sum (λ p, r.sum (λ q, t₁ ⟨j,p,q⟩))) : by {apply sum_congr rfl,intros j j_le, apply sum_congr rfl,intros k k_le, apply sum_congr rfl,intros p p_le, rw[mul_assoc,← mul_assoc (coeff j (g ^ k)),mul_comm (coeff j (g ^ k))], rw[← mul_assoc,← mul_assoc],} ... = r.sum (λ j, r2.sum (λ pq, t₁ ⟨j,pq⟩)) : by {apply sum_congr rfl,intros j j_le,rw[sum_product],} ... = r3.sum t₁ : by rw[← sum_product], rw[e₂], clear e₂, let s := λ (jpq : ℕ × ℕ × ℕ) (h : jpq ∈ r3), prod.mk jpq.2 jpq.1, let e := @sum_bij _ _ _ _ r3 r3' t₁ t'₁ s (λ ⟨j,p,q⟩ h, by {dsimp[s],repeat {rw[mem_product] at h ⊢}, rcases h with ⟨hj,hp,hq⟩,repeat {split}; assumption,}) (λ ⟨j,p,q⟩ h, rfl) (λ ⟨j₁,p₁,q₁⟩ ⟨j₂,p₂,q₂⟩ h₁ h₂ e, by {dsimp[s] at e,injection e with epq ej,injection epq with ep eq, rw[ej,ep,eq],}) (λ ⟨⟨p,q⟩,j⟩ h, by {use ⟨j,p,q⟩,have : (⟨j,p,q⟩ : ℕ × ℕ × ℕ) ∈ r3, {repeat {rw[mem_product] at h ⊢}, rcases h with ⟨⟨hp,hq⟩,hj⟩,repeat {split}; assumption,}, use this}), exact e.symm, end lemma C_compose (a : R) (g : power_series R) : compose (C a) g = C a := begin ext n,rw[coeff_compose], let f := λ (j : ℕ), coeff j (C a) * coeff n (g ^ j), change (range n.succ).sum f = coeff n (C a), have : f 0 = coeff n (C a) := by {dsimp[f],rw[coeff_zero_C,coeff_n_one,coeff_n_C], split_ifs,rw[mul_one],rw[mul_zero]}, rw[← this],apply sum_eq_single, {intros j h_le h_ne,dsimp[f],rw[coeff_n_C,if_neg h_ne.symm,zero_mul]}, {intro h,exfalso,exact h (mem_range_succ.mpr (nat.zero_le n))} end lemma X_compose (a : R) (g : power_series R) (hg : coeff 0 g = 0) : compose X g = g := begin ext n,rw[coeff_compose], let f := λ (j : ℕ), coeff j X * coeff n (g ^ j), change (range n.succ).sum f = coeff n g, have : f 1 = coeff n g := by {dsimp[f],rw[coeff_one_X,pow_one,one_mul]}, rw[← this],apply sum_eq_single, {intros j h_le h_ne,dsimp[f],rw[coeff_n_X,if_neg h_ne.symm,zero_mul]}, {cases n with n, {intro h,rw[this],exact hg}, {intro h,exfalso, exact h (mem_range_succ.mpr (nat.succ_le_succ (nat.zero_le n))), }} end end compose end power_series
08ae30347477e41224b46a1c716c08321d95f14f
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/algebra/big_operators.lean
405e2c54bfd6001e8da23e90b938c45a7dbb08c3
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
30,770
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 Some big operators for lists and finite sets. -/ import data.list.basic data.list.perm data.finset import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive finset.sum] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod attribute [to_additive finset.sum.equations._eqn_1] finset.prod.equations._eqn_1 @[to_additive finset.sum_eq_fold] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive finset.sum_empty] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive finset.sum_insert] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive finset.sum_singleton] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive finset.sum_const_zero] prod_const_one @[simp, to_additive finset.sum_image] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive sum_map] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β): (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive finset.sum_congr] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive finset.sum_union_inter] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive finset.sum_union] lemma prod_union [decidable_eq α] (h : s₁ ∩ s₂ = ∅) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, h]; exact (mul_one _).symm @[to_additive finset.sum_sdiff] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union (sdiff_inter_self _ _), sdiff_union_of_subset h] @[to_additive finset.sum_bind] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅, from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have t x ∩ finset.bind s t = ∅, from eq_empty_of_forall_not_mem $ assume a, by rw [mem_inter, mem_bind]; rintro ⟨h₁, y, hys, hy₂⟩; exact eq_empty_iff_forall_not_mem.1 (hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hys) (assume h, hxs (h.symm ▸ hys))) _ (mem_inter_of_mem h₁ hy₂), by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive finset.sum_product] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind (λ x hx y hy h, eq_empty_of_forall_not_mem _)], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [mem_inter, mem_image], rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩, apply h, cc end @[to_additive finset.sum_sigma] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_image]; rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive finset.sum_image'] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine disjoint_iff_inter_eq_empty.1 (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive finset.sum_add_distrib] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive finset.sum_comm] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom (λ _ _, is_monoid_hom.map_mul g)) @[to_additive finset.sum_hom_rel] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive finset.sum_subset] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive sum_filter] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive finset.sum_eq_single] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive finset.sum_attach] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive finset.sum_bij] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = s.attach.prod (λx, f x.val) : prod_attach.symm ... = s.attach.prod (λx, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _ ... = (s.attach.image $ λx:{x // x ∈ s}, i x.1 x.2).prod g : (prod_image $ assume (a₁:{x // x ∈ s}) _ a₂ _ eq, subtype.eq $ i_inj a₁.1 a₂.1 a₁.2 a₂.2 eq).symm ... = t.prod g : prod_subset (by simp only [subset_iff, mem_image, mem_attach]; rintro _ ⟨⟨_, _⟩, _, rfl⟩; solve_by_elim) (assume b hb hb1, false.elim $ hb1 $ by rcases i_surj b hb with ⟨a, ha, rfl⟩; exact mem_image.2 ⟨⟨_, _⟩, mem_attach _ _, rfl⟩) @[to_additive finset.sum_bij_ne_zero] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive finset.exists_ne_zero_of_sum_ne_zero] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive finset.sum_range_succ] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive finset.sum_involution] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive finset.sum_eq_zero] lemma prod_eq_one [comm_monoid β] {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid lemma sum_hom [add_comm_monoid β] [add_comm_monoid γ] (g : β → γ) [is_add_monoid_hom g] : s.sum (λx, g (f x)) = g (s.sum f) := eq.trans (by rw is_add_monoid_hom.map_zero g; refl) (fold_hom (λ _ _, is_add_monoid_hom.map_add g)) attribute [to_additive finset.sum_hom] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive finset.sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive finset.sum_const] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive finset.sum_range_succ'] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)):= 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 [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive finset.sum_neg_distrib] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → t x ∩ t y = ∅) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section ordered_cancel_comm_monoid variables [decidable_eq α] [ordered_cancel_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma zero_le_sum (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_le_zero (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) end ordered_cancel_comm_monoid section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, image (pi.cons s a x) (pi s t) ∩ image (pi.cons s a y) (pi s t) = ∅, { assume x hx y hy h, apply eq_empty_of_forall_not_mem, simp only [mem_inter, mem_image], rintro p₁ ⟨⟨p₂, hp, eq⟩, ⟨p₃, hp₃, rfl⟩⟩, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum' : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma zero_le_sum' (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum' h) lemma sum_le_zero' (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 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) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ zero_le_sum' $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union (sdiff_inter_self _ _)).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (zero_le_sum' this), forall_mem_insert, ih this] lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, 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_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] [@decidable_rel β (≤)] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; apply filter_inter_filter_neg_eq ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_le_zero' $ 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_monoid @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ @[simp] lemma prod_range_id_eq_fact (n : ℕ) : ((range n.succ).erase 0).prod (λ x, x) = nat.fact n := calc ((range n.succ).erase 0).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, mem_erase.2 ⟨nat.succ_ne_zero _, mem_range.2 $ nat.succ_lt_succ $ by simpa using h₁⟩) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset section geom_sum open finset theorem geom_sum_mul_add [semiring α] (x : α) : ∀ (n : ℕ), ((range n).sum (λ i, (x+1)^i)) * x + 1 = (x+1)^n | 0 := by simp | (n+1) := calc (range (n + 1)).sum (λi, (x + 1) ^ i) * x + 1 = (x + 1)^n * x + (((range n).sum (λ i, (x+1)^i)) * x + 1) : by simp [range_add_one, add_mul] ... = (x + 1)^n * x + (x + 1)^n : by rw geom_sum_mul_add n ... = (x + 1) ^ (n + 1) : by simp [pow_add, mul_add] theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : ((range n).sum (λ i, x^i)) * (x-1) = x^n-1 := have _ := geom_sum_mul_add (x-1) n, by rw [sub_add_cancel] at this; rw [← this, add_sub_cancel] theorem geom_sum [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (range n).sum (λ i, x^i) = (x^n-1)/(x-1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (range n).sum (λ m, x⁻¹ ^ m) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * x⁻¹ ^ n = x⁻¹ ^ n * x, from nat.cases_on n (by simp) (λ _, by conv { to_rhs, rw [pow_succ', mul_assoc, inv_mul_cancel hx0, mul_one] }; rw [pow_succ, ← mul_assoc, mul_inv_cancel hx0, one_mul]), by rw [geom_sum h₁, div_eq_iff_mul_eq h₂, ← domain.mul_left_inj h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄] end geom_sum namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum end finset section group open list variables [group α] [group β] @[to_additive is_add_group_hom.map_sum] theorem is_group_hom.map_prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_group_hom.map_mul f, is_group_hom.map_one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive is_add_group_hom.multiset_sum] lemma is_group_hom.map_multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.map_prod f l] @[to_additive is_add_group_hom.finset_sum] lemma is_group_hom.finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.map_multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := ⟨assume a b, by simp only [λc, is_group_hom.map_mul (f c), finset.prod_mul_distrib]⟩ attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset
6333819d7edc8da2e382598282e929a197a0b23a
618003631150032a5676f229d13a079ac875ff77
/src/algebraic_geometry/prime_spectrum.lean
9d6e7eed90d50f4ae501b69278cd5304a2a68800
[ "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
13,043
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.opens import ring_theory.ideal_operations import linear_algebra.finsupp /-! # Prime spectrum of a commutative ring The prime spectrum of a commutative ring is the type of all prime ideals. It is naturally endowed with a topology: the Zariski topology. (It is also naturally endowed with a sheaf of rings, but that sheaf is not constructed in this file. It should be contributed to mathlib in future work.) ## Main definitions * `prime_spectrum R`: The prime spectrum of a commutative ring `R`, i.e., the set of all prime ideals of `R`. * `zero_locus s`: The zero locus of a subset `s` of `R` is the subset of `prime_spectrum R` consisting of all prime ideals that contain `s`. * `vanishing_ideal t`: The vanishing ideal of a subset `t` of `prime_spectrum R` is the intersection of points in `t` (viewed as prime ideals). ## Conventions We denote subsets of rings with `s`, `s'`, etc... whereas we denote subsets of prime spectra with `t`, `t'`, etc... ## Inspiration/contributors The contents of this file draw inspiration from <https://github.com/ramonfmir/lean-scheme> which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau, and Chris Hughes (on an earlier repository). -/ noncomputable theory open_locale classical universe variables u v variables (R : Type u) [comm_ring R] /-- The prime spectrum of a commutative ring `R` is the type of all prime ideal of `R`. It is naturally endowed with a topology (the Zariski topology), and a sheaf of commutative rings (not yet in mathlib). It is a fundamental building block in algebraic geometry. -/ def prime_spectrum := {I : ideal R // I.is_prime} variable {R} namespace prime_spectrum /-- A method to view a point in the prime spectrum of a commutative ring as an ideal of that ring. -/ abbreviation as_ideal (x : prime_spectrum R) : ideal R := x.val instance as_ideal.is_prime (x : prime_spectrum R) : x.as_ideal.is_prime := x.2 @[ext] lemma ext {x y : prime_spectrum R} : x = y ↔ x.as_ideal = y.as_ideal := subtype.ext /-- The zero locus of a set `s` of elements of a commutative ring `R` is the set of all prime ideals of the ring that contain the set `s`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `zero_locus s` is exactly the subset of `prime_spectrum R` where all "functions" in `s` vanish simultaneously. -/ def zero_locus (s : set R) : set (prime_spectrum R) := {x | s ⊆ x.as_ideal} @[simp] lemma mem_zero_locus (x : prime_spectrum R) (s : set R) : x ∈ zero_locus s ↔ s ⊆ x.as_ideal := iff.rfl @[simp] lemma zero_locus_span (s : set R) : zero_locus (ideal.span s : set R) = zero_locus s := by { ext x, exact (submodule.gi R R).gc s x.as_ideal } /-- The vanishing ideal of a set `t` of points of the prime spectrum of a commutative ring `R` is the intersection of all the prime ideals in the set `t`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `vanishing_ideal t` is exactly the ideal of `R` consisting of all "functions" that vanish on all of `t`. -/ def vanishing_ideal (t : set (prime_spectrum R)) : ideal R := ⨅ (x : prime_spectrum R) (h : x ∈ t), x.as_ideal lemma coe_vanishing_ideal (t : set (prime_spectrum R)) : (vanishing_ideal t : set R) = {f : R | ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal} := begin ext f, rw [vanishing_ideal, submodule.mem_coe, submodule.mem_infi], apply forall_congr, intro x, rw [submodule.mem_infi], end lemma mem_vanishing_ideal (t : set (prime_spectrum R)) (f : R) : f ∈ vanishing_ideal t ↔ ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal := by rw [← submodule.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq] lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (prime_spectrum R)) (I : ideal R) : t ⊆ zero_locus I ↔ I ≤ vanishing_ideal t := begin split; intro h, { intros f hf, rw [mem_vanishing_ideal], intros x hx, have hxI := h hx, rw mem_zero_locus at hxI, exact hxI hf }, { intros x hx, rw mem_zero_locus, refine le_trans h _, intros f hf, rw [mem_vanishing_ideal] at hf, exact hf x hx } end section gc variable (R) /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc : @galois_connection (ideal R) (order_dual (set (prime_spectrum R))) _ _ (λ I, zero_locus I) (λ t, vanishing_ideal t) := λ I t, subset_zero_locus_iff_le_vanishing_ideal t I /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_set : @galois_connection (set R) (order_dual (set (prime_spectrum R))) _ _ (λ s, zero_locus s) (λ t, vanishing_ideal t) := have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi R R).gc, by simpa [zero_locus_span, function.comp] using galois_connection.compose _ _ _ _ ideal_gc (gc R) lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (prime_spectrum R)) (s : set R) : t ⊆ zero_locus s ↔ s ⊆ vanishing_ideal t := (gc_set R) s t end gc -- TODO: we actually get the radical ideal, -- but I think that isn't in mathlib yet. lemma subset_vanishing_ideal_zero_locus (s : set R) : s ⊆ vanishing_ideal (zero_locus s) := (gc_set R).le_u_l s lemma le_vanishing_ideal_zero_locus (I : ideal R) : I ≤ vanishing_ideal (zero_locus I) := (gc R).le_u_l I lemma subset_zero_locus_vanishing_ideal (t : set (prime_spectrum R)) : t ⊆ zero_locus (vanishing_ideal t) := (gc R).l_u_le t lemma zero_locus_bot : zero_locus ((⊥ : ideal R) : set R) = set.univ := (gc R).l_bot @[simp] lemma zero_locus_singleton_zero : zero_locus ({0} : set R) = set.univ := zero_locus_bot @[simp] lemma zero_locus_empty : zero_locus (∅ : set R) = set.univ := (gc_set R).l_bot @[simp] lemma vanishing_ideal_univ : vanishing_ideal (∅ : set (prime_spectrum R)) = ⊤ := by simpa using (gc R).u_top lemma zero_locus_empty_of_one_mem {s : set R} (h : (1:R) ∈ s) : zero_locus s = ∅ := begin rw set.eq_empty_iff_forall_not_mem, intros x hx, rw mem_zero_locus at hx, have x_prime : x.as_ideal.is_prime := by apply_instance, have eq_top : x.as_ideal = ⊤, { rw ideal.eq_top_iff_one, exact hx h }, apply x_prime.1 eq_top, end lemma zero_locus_empty_iff_eq_top {I : ideal R} : zero_locus (I : set R) = ∅ ↔ I = ⊤ := begin split, { contrapose!, intro h, apply set.ne_empty_iff_nonempty.mpr, rcases ideal.exists_le_maximal I h with ⟨M, hM, hIM⟩, exact ⟨⟨M, hM.is_prime⟩, hIM⟩ }, { rintro rfl, apply zero_locus_empty_of_one_mem, trivial } end @[simp] lemma zero_locus_univ : zero_locus (set.univ : set R) = ∅ := zero_locus_empty_of_one_mem (set.mem_univ 1) lemma zero_locus_sup (I J : ideal R) : zero_locus ((I ⊔ J : ideal R) : set R) = zero_locus I ∩ zero_locus J := (gc R).l_sup lemma zero_locus_union (s s' : set R) : zero_locus (s ∪ s') = zero_locus s ∩ zero_locus s' := (gc_set R).l_sup lemma vanishing_ideal_union (t t' : set (prime_spectrum R)) : vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' := (gc R).u_inf lemma zero_locus_supr {ι : Sort*} (I : ι → ideal R) : zero_locus ((⨆ i, I i : ideal R) : set R) = (⋂ i, zero_locus (I i)) := (gc R).l_supr lemma zero_locus_Union {ι : Sort*} (s : ι → set R) : zero_locus (⋃ i, s i) = (⋂ i, zero_locus (s i)) := (gc_set R).l_supr lemma vanishing_ideal_Union {ι : Sort*} (t : ι → set (prime_spectrum R)) : vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) := (gc R).u_infi lemma zero_locus_inf (I J : ideal R) : zero_locus ((I ⊓ J : ideal R) : set R) = zero_locus I ∪ zero_locus J := begin ext x, split, { rintro h, rw set.mem_union, simp only [mem_zero_locus] at h ⊢, -- TODO: The rest of this proof should be factored out. rw classical.or_iff_not_imp_right, intros hs r hr, rw set.not_subset at hs, rcases hs with ⟨s, hs1, hs2⟩, apply (ideal.is_prime.mem_or_mem (by apply_instance) _).resolve_left hs2, apply h, split, { exact ideal.mul_mem_left _ hr }, { exact ideal.mul_mem_right _ hs1 } }, { rintro (h|h), all_goals { rw mem_zero_locus at h ⊢, refine set.subset.trans _ h, intros r hr, cases hr, assumption } } end lemma union_zero_locus (s s' : set R) : zero_locus s ∪ zero_locus s' = zero_locus ((ideal.span s) ⊓ (ideal.span s') : ideal R) := by { rw zero_locus_inf, simp } lemma sup_vanishing_ideal_le (t t' : set (prime_spectrum R)) : vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') := begin intros r, rw [submodule.mem_sup, mem_vanishing_ideal], rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩, rw mem_vanishing_ideal at hf hg, apply submodule.add_mem; solve_by_elim end /-- The Zariski topology on the prime spectrum of a commutative ring is defined via the closed sets of the topology: they are exactly those sets that are the zero locus of a subset of the ring. -/ instance zariski_topology : topological_space (prime_spectrum R) := topological_space.of_closed (set.range prime_spectrum.zero_locus) (⟨set.univ, by simp⟩) begin intros Zs h, rw set.sInter_eq_Inter, let f : Zs → set R := λ i, classical.some (h i.2), have hf : ∀ i : Zs, i.1 = zero_locus (f i) := λ i, (classical.some_spec (h i.2)).symm, simp only [hf], exact ⟨_, zero_locus_Union _⟩ end (by { rintro _ _ ⟨s, rfl⟩ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus s t).symm⟩ }) lemma is_open_iff (U : set (prime_spectrum R)) : is_open U ↔ ∃ s, -U = zero_locus s := by simp only [@eq_comm _ (-U)]; refl lemma is_closed_iff_zero_locus (Z : set (prime_spectrum R)) : is_closed Z ↔ ∃ s, Z = zero_locus s := by rw [is_closed, is_open_iff, set.compl_compl] lemma is_closed_zero_locus (s : set R) : is_closed (zero_locus s) := by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ } section comap variables {S : Type v} [comm_ring S] {S' : Type*} [comm_ring S'] /-- The function between prime spectra of commutative rings induced by a ring homomorphism. This function is continuous. -/ def comap (f : R →+* S) : prime_spectrum S → prime_spectrum R := λ y, ⟨ideal.comap f y.as_ideal, by exact ideal.is_prime.comap _⟩ variables (f : R →+* S) @[simp] lemma comap_as_ideal (y : prime_spectrum S) : (comap f y).as_ideal = ideal.comap f y.as_ideal := rfl @[simp] lemma comap_id : comap (ring_hom.id R) = id := funext $ λ x, ext.mpr $ by { rw [comap_as_ideal], apply ideal.ext, intros r, simp } @[simp] lemma comap_comp (f : R →+* S) (g : S →+* S') : comap (g.comp f) = comap f ∘ comap g := funext $ λ x, ext.mpr $ by { simp, refl } @[simp] lemma preimage_comap_zero_locus (s : set R) : (comap f) ⁻¹' (zero_locus s) = zero_locus (f '' s) := begin ext x, simp only [mem_zero_locus, set.mem_preimage, comap_as_ideal, set.image_subset_iff], refl end lemma comap_continuous (f : R →+* S) : continuous (comap f) := begin rw continuous_iff_is_closed, simp only [is_closed_iff_zero_locus], rintro _ ⟨s, rfl⟩, exact ⟨_, preimage_comap_zero_locus f s⟩ end end comap lemma zero_locus_vanishing_ideal_eq_closure (t : set (prime_spectrum R)) : zero_locus (vanishing_ideal t : set R) = closure t := begin apply set.subset.antisymm, { rintro x hx t' ⟨ht', ht⟩, obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus s, by rwa [is_closed_iff_zero_locus] at ht', rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht, calc fs ⊆ vanishing_ideal t : ht ... ⊆ x.as_ideal : hx }, { rw closure_subset_iff_subset_of_is_closed (is_closed_zero_locus _), exact subset_zero_locus_vanishing_ideal t } end /-- The prime spectrum of a commutative ring is a compact topological space. -/ instance : compact_space (prime_spectrum R) := begin apply compact_space_of_finite_subfamily_closed, intros ι Z hZc hZ, let I : ι → ideal R := λ i, vanishing_ideal (Z i), have hI : ∀ i, Z i = zero_locus (I i), { intro i, rw [zero_locus_vanishing_ideal_eq_closure, closure_eq_of_is_closed], exact hZc i }, have one_mem : (1:R) ∈ ⨆ (i : ι), I i, { rw [← ideal.eq_top_iff_one, ← zero_locus_empty_iff_eq_top, zero_locus_supr], simpa only [hI] using hZ }, obtain ⟨s, hs⟩ : ∃ s : finset ι, (1:R) ∈ ⨆ i ∈ s, I i := submodule.exists_finset_of_mem_supr I one_mem, show ∃ t : finset ι, (⋂ i ∈ t, Z i) = ∅, use s, rw [← ideal.eq_top_iff_one, ←zero_locus_empty_iff_eq_top] at hs, simpa only [zero_locus_supr, hI] using hs end end prime_spectrum
61667fbc67ce9e2ac4b803da613ceef76ab40ea1
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta.lean
b1cadcec89a4091fc59aa48b29d46a701e57d02d
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,052
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.Meta.Basic import Lean.Meta.LevelDefEq import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.ExprDefEq import Lean.Meta.DiscrTree import Lean.Meta.Reduce import Lean.Meta.Instances import Lean.Meta.AbstractMVars import Lean.Meta.SynthInstance import Lean.Meta.AppBuilder import Lean.Meta.Tactic import Lean.Meta.KAbstract import Lean.Meta.RecursorInfo import Lean.Meta.GeneralizeTelescope import Lean.Meta.Match import Lean.Meta.ReduceEval import Lean.Meta.Closure import Lean.Meta.AbstractNestedProofs import Lean.Meta.ForEachExpr import Lean.Meta.Transform import Lean.Meta.PPGoal import Lean.Meta.UnificationHint import Lean.Meta.Inductive import Lean.Meta.SizeOf import Lean.Meta.IndPredBelow import Lean.Meta.Coe import Lean.Meta.SortLocalDecls import Lean.Meta.CollectFVars import Lean.Meta.GeneralizeVars import Lean.Meta.Injective
6bc70f898040e45eda17bba5cc3ded38b5a02944
274748215b6d042f0d9c9a505f9551fa8e0c5f38
/src/for_mathlib/ring_theory/algebra.lean
be2cd104a6814747ea54e94da5b4c2a33ac653a4
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M4P33
878ecb515c77d20cc799ff1ebd78f1bf4fd65c12
1a179372db71ad6802d11eacbc1f02f327d55f8f
refs/heads/master
1,607,519,867,193
1,583,344,297,000
1,583,344,297,000
233,316,107
59
4
Apache-2.0
1,579,285,778,000
1,578,788,367,000
Lean
UTF-8
Lean
false
false
4,212
lean
import ring_theory.algebra namespace mv_polynomial /-- evaluation of a polynomial over R in an R-algebra is an R-algebra morphism-/ noncomputable def alg_eval {R : Type*} [comm_ring R] {A : Type*} [comm_ring A] [algebra R A] {σ : Type*} (f : σ → A) : mv_polynomial σ R →ₐ[R] A := { commutes' := λ _, eval₂_C _ _ _, ..ring_hom.of (eval₂ (algebra_map A : R → A) f) } /-- An R-algebra homomorphism f : R[X_1, X_2, ...] → A is determined by the evaluations f(X_1), f(X_2), ... -/ @[simp] lemma alg_eval_hom_X {R : Type*} [comm_ring R] {A : Type*} [comm_ring A] [algebra R A] {σ : Type*} --{σ : Type*} (c : ℤ → β) [is_ring_hom c] (f : mv_polynomial σ R →ₐ[R] A) (x : mv_polynomial σ R) : eval₂ (algebra_map A) (f ∘ X) x = f x := mv_polynomial.induction_on x (λ r, by rw eval₂_C; exact (f.commutes r).symm) (λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (is_ring_hom.map_add f).symm }) (λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (is_ring_hom.map_mul f).symm }) /-- If A is an R-algebra, then to give an R-algebra homomorphism f : R[X_i : i ∈ σ] → A is to give a map σ → A -/ noncomputable def alg_hom_equiv {R : Type*} [comm_ring R] {A : Type*} [comm_ring A] [algebra R A] {σ : Type} : (mv_polynomial σ R →ₐ[R] A) ≃ (σ → A) := { to_fun := λ f, ⇑f ∘ X, inv_fun := alg_eval, left_inv := λ _, alg_hom.ext $ alg_eval_hom_X _, right_inv := λ _, funext $ λ _, eval₂_X _ _ _, } end mv_polynomial -- quotients namespace alg_hom open function theorem ext_iff {R : Type*} [comm_ring R] {A : Type*} [comm_ring A] [algebra R A] {B : Type*} [comm_ring B] [algebra R B] (φ ψ : A →ₐ[R] B) : φ = ψ ↔ ∀ a : A, φ a = ψ a := ⟨λ h a, by rw h, alg_hom.ext⟩ noncomputable def quot.lift {R : Type*} [comm_ring R] {A : Type*} [comm_ring A] [algebra R A] {B : Type*} [comm_ring B] [algebra R B] {C : Type*} [comm_ring C] [algebra R C] (f : A →ₐ[R] B) (hf : surjective f) (g : A →ₐ[R] C) (hfg : ∀ a : A, f a = 0 → g a = 0) : B →ₐ[R] C := { to_fun := λ b, g (classical.some (hf b)), map_one' := begin change _ = (1 : C), rw [←g.map_one, ←sub_eq_zero_iff_eq, ←g.map_sub], apply hfg, rw [f.map_sub, sub_eq_zero_iff_eq, f.map_one], exact classical.some_spec (hf 1), end, map_mul' := begin intros b₁ b₂, show _ = _ * _, rw [←g.map_mul, ←sub_eq_zero_iff_eq, ←g.map_sub], apply hfg, rw [f.map_sub, sub_eq_zero_iff_eq, f.map_mul], rw [classical.some_spec (hf b₁), classical.some_spec (hf b₂)], exact classical.some_spec (hf (b₁ * b₂)) end, map_zero' := begin change _ = (0 : C), apply hfg, exact classical.some_spec (hf 0), end, map_add' := begin intros b₁ b₂, show _ = _ + _, rw [←g.map_add, ←sub_eq_zero_iff_eq, ←g.map_sub], apply hfg, rw [f.map_sub, sub_eq_zero_iff_eq, f.map_add], rw [classical.some_spec (hf b₁), classical.some_spec (hf b₂)], exact classical.some_spec (hf (b₁ + b₂)) end, commutes' := begin intros r, rw [←g.commutes, ←sub_eq_zero_iff_eq, ←g.map_sub], apply hfg, rw [f.map_sub, sub_eq_zero_iff_eq, f.commutes, classical.some_spec (hf (algebra_map B r))] end } theorem quot.thm {R : Type*} [comm_ring R] {A : Type*} [comm_ring A] [algebra R A] {B : Type*} [comm_ring B] [algebra R B] {C : Type*} [comm_ring C] [algebra R C] (f : A →ₐ[R] B) (hf : surjective f) (g : A →ₐ[R] C) (hfg : ∀ a : A, f a = 0 → g a = 0) : alg_hom.comp (quot.lift f hf g hfg) f = g := begin ext a, show g _ = g a, rw [←sub_eq_zero_iff_eq, ←g.map_sub], apply hfg, rw [f.map_sub, sub_eq_zero_iff_eq], exact classical.some_spec (hf _), end theorem quot.thm' {R : Type*} [comm_ring R] {A : Type*} [comm_ring A] [algebra R A] {B : Type*} [comm_ring B] [algebra R B] {C : Type*} [comm_ring C] [algebra R C] (f : A →ₐ[R] B) (hf : surjective f) (g : A →ₐ[R] C) (hfg : ∀ a : A, f a = 0 → g a = 0) (a : A) : (quot.lift f hf g hfg) (f a) = g a := begin have xxx := quot.thm f hf g hfg, rw alg_hom.ext_iff at xxx, exact xxx a, end end alg_hom
cf01d4a1ab686f5975dd335923ffadc96f340bbd
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/issue136.lean
5ae51caf9bb9287fd5fb1bd4f94b6398c8a7a50a
[ "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
185
lean
meta def tactic.interactive.test (a : interactive.parse (lean.parser.of_tactic (@tactic.fail ℕ _ _ "oh no"))) := tactic.skip example : true := begin test end -- should be "oh no"
24406801ce8dcfbaf3c3d32ca66db5bb8c9ff9d5
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/functor.lean
cb845e9f9bcae60942fde26f003af825bae842bc
[ "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
492
lean
/- Copyright (c) Luke Nelson and Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson and Jared Roesch -/ prelude universe variables u v structure [class] functor (F : Type u → Type v) : Type (max u+1 v) := (map : Π {A B : Type u}, (A → B) → F A → F B) attribute [inline] definition fmap {F : Type u → Type v} [functor F] {A B : Type u} : (A → B) → F A → F B := functor.map infixr ` <$> `:100 := fmap
872321ea9134f4c66e1dd15c985d53f634d7affd
32317185abf7e7c963f4c67c190aec61af6b3628
/tests/lean/run/inj_tac.lean
6d6bdb19e198faa8fb9016a87dcdc4de43f685ac
[ "Apache-2.0" ]
permissive
Andrew-Zipperer-unorganized/lean
198a2317f21198cd8d26e7085e484b86277f17f7
dcb35008e1474a0abebe632b1dced120e5f8c009
refs/heads/master
1,622,526,520,945
1,453,576,559,000
1,454,612,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,252
lean
import data.examples.vector open nat vector example (a b : nat) : succ a = succ b → a + 2 = b + 2 := begin intro H, injection H with aeqb, rewrite aeqb end example (A : Type) (n : nat) (v w : vector A n) (a : A) (b : A) : a :: v = a :: w → b :: v = b :: w := begin intro H, injection H with veqw, rewrite veqw end example (A : Type) (n : nat) (v w : vector A n) (a : A) (b : A) : a :: v = b :: w → b :: v = a :: w := begin intro H, injection H with aeqb veqw, rewrite [aeqb, veqw] end example (A : Type) (a₁ a₂ a₃ b₁ b₂ b₃ : A) : (a₁, a₂, a₃) = (b₁, b₂, b₃) → b₁ = a₁ := begin intro H, injection H with a₁b₁ a₂b₂ a₃b₃, rewrite a₁b₁ end example (A : Type) (a₁ a₂ a₃ b₁ b₂ b₃ : A) : (a₁ :: [], a₂, a₃) = (b₁ :: [], b₂, b₃) → b₁ = a₁ := begin intro H, injection H with a₁b₁ a₂b₂ a₃b₃, rewrite a₁b₁ end example (a₁ a₂ a₃ b₁ b₂ b₃ : nat) : (a₁+2, a₂+3, a₃+1) = (b₁+2, b₂+2, b₃+2) → b₁ = a₁ ∧ a₃ = b₃+1 ∧ b₂ = succ a₂ := begin intro H, injection H with a₁b₁ sa₂b₂ a₃sb₃, esimp at *, rewrite [a₁b₁, a₃sb₃, sa₂b₂], repeat (split | esimp) end
14be02c3e26d97e95c7cd10e812630ca4a832cf5
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Parser/Level.lean
eb0cb484524750e56167a2a7db4e4120e288d10a
[ "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,116
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, Sebastian Ullrich -/ import Lean.Parser.Extension -- necessary for auto-generation import Lean.PrettyPrinter.Parenthesizer import Lean.PrettyPrinter.Formatter namespace Lean namespace Parser @[init] def regBuiltinLevelParserAttr : IO Unit := registerBuiltinParserAttribute `builtinLevelParser `level @[inline] def levelParser (rbp : Nat := 0) : Parser := categoryParser `level rbp namespace Level @[builtinLevelParser] def paren := parser! "(" >> levelParser >> ")" @[builtinLevelParser] def max := parser! nonReservedSymbol "max " true >> many1 (levelParser maxPrec) @[builtinLevelParser] def imax := parser! nonReservedSymbol "imax " true >> many1 (levelParser maxPrec) @[builtinLevelParser] def hole := parser! "_" @[builtinLevelParser] def num := checkPrec maxPrec >> numLit @[builtinLevelParser] def ident := checkPrec maxPrec >> ident @[builtinLevelParser] def addLit := tparser!:65 "+" >> numLit end Level end Parser end Lean
e05bf207369d0925ae137fc8d907a5d3dde4c4fb
f57570f33b51ef0271f8c366142363d5ae8fff45
/src/native_logic.lean
e4396abcde976bdc40a9e10220c9570e2f9984be
[]
no_license
maxd13/lean-logic
4083cb3fbb45b423befca7fda7268b8ba85ff3a6
ddcab46b77adca91b120a5f37afbd48794da8b52
refs/heads/master
1,692,257,681,488
1,631,740,832,000
1,631,740,832,000
246,324,437
0
0
null
null
null
null
UTF-8
Lean
false
false
16,399
lean
import tactic.find tactic.tidy data.set.basic universes u v namespace metalogic open tactic set inductive HProp : Type | intro (p : Prop) : HProp def is_true : HProp → Prop | (HProp.intro p) := p -- inductive andH : HProp → HProp -- | intro (p : HProp) : andH p inductive provable.prop.classical : set (Sort u) → (Sort u) → (Sort (max (u+1) v)) | reflexive {Γ : set (Sort u)} {φ : (Sort u)} (h : φ ∈ Γ) : provable.prop.classical Γ φ | transitivity {Γ Δ : set (Sort u)} {φ : (Sort u)} (h₁ : ∀ ψ ∈ Δ, provable.prop.classical Γ ψ) (h₂ : provable.prop.classical Δ φ) : provable.prop.classical Γ φ | modus_ponens (φ ψ : (Sort u)) (Γ : set (Sort u)) (h₁ : provable.prop.classical Γ (φ → ψ)) (h₂ : provable.prop.classical Γ φ) : provable.prop.classical Γ ψ | intro {φ ψ : (Sort u)} {Γ : set (Sort u)} (h : provable.prop.classical (Γ ∪ {φ}) ψ) : provable.prop.classical Γ (φ → ψ) -- | exfalso -- (φ : (Sort u)) (Γ : set (Sort u)) -- (h : provable.prop.classical Γ ) -- : provable.prop.classical Γ φ -- | by_contradiction (φ : (Sort u)) (Γ : set (Sort u)) -- (h : provable.prop.classical Γ ¬¬φ) -- : provable.prop.classical Γ φ variables {Γ : set Prop} {φ : Prop} #check provable.prop.classical.{0} example : φ → provable.prop.classical.{0} Γ φ := begin intro h, have c₁ : φ = true, simp [h], have c₂ : (φ → φ) = true, simp, rw [c₁,←c₂], apply provable.prop.classical.intro, apply provable.prop.classical.reflexive, simp, end -- example : φ → provable.prop.classical.{1} ∅ (provable.prop.classical.{0} Γ φ) := -- begin -- end -- We wanted to define what a tautology is in order -- to define a necessitation rule for normal modal logics -- in terms of this notion of tautology. -- However our approach did not work. -- For this approach to work the defined proof system -- would have to be incomplete relative to provability -- or "truth" in LEAN. However we were able to prove -- that given a proof of proposition φ we can build -- a proof of proposition provable.minimal Γ φ -- for any set Γ of propositions. inductive provable.minimal : set Prop → Prop → Prop | reflexive (Γ : set Prop) (φ : Prop) (h : set.mem φ Γ) : provable.minimal Γ φ | transitivity (Γ Δ : set Prop) (φ : Prop) (h₁ : ∀ ψ ∈ Δ, provable.minimal Γ ψ) (h₂ : provable.minimal Δ φ) : provable.minimal Γ φ | and_intro (φ ψ : Prop) (Γ : set Prop) (h₁ : provable.minimal Γ φ) (h₂ : provable.minimal Γ ψ) : provable.minimal Γ (φ ∧ ψ) | and_elim_left (φ ψ : Prop) (Γ : set Prop) (h : provable.minimal Γ (φ ∧ ψ)) : provable.minimal Γ φ | and_elim_right (φ ψ : Prop) (Γ : set Prop) (h : provable.minimal Γ (φ ∧ ψ)) : provable.minimal Γ ψ | or_intro_left (φ ψ : Prop) (Γ : set Prop) (h : provable.minimal Γ φ) : provable.minimal Γ (φ ∨ ψ) | or_intro_right (φ ψ : Prop) (Γ : set Prop) (h : provable.minimal Γ ψ) : provable.minimal Γ (φ ∨ ψ) | or_elim (φ ψ δ : Prop) (Γ : set Prop) (h₁ : provable.minimal Γ (φ ∨ ψ)) (h₂ : provable.minimal Γ (φ → δ)) (h₃ : provable.minimal Γ (ψ → δ)) : provable.minimal Γ δ | modus_ponens (φ ψ : Prop) (Γ : set Prop) (h₁ : provable.minimal Γ (φ → ψ)) (h₂ : provable.minimal Γ φ) : provable.minimal Γ ψ | intro (φ ψ : Prop) (Γ : set Prop) (h : provable.minimal (Γ ∪ {φ}) ψ) : provable.minimal Γ (φ → ψ) | true_intro (Γ : set Prop) : provable.minimal Γ true | for_all_intro {α : Type u} (Γ : set Prop) (p : α → Prop) (h : ∀ x : α, provable.minimal Γ (p x)) : provable.minimal Γ (∀ x:α, p x) | for_all_elim {α : Type u} (Γ : set Prop) (p : α → Prop) (c : α) (h : provable.minimal Γ (∀ x : α, p x)) : provable.minimal Γ (p c) | exists_intro {α : Type u} (Γ : set Prop) (p : α → Prop) (c : α) (h : provable.minimal Γ (p c)) : provable.minimal Γ (∃x:α, p x) | exists_elim {α : Type u} (Γ : set Prop) (p : α → Prop) (ψ : Prop) (h₁ : provable.minimal Γ (∃x:α, p x)) (h₂ : ∀ x:α, provable.minimal Γ (p x → ψ)) : provable.minimal Γ ψ | identity_intro {α : Type u} (Γ : set Prop) (c : α) : provable.minimal Γ (c = c) | identity_elim {α : Type u} (Γ : set Prop) (p : α → Prop) (c₁ c₂: α) (h : provable.minimal Γ (p c₁)) (eq : provable.minimal Γ (c₁ = c₂)) : provable.minimal Γ (p c₂) -- variables {Γ : set Prop} {φ : Prop} example : provable.minimal.{u} Γ (φ → φ) := begin apply provable.minimal.intro, apply provable.minimal.reflexive (Γ∪{φ} : set Prop) φ, right, -- this would be needed if we forgot the .{u} -- apply singleton_subset_iff.mp, simp, end -- here is the proof why this approach doesn't quite work: theorem completeness.minimal : φ → minimal Γ φ := begin intro h₁, have c₁ := classical.eq_true_or_eq_false φ, cases c₁, rw c₁, apply provable.minimal.true_intro Γ, simp at c₁, contradiction, end -- it doesn't help to remove the true_intro rule -- because it can be proven using the same logic: -- (1) prove that Γ proves false → false, -- (2) simplify false → false to true, -- (3) conclude that Γ proves true -- and it gets worse than that: def complete.minimal (Γ : set Prop) := ∀ φ : Prop, provable.minimal.{u} Γ φ ∨ provable.minimal.{u} Γ (¬φ) theorem universal_decidibility.minimal : complete.minimal Γ := begin intro φ, classical, by_cases φ, left, apply completeness.minimal, assumption, right, apply completeness.minimal, assumption, end -- It might have worked out if we refrained -- from using classical logic, but there isn't a -- clear requirement that we refrain from it. -- Even if we do another user of this module might use it, -- and he might prove the same result we did above. -- There is no way to keep tabs on where classical -- reasoning is being used. -- It would be more useful if whenever we used -- classical logic, we had to add a tag -- to the theorem or definition name, like "meta" -- or "noncomputable" are already in use. -- Which is pretty sad because I made all these nice -- other proofs: theorem provable.minimal.monotonicity : ∀ (Δ ⊆ Γ) (ψ : Prop), provable.minimal.{u} Δ ψ → provable.minimal.{u} Γ ψ := begin intros Δ H ψ h, -- induction on the possible ways in which -- Δ could prove ψ induction h, -- case it was proven by reflection apply provable.minimal.reflexive Γ h_φ, exact H h_h, -- case it was proven by transitivity apply provable.minimal.transitivity Γ h_Δ h_φ, intros ψ₂ elem, repeat {assumption <|> apply_assumption}, -- case it was proven by and_intro apply provable.minimal.and_intro,-- h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by and_elim_left apply provable.minimal.and_elim_left h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by and_elim_right apply provable.minimal.and_elim_right h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by or_intro_left apply provable.minimal.or_intro_left h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by or_intro_right apply provable.minimal.or_intro_right h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by or_elim apply provable.minimal.or_elim,-- h_φ h_ψ h_δ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by modus ponens apply provable.minimal.modus_ponens h_φ h_ψ Γ, repeat {assumption <|> apply_assumption}, -- case it was proven by intro have c : provable.minimal h_Γ (h_φ → h_ψ), apply provable.minimal.intro h_φ h_ψ h_Γ, assumption, apply provable.minimal.transitivity Γ h_Γ (h_φ → h_ψ), intros ψ₂ elem, have c₂ := H elem, exact provable.minimal.reflexive Γ ψ₂ c₂, assumption, -- case it was proven by true_intro exact provable.minimal.true_intro Γ, -- case it was proven by for_all_intro apply provable.minimal.for_all_intro, intro x, have c := h_ih x, repeat {assumption <|> apply_assumption}, -- case it was proven by for_all_elim apply provable.minimal.for_all_elim, repeat {assumption <|> apply_assumption}, -- case it was proven by exists_intro apply provable.minimal.exists_intro, repeat {assumption <|> apply_assumption}, -- case it was proven by exists_elim have c : minimal h_Γ h_ψ, apply provable.minimal.exists_elim h_Γ h_p h_ψ, repeat {assumption <|> apply_assumption}, apply provable.minimal.exists_elim Γ h_p h_ψ, repeat {assumption <|> apply_assumption}, intro x, repeat {assumption <|> apply_assumption}, -- case it was proven by identity_intro apply provable.minimal.identity_intro, -- case it was proven by identity_elim apply provable.minimal.identity_elim, repeat {assumption <|> apply_assumption}, end -- prove that minimal logic is sound relative to LEAN -- semantics. theorem provable.minimal.sound : provable.minimal Γ φ → (∀ ψ ∈ Γ, ψ) → φ := begin intros h₀ h₁, induction h₀, -- case it was proven by reflection apply_assumption, assumption, -- case it was proven by transitivity apply h₀_ih_h₂, intros ψ elem, have c := h₀_ih_h₁ ψ elem, exact c h₁, -- case it was proven by and_intro constructor; apply_assumption; assumption, -- case it was proven by and_elim_left exact (h₀_ih h₁).1, -- case it was proven by and_elim_right exact (h₀_ih h₁).2, -- case it was proven by or_intro_left left, apply_assumption, assumption, -- case it was proven by or_intro_right right, apply_assumption, assumption, -- case it was proven by or_elim cases h₀_ih_h₁ h₁ with h, exact h₀_ih_h₂ h₁ h, exact h₀_ih_h₃ h₁ h, -- case it was proven by modus ponens apply h₀_ih_h₁ h₁, apply_assumption, assumption, -- case it was proven by intro have c : (∀ (ψ : Prop), ψ ∈ h₀_Γ ∪ {h₀_φ} → ψ), intros ψ elem, cases elem, exact h₀_h₁ ψ elem, simp at elem, exact elem.2 a, apply_assumption, assumption, -- case it was proven by true_intro exact true.intro, -- case it was proven by for_all_intro have c := h₀_ih x, apply_assumption, assumption, -- case it was proven by for_all_elim exact h₀_ih h₁ h₀_c, -- case it was proven by exists_intro existsi h₀_c, apply_assumption, assumption, -- case it was proven by exists_elim obtain ⟨x, p⟩ := h₀_ih_h₁ h₁, have c := h₀_ih_h₂ x, exact c h₁ p, -- case it was proven by identity_intro refl, -- case it was proven by identity_elim have c := h₀_ih_h h₁, rwa h₀_ih_eq h₁ at c, end lemma provable.minimal.cond : provable.minimal.{u} Γ φ → ∀ ψ : Prop, provable.minimal.{u} Γ (ψ → φ) := begin intros h ψ, apply provable.minimal.intro, apply provable.minimal.monotonicity Γ, simp, assumption, end def tautology.minimal (φ : Prop) : Prop := provable.minimal ∅ φ def consistent.minimal (Γ : set Prop) := ¬ ∀ φ : Prop, provable.minimal.{u} Γ φ inductive provable.constructive : set Prop → Prop → Prop | minimal (Γ : set Prop) (φ : Prop) (h : provable.minimal Γ φ) : provable.constructive Γ φ | quodlibet (Γ : set Prop) (φ : Prop) : provable.constructive Γ (false → φ) theorem provable.constructive.sound : provable.constructive Γ φ → (∀ ψ ∈ Γ, ψ) → φ := begin intros h₀ h₁, induction h₀, exact provable.minimal.sound h₀_h h₁, contradiction, end -- lemma provable.constructive.cond : provable.constructive.{u} Γ φ → ∀ ψ : Prop, provable.constructive.{u} Γ (ψ → φ) := -- begin -- intros h ψ, -- cases h, -- end -- lemma provable.constructive.intro : ∀ φ ψ : Prop, -- (provable.constructive.{u} (Γ ∪ {φ}) ψ) -- → provable.constructive.{u} Γ (φ → ψ) := -- begin -- intros φ ψ h, -- rcases h with h₁| h₂, -- apply provable.constructive.minimal, -- apply provable.minimal.intro, -- have c : ((Γ ∪ {φ}) : set Prop) = λ (a : Prop), a ∈ Γ ∨ a ∈ ({φ}:set Prop), -- trivial, -- rwa c, -- simp, -- end def tautology.constructive (φ : Prop) : Prop := provable.constructive ∅ φ inductive provable.classical : set Prop → Prop → Prop | constructive (Γ : set Prop) (φ : Prop) (h : provable.constructive Γ φ) : provable.classical Γ φ | by_contradiction (Γ : set Prop) (φ : Prop) (h : provable.classical Γ (¬φ → false)) : provable.classical Γ φ theorem provable.classical.sound : provable.classical Γ φ → (∀ ψ ∈ Γ, ψ) → φ := begin intros h₀ h₁, induction h₀, exact provable.constructive.sound h₀_h h₁, have c := h₀_ih h₁, classical, by_contradiction h, exact c h, end def tautology.classical (φ : Prop) : Prop := provable.classical ∅ φ -- lemma provable.classical.intro : ∀ φ ψ : Prop, -- (provable.classical (Γ ∪ {φ}) ψ) -- → provable.classical Γ (φ → ψ) -- := -- begin -- intros φ ψ h, -- cases h, -- apply provable.classical.constructive, -- -- apply provable.constructive.minimal, -- end -- example : tautology.classical (φ ∨ ¬ φ) := -- begin -- unfold tautology.classical, -- apply provable.classical.by_contradiction ∅ (φ ∨ ¬ φ), -- apply provable.classical.constructive ∅ (¬(φ ∨ ¬φ) → false), -- apply provable.constructive.minimal ∅ (¬(φ ∨ ¬φ) → false), -- apply provable.minimal.intro (¬(φ ∨ ¬φ)) false ∅, simp, -- have c₀ : minimal ∅ (φ → φ ∨ ¬φ), -- -- apply provable.classical.constructive ∅ (φ → φ ∨ ¬φ), -- -- apply provable.constructive.minimal ∅ (φ → φ ∨ ¬φ), -- apply provable.minimal.intro φ (φ ∨ ¬φ) ∅, -- simp, -- apply provable.minimal.or_intro_left φ (¬φ) {φ}, -- apply provable.minimal.reflexive {φ} φ, -- -- again, what the hell??? -- apply singleton_subset_iff.mp, -- simp, -- have c₁ : minimal -- end end metalogic
f925fe2bf32f3b32935d537e728100cefae2314e
94e33a31faa76775069b071adea97e86e218a8ee
/src/logic/equiv/basic.lean
6e3532985a63b8cf55c7edd7d21a8effe9a7bc9e
[ "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
95,193
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, Mario Carneiro -/ import data.fun_like.equiv import data.option.basic import data.prod.basic import data.quot import data.sigma.basic import data.subtype import data.sum.basic import logic.function.conjugate import logic.unique import tactic.norm_cast import tactic.simps /-! # Equivalence between types In this file we define two types: * `equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and not equality!) to express that various `Type`s or `Sort`s are equivalent. * `equiv.perm α`: the group of permutations `α ≃ α`. More lemmas about `equiv.perm` can be found in `group_theory/perm`. Then we define * canonical isomorphisms between various types: e.g., - `equiv.refl α` is the identity map interpreted as `α ≃ α`; - `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `α ⊕ β` and the sigma-type `Σ b : bool, cond b α β`; - `equiv.prod_sum_distrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum satisfy the distributive law up to a canonical equivalence; * operations on equivalences: e.g., - `equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`; - `equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order of the arguments!); - `equiv.prod_congr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and `eb : β₁ ≃ β₂` using `prod.map`. * definitions that transfer some instances along an equivalence. By convention, we transfer instances from right to left. - `equiv.inhabited` takes `e : α ≃ β` and `[inhabited β]` and returns `inhabited α`; - `equiv.unique` takes `e : α ≃ β` and `[unique β]` and returns `unique α`; - `equiv.decidable_eq` takes `e : α ≃ β` and `[decidable_eq β]` and returns `decidable_eq α`. More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance` does it for many algebraic type classes like `group`, `module`, etc. ## Tags equivalence, congruence, bijective map -/ open function universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) infix ` ≃ `:25 := equiv instance {F} [equiv_like F α β] : has_coe_t F (α ≃ β) := ⟨λ f, { to_fun := f, inv_fun := equiv_like.inv f, left_inv := equiv_like.left_inv f, right_inv := equiv_like.right_inv f }⟩ /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def equiv.perm (α : Sort*) := equiv α α namespace equiv instance : equiv_like (α ≃ β) α β := { coe := to_fun, inv := inv_fun, left_inv := left_inv, right_inv := right_inv, coe_injective' := λ e₁ e₂ h₁ h₂, by { cases e₁, cases e₂, congr' } } instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl /-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. -/ theorem coe_fn_injective : @function.injective (α ≃ β) (α → β) coe_fn := fun_like.coe_injective protected lemma coe_inj {e₁ e₂ : α ≃ β} : (e₁ : α → β) = e₂ ↔ e₁ = e₂ := fun_like.coe_fn_eq @[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g := fun_like.ext f g H protected lemma congr_arg {f : equiv α β} {x x' : α} : x = x' → f x = f x' := fun_like.congr_arg f protected lemma congr_fun {f g : equiv α β} (h : f = g) (x : α) : f x = g x := fun_like.congr_fun h x lemma ext_iff {f g : equiv α β} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff @[ext] lemma perm.ext {σ τ : equiv.perm α} (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext H protected lemma perm.congr_arg {f : equiv.perm α} {x x' : α} : x = x' → f x = f x' := equiv.congr_arg protected lemma perm.congr_fun {f g : equiv.perm α} (h : f = g) (x : α) : f x = g x := equiv.congr_fun h x lemma perm.ext_iff {σ τ : equiv.perm α} : σ = τ ↔ ∀ x, σ x = τ x := ext_iff /-- Any type is equivalent to itself. -/ @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ instance inhabited' : inhabited (α ≃ α) := ⟨equiv.refl α⟩ /-- Inverse of an equivalence `e : α ≃ β`. -/ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ /-- See Note [custom simps projection] -/ def simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply) /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ @[simp] lemma to_fun_as_coe (e : α ≃ β) : e.to_fun = e := rfl @[simp] lemma inv_fun_as_coe (e : α ≃ β) : e.inv_fun = e.symm := rfl protected theorem injective (e : α ≃ β) : injective e := equiv_like.injective e protected theorem surjective (e : α ≃ β) : surjective e := equiv_like.surjective e protected theorem bijective (e : α ≃ β) : bijective e := equiv_like.bijective e protected theorem subsingleton (e : α ≃ β) [subsingleton β] : subsingleton α := e.injective.subsingleton protected theorem subsingleton.symm (e : α ≃ β) [subsingleton α] : subsingleton β := e.symm.injective.subsingleton lemma subsingleton_congr (e : α ≃ β) : subsingleton α ↔ subsingleton β := ⟨λ h, by exactI e.symm.subsingleton, λ h, by exactI e.subsingleton⟩ instance equiv_subsingleton_cod [subsingleton β] : subsingleton (α ≃ β) := ⟨λ f g, equiv.ext $ λ x, subsingleton.elim _ _⟩ instance equiv_subsingleton_dom [subsingleton α] : subsingleton (α ≃ β) := ⟨λ f g, equiv.ext $ λ x, @subsingleton.elim _ (equiv.subsingleton.symm f) _ _⟩ instance perm_unique [subsingleton α] : unique (perm α) := unique_of_subsingleton (equiv.refl α) lemma perm.subsingleton_eq_refl [subsingleton α] (e : perm α) : e = equiv.refl α := subsingleton.elim _ _ /-- Transfer `decidable_eq` across an equivalence. -/ protected def decidable_eq (e : α ≃ β) [decidable_eq β] : decidable_eq α := e.injective.decidable_eq lemma nonempty_congr (e : α ≃ β) : nonempty α ↔ nonempty β := nonempty.congr e e.symm protected lemma nonempty (e : α ≃ β) [nonempty β] : nonempty α := e.nonempty_congr.mpr ‹_› /-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/ protected def inhabited [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm default⟩ /-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/ protected def unique [unique β] (e : α ≃ β) : unique α := e.symm.surjective.unique /-- Equivalence between equal types. -/ protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem coe_refl : ⇑(equiv.refl α) = id := rfl /-- This cannot be a `simp` lemmas as it incorrectly matches against `e : α ≃ synonym α`, when `synonym α` is semireducible. This makes a mess of `multiplicative.of_add` etc. -/ theorem perm.coe_subsingleton {α : Type*} [subsingleton α] (e : perm α) : ⇑(e) = id := by rw [perm.subsingleton_eq_refl e, coe_refl] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : ⇑(f.trans g) = g ∘ f := rfl theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x := e.right_inv x @[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x := e.left_inv x @[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl -- The `simp` attribute is needed to make this a `dsimp` lemma. -- `simp` will always rewrite with `equiv.symm_symm` before this has a chance to fire. @[simp, nolint simp_nf] theorem symm_symm_apply (f : α ≃ β) (b : α) : f.symm.symm b = f b := rfl theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y := equiv_like.apply_eq_iff_eq f theorem apply_eq_iff_eq_symm_apply {α β : Sort*} (f : α ≃ β) {x : α} {y : β} : f x = y ↔ x = f.symm y := begin conv_lhs { rw ←apply_symm_apply f y, }, rw apply_eq_iff_eq, end @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl @[simp] theorem cast_symm {α β} (h : α = β) : (equiv.cast h).symm = equiv.cast h.symm := rfl @[simp] theorem cast_refl {α} (h : α = α := rfl) : equiv.cast h = equiv.refl α := rfl @[simp] theorem cast_trans {α β γ} (h : α = β) (h2 : β = γ) : (equiv.cast h).trans (equiv.cast h2) = equiv.cast (h.trans h2) := ext $ λ x, by { substs h h2, refl } lemma cast_eq_iff_heq {α β} (h : α = β) {a : α} {b : β} : equiv.cast h a = b ↔ a == b := by { subst h, simp } lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl } @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl } @[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl } @[simp] theorem symm_trans_self (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext (by simp) @[simp] theorem self_trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv lemma injective_comp (e : α ≃ β) (f : β → γ) : injective (f ∘ e) ↔ injective f := equiv_like.injective_comp e f lemma comp_injective (f : α → β) (e : β ≃ γ) : injective (e ∘ f) ↔ injective f := equiv_like.comp_injective f e lemma surjective_comp (e : α ≃ β) (f : β → γ) : surjective (f ∘ e) ↔ surjective f := equiv_like.surjective_comp e f lemma comp_surjective (f : α → β) (e : β ≃ γ) : surjective (e ∘ f) ↔ surjective f := equiv_like.comp_surjective f e lemma bijective_comp (e : α ≃ β) (f : β → γ) : bijective (f ∘ e) ↔ bijective f := equiv_like.bijective_comp e f lemma comp_bijective (f : α → β) (e : β ≃ γ) : bijective (e ∘ f) ↔ bijective f := equiv_like.comp_bijective f e /-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ` is equivalent to the type of equivalences `β ≃ δ`. -/ def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, by { ext x, simp }, assume ac, by { ext x, simp } ⟩ @[simp] lemma equiv_congr_refl {α β} : (equiv.refl α).equiv_congr (equiv.refl β) = equiv.refl (α ≃ β) := by { ext, refl } @[simp] lemma equiv_congr_symm {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (ab.equiv_congr cd).symm = ab.symm.equiv_congr cd.symm := by { ext, refl } @[simp] lemma equiv_congr_trans {δ ε ζ} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) : (ab.equiv_congr de).trans (bc.equiv_congr ef) = (ab.trans bc).equiv_congr (de.trans ef) := by { ext, refl } @[simp] lemma equiv_congr_refl_left {α β γ} (bg : β ≃ γ) (e : α ≃ β) : (equiv.refl α).equiv_congr bg e = e.trans bg := rfl @[simp] lemma equiv_congr_refl_right {α β} (ab e : α ≃ β) : ab.equiv_congr (equiv.refl β) e = ab.symm.trans e := rfl @[simp] lemma equiv_congr_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) : ab.equiv_congr cd e x = cd (e (ab.symm x)) := rfl section perm_congr variables {α' β' : Type*} (e : α' ≃ β') /-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/ def perm_congr : perm α' ≃ perm β' := equiv_congr e e lemma perm_congr_def (p : equiv.perm α') : e.perm_congr p = (e.symm.trans p).trans e := rfl @[simp] lemma perm_congr_refl : e.perm_congr (equiv.refl _) = equiv.refl _ := by simp [perm_congr_def] @[simp] lemma perm_congr_symm : e.perm_congr.symm = e.symm.perm_congr := rfl @[simp] lemma perm_congr_apply (p : equiv.perm α') (x) : e.perm_congr p x = e (p (e.symm x)) := rfl lemma perm_congr_symm_apply (p : equiv.perm β') (x) : e.perm_congr.symm p x = e.symm (p (e x)) := rfl lemma perm_congr_trans (p p' : equiv.perm α') : (e.perm_congr p).trans (e.perm_congr p') = e.perm_congr (p.trans p') := by { ext, simp } end perm_congr /-- Two empty types are equivalent. -/ def equiv_of_is_empty (α β : Sort*) [is_empty α] [is_empty β] : α ≃ β := ⟨is_empty_elim, is_empty_elim, is_empty_elim, is_empty_elim⟩ /-- If `α` is an empty type, then it is equivalent to the `empty` type. -/ def equiv_empty (α : Sort u) [is_empty α] : α ≃ empty := equiv_of_is_empty α _ /-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/ def equiv_pempty (α : Sort v) [is_empty α] : α ≃ pempty.{u} := equiv_of_is_empty α _ /-- `α` is equivalent to an empty type iff `α` is empty. -/ def equiv_empty_equiv (α : Sort u) : (α ≃ empty) ≃ is_empty α := ⟨λ e, function.is_empty e, @equiv_empty α, λ e, ext $ λ x, (e x).elim, λ p, rfl⟩ /-- The `Sort` of proofs of a false proposition is equivalent to `pempty`. -/ def prop_equiv_pempty {p : Prop} (h : ¬p) : p ≃ pempty := @equiv_pempty p $ is_empty.prop_iff.2 h /-- If both `α` and `β` have a unique element, then `α ≃ β`. -/ def equiv_of_unique (α β : Sort*) [unique α] [unique β] : α ≃ β := { to_fun := default, inv_fun := default, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- If `α` has a unique element, then it is equivalent to any `punit`. -/ def equiv_punit (α : Sort*) [unique α] : α ≃ punit.{v} := equiv_of_unique α _ /-- The `Sort` of proofs of a true proposition is equivalent to `punit`. -/ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := @equiv_punit p $ unique_prop h /-- `ulift α` is equivalent to `α`. -/ @[simps apply symm_apply {fully_applied := ff}] protected def ulift {α : Type v} : ulift.{u} α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ /-- `plift α` is equivalent to `α`. -/ @[simps apply symm_apply {fully_applied := ff}] protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ /-- `pprod α β` is equivalent to `α × β` -/ @[simps apply symm_apply] def pprod_equiv_prod {α β : Type*} : pprod α β ≃ α × β := { to_fun := λ x, (x.1, x.2), inv_fun := λ x, ⟨x.1, x.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } /-- Product of two equivalences, in terms of `pprod`. If `α ≃ β` and `γ ≃ δ`, then `pprod α γ ≃ pprod β δ`. -/ @[congr, simps apply] def pprod_congr {δ : Sort z} (e₁ : α ≃ β) (e₂ : γ ≃ δ) : pprod α γ ≃ pprod β δ := { to_fun := λ x, ⟨e₁ x.1, e₂ x.2⟩, inv_fun := λ x, ⟨e₁.symm x.1, e₂.symm x.2⟩, left_inv := λ ⟨x, y⟩, by simp, right_inv := λ ⟨x, y⟩, by simp } /-- Combine two equivalences using `pprod` in the domain and `prod` in the codomain. -/ @[simps apply symm_apply] def pprod_prod {α₁ β₁ : Sort*} {α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : pprod α₁ β₁ ≃ α₂ × β₂ := (ea.pprod_congr eb).trans pprod_equiv_prod /-- Combine two equivalences using `pprod` in the codomain and `prod` in the domain. -/ @[simps apply symm_apply] def prod_pprod {α₁ β₁ : Type*} {α₂ β₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ × β₁ ≃ pprod α₂ β₂ := (ea.symm.pprod_prod eb.symm).symm /-- `pprod α β` is equivalent to `plift α × plift β` -/ @[simps apply symm_apply] def pprod_equiv_prod_plift {α β : Sort*} : pprod α β ≃ plift α × plift β := equiv.plift.symm.pprod_prod equiv.plift.symm /-- equivalence of propositions is the same as iff -/ def of_iff {P Q : Prop} (h : P ↔ Q) : P ≃ Q := { to_fun := h.mp, inv_fun := h.mpr, left_inv := λ x, rfl, right_inv := λ y, rfl } /-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁` is equivalent to the type of maps `α₂ → β₂`. -/ @[congr, simps apply] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := { to_fun := λ f, e₂ ∘ f ∘ e₁.symm, inv_fun := λ f, e₂.symm ∘ f ∘ e₁, left_inv := λ f, funext $ λ x, by simp, right_inv := λ f, funext $ λ x, by simp } lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) := by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] } @[simp] lemma arrow_congr_refl {α β : Sort*} : arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := rfl @[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := rfl /-- A version of `equiv.arrow_congr` in `Type`, rather than `Sort`. The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`, because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`. -/ @[congr, simps apply] def arrow_congr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := equiv.arrow_congr hα hβ @[simp] lemma arrow_congr'_refl {α β : Type*} : arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr'_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Type*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr' (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr' e₁ e₁').trans (arrow_congr' e₂ e₂') := rfl @[simp] lemma arrow_congr'_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr' e₁ e₂).symm = arrow_congr' e₁.symm e₂.symm := rfl /-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/ @[simps apply] def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e @[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl @[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl @[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl -- This should not be a simp lemma as long as `(∘)` is reducible: -- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using -- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination. lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) := by apply arrow_congr_comp lemma eq_comp_symm {α β γ} (e : α ≃ β) (f : β → γ) (g : α → γ) : f = g ∘ e.symm ↔ f ∘ e = g := (e.arrow_congr (equiv.refl γ)).symm_apply_eq.symm lemma comp_symm_eq {α β γ} (e : α ≃ β) (f : β → γ) (g : α → γ) : g ∘ e.symm = f ↔ g = f ∘ e := (e.arrow_congr (equiv.refl γ)).eq_symm_apply.symm lemma eq_symm_comp {α β γ} (e : α ≃ β) (f : γ → α) (g : γ → β) : f = e.symm ∘ g ↔ e ∘ f = g := ((equiv.refl γ).arrow_congr e).eq_symm_apply lemma symm_comp_eq {α β γ} (e : α ≃ β) (f : γ → α) (g : γ → β) : e.symm ∘ g = f ↔ g = e ∘ f := ((equiv.refl γ).arrow_congr e).symm_apply_eq section binary_op variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) lemma semiconj_conj (f : α₁ → α₁) : semiconj e f (e.conj f) := λ x, by simp lemma semiconj₂_conj : semiconj₂ e f (e.arrow_congr e.conj f) := λ x y, by simp instance [is_associative α₁ f] : is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_associative_right e.surjective instance [is_idempotent α₁ f] : is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_idempotent_right e.surjective instance [is_left_cancel α₁ f] : is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩ instance [is_right_cancel α₁ f] : is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩ end binary_op /-- `punit` sorts in any two universes are equivalent. -/ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩ section /-- The sort of maps to `punit.{v}` is equivalent to `punit.{w}`. -/ def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩ /-- If `α` is `subsingleton` and `a : α`, then the type of dependent functions `Π (i : α), β i` is equivalent to `β i`. -/ @[simps] def Pi_subsingleton {α} (β : α → Sort*) [subsingleton α] (a : α) : (Π a', β a') ≃ β a := { to_fun := eval a, inv_fun := λ x b, cast (congr_arg β $ subsingleton.elim a b) x, left_inv := λ f, funext $ λ b, by { rw subsingleton.elim b a, reflexivity }, right_inv := λ b, rfl } /-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/ @[simps { fully_applied := ff }] def fun_unique (α β) [unique α] : (α → β) ≃ β := Pi_subsingleton _ default /-- The sort of maps from `punit` is equivalent to the codomain. -/ def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := fun_unique _ _ /-- The sort of maps from `true` is equivalent to the codomain. -/ def true_arrow_equiv (α : Sort*) : (true → α) ≃ α := fun_unique _ _ /-- The sort of maps from a type that `is_empty` is equivalent to `punit`. -/ def arrow_punit_of_is_empty (α β : Sort*) [is_empty α] : (α → β) ≃ punit.{u} := ⟨λ f, punit.star, λ u, is_empty_elim, λ f, funext is_empty_elim, λ u, by { cases u, refl }⟩ /-- The sort of maps from `empty` is equivalent to `punit`. -/ def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ /-- The sort of maps from `pempty` is equivalent to `punit`. -/ def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ /-- The sort of maps from `false` is equivalent to `punit`. -/ def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ end /-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. This is `prod.map` as an equivalence. -/ @[congr, simps apply] def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩ @[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm := rfl /-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. This is `prod.swap` as an equivalence.-/ @[simps apply] def prod_comm (α β : Type*) : α × β ≃ β × α := ⟨prod.swap, prod.swap, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ @[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl /-- Type product is associative up to an equivalence. -/ @[simps] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) := ⟨λ p, (p.1.1, p.1.2, p.2), λ p, ((p.1, p.2.1), p.2.2), λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ /-- Functions on `α × β` are equivalent to functions `α → β → γ`. -/ @[simps {fully_applied := ff}] def curry (α β γ : Type*) : (α × β → γ) ≃ (α → β → γ) := { to_fun := curry, inv_fun := uncurry, left_inv := uncurry_curry, right_inv := curry_uncurry } section /-- `punit` is a right identity for type product up to an equivalence. -/ @[simps] def prod_punit (α : Type*) : α × punit.{u+1} ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ /-- `punit` is a left identity for type product up to an equivalence. -/ @[simps] def punit_prod (α : Type*) : punit.{u+1} × α ≃ α := calc punit × α ≃ α × punit : prod_comm _ _ ... ≃ α : prod_punit _ /-- Any `unique` type is a right identity for type product up to equivalence. -/ def prod_unique (α β : Type*) [unique β] : α × β ≃ α := ((equiv.refl α).prod_congr $ equiv_punit β).trans $ prod_punit α /-- Any `unique` type is a left identity for type product up to equivalence. -/ def unique_prod (α β : Type*) [unique β] : β × α ≃ α := ((equiv_punit β).prod_congr $ equiv.refl α).trans $ punit_prod α /-- `empty` type is a right absorbing element for type product up to an equivalence. -/ def prod_empty (α : Type*) : α × empty ≃ empty := equiv_empty _ /-- `empty` type is a left absorbing element for type product up to an equivalence. -/ def empty_prod (α : Type*) : empty × α ≃ empty := equiv_empty _ /-- `pempty` type is a right absorbing element for type product up to an equivalence. -/ def prod_pempty (α : Type*) : α × pempty ≃ pempty := equiv_pempty _ /-- `pempty` type is a left absorbing element for type product up to an equivalence. -/ def pempty_prod (α : Type*) : pempty × α ≃ pempty := equiv_pempty _ end section open sum /-- `psum` is equivalent to `sum`. -/ def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β := { to_fun := λ s, psum.cases_on s inl inr, inv_fun := sum.elim psum.inl psum.inr, left_inv := λ s, by cases s; refl, right_inv := λ s, by cases s; refl } /-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. This is `sum.map` as an equivalence. -/ @[simps apply] def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ := ⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩ /-- If `α ≃ α'` and `β ≃ β'`, then `psum α β ≃ psum α' β'`. -/ def psum_congr {δ : Sort z} (e₁ : α ≃ β) (e₂ : γ ≃ δ) : psum α γ ≃ psum β δ := { to_fun := λ x, psum.cases_on x (psum.inl ∘ e₁) (psum.inr ∘ e₂), inv_fun := λ x, psum.cases_on x (psum.inl ∘ e₁.symm) (psum.inr ∘ e₂.symm), left_inv := by rintro (x|x); simp, right_inv := by rintro (x|x); simp } /-- Combine two `equiv`s using `psum` in the domain and `sum` in the codomain. -/ def psum_sum {α₁ β₁ : Sort*} {α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : psum α₁ β₁ ≃ α₂ ⊕ β₂ := (ea.psum_congr eb).trans (psum_equiv_sum _ _) /-- Combine two `equiv`s using `sum` in the domain and `psum` in the codomain. -/ def sum_psum {α₁ β₁ : Type*} {α₂ β₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ psum α₂ β₂ := (ea.symm.psum_sum eb.symm).symm @[simp] lemma sum_congr_trans {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} (e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) : (equiv.sum_congr e f).trans (equiv.sum_congr g h) = (equiv.sum_congr (e.trans g) (f.trans h)) := by { ext i, cases i; refl } @[simp] lemma sum_congr_symm {α β γ δ : Sort*} (e : α ≃ β) (f : γ ≃ δ) : (equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) := rfl @[simp] lemma sum_congr_refl {α β : Sort*} : equiv.sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := by { ext i, cases i; refl } namespace perm /-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/ @[reducible] def sum_congr {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) : equiv.perm (α ⊕ β) := equiv.sum_congr ea eb @[simp] lemma sum_congr_apply {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) (x : α ⊕ β) : sum_congr ea eb x = sum.map ⇑ea ⇑eb x := equiv.sum_congr_apply ea eb x @[simp] lemma sum_congr_trans {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) (g : equiv.perm α) (h : equiv.perm β) : (sum_congr e f).trans (sum_congr g h) = sum_congr (e.trans g) (f.trans h) := equiv.sum_congr_trans e f g h @[simp] lemma sum_congr_symm {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) : (sum_congr e f).symm = sum_congr (e.symm) (f.symm) := equiv.sum_congr_symm e f @[simp] lemma sum_congr_refl {α β : Sort*} : sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := equiv.sum_congr_refl end perm /-- `bool` is equivalent the sum of two `punit`s. -/ def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ /-- `Prop` is noncomputably equivalent to `bool`. -/ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ /-- Sum of types is commutative up to an equivalence. This is `sum.swap` as an equivalence. -/ @[simps apply {fully_applied := ff}] def sum_comm (α β : Type*) : α ⊕ β ≃ β ⊕ α := ⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩ @[simp] lemma sum_comm_symm (α β) : (sum_comm α β).symm = sum_comm β α := rfl /-- Sum of types is associative up to an equivalence. -/ def sum_assoc (α β γ : Type*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr), sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr, by rintros (⟨_ | _⟩ | _); refl, by rintros (_ | ⟨_ | _⟩); refl⟩ @[simp] lemma sum_assoc_apply_inl_inl {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] lemma sum_assoc_apply_inl_inr {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] lemma sum_assoc_apply_inr {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] lemma sum_assoc_symm_apply_inl {α β γ} (a) : (sum_assoc α β γ).symm (inl a) = inl (inl a) := rfl @[simp] lemma sum_assoc_symm_apply_inr_inl {α β γ} (b) : (sum_assoc α β γ).symm (inr (inl b)) = inl (inr b) := rfl @[simp] lemma sum_assoc_symm_apply_inr_inr {α β γ} (c) : (sum_assoc α β γ).symm (inr (inr c)) = inr c := rfl /-- Sum with `empty` is equivalent to the original type. -/ @[simps symm_apply] def sum_empty (α β : Type*) [is_empty β] : α ⊕ β ≃ α := ⟨sum.elim id is_empty_elim, inl, λ s, by { rcases s with _ | x, refl, exact is_empty_elim x }, λ a, rfl⟩ @[simp] lemma sum_empty_apply_inl {α β : Type*} [is_empty β] (a : α) : sum_empty α β (sum.inl a) = a := rfl /-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/ @[simps symm_apply] def empty_sum (α β : Type*) [is_empty α] : α ⊕ β ≃ β := (sum_comm _ _).trans $ sum_empty _ _ @[simp] lemma empty_sum_apply_inr {α β : Type*} [is_empty α] (b : β) : empty_sum α β (sum.inr b) = b := rfl /-- `option α` is equivalent to `α ⊕ punit` -/ def option_equiv_sum_punit (α : Type*) : option α ≃ α ⊕ punit.{u+1} := ⟨λ o, o.elim (inr punit.star) inl, λ s, s.elim some (λ _, none), λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ @[simp] lemma option_equiv_sum_punit_none {α} : option_equiv_sum_punit α none = sum.inr punit.star := rfl @[simp] lemma option_equiv_sum_punit_some {α} (a) : option_equiv_sum_punit α (some a) = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_coe {α} (a : α) : option_equiv_sum_punit α a = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_symm_inl {α} (a) : (option_equiv_sum_punit α).symm (sum.inl a) = a := rfl @[simp] lemma option_equiv_sum_punit_symm_inr {α} (a) : (option_equiv_sum_punit α).symm (sum.inr a) = none := rfl /-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/ @[simps] def option_is_some_equiv (α : Type*) : {x : option α // x.is_some} ≃ α := { to_fun := λ o, option.get o.2, inv_fun := λ x, ⟨some x, dec_trivial⟩, left_inv := λ o, subtype.eq $ option.some_get _, right_inv := λ x, option.get_some _ _ } /-- The product over `option α` of `β a` is the binary product of the product over `α` of `β (some α)` and `β none` -/ @[simps] def pi_option_equiv_prod {α : Type*} {β : option α → Type*} : (Π a : option α, β a) ≃ (β none × Π a : α, β (some a)) := { to_fun := λ f, (f none, λ a, f (some a)), inv_fun := λ x a, option.cases_on a x.fst x.snd, left_inv := λ f, funext $ λ a, by cases a; refl, right_inv := λ x, by simp } /-- `α ⊕ β` is equivalent to a `sigma`-type over `bool`. Note that this definition assumes `α` and `β` to be types from the same universe, so it cannot by used directly to transfer theorems about sigma types to theorems about sum types. In many cases one can use `ulift` to work around this difficulty. -/ def sum_equiv_sigma_bool (α β : Type u) : α ⊕ β ≃ (Σ b: bool, cond b α β) := ⟨λ s, s.elim (λ x, ⟨tt, x⟩) (λ x, ⟨ff, x⟩), λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ /-- `sigma_fiber_equiv f` for `f : α → β` is the natural equivalence between the type of all fibres of `f` and the total space `α`. -/ -- See also `equiv.sigma_preimage_equiv`. @[simps] def sigma_fiber_equiv {α β : Type*} (f : α → β) : (Σ y : β, {x // f x = y}) ≃ α := ⟨λ x, ↑x.2, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩ end section sum_compl /-- For any predicate `p` on `α`, the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}` is naturally equivalent to `α`. See `subtype_or_equiv` for sum types over subtypes `{x // p x}` and `{x // q x}` that are not necessarily `is_compl p q`. -/ def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] : {a // p a} ⊕ {a // ¬ p a} ≃ α := { to_fun := sum.elim coe coe, inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩, left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], }, right_inv := λ a, by { dsimp, split_ifs; refl } } @[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // p a}) : sum_compl p (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // ¬ p a}) : sum_compl p (sum.inr x) = x := rfl @[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : p a) : (sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h @[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : ¬ p a) : (sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h /-- Combines an `equiv` between two subtypes with an `equiv` between their complements to form a permutation. -/ def subtype_congr {α : Type*} {p q : α → Prop} [decidable_pred p] [decidable_pred q] (e : {x // p x} ≃ {x // q x}) (f : {x // ¬p x} ≃ {x // ¬q x}) : perm α := (sum_compl p).symm.trans ((sum_congr e f).trans (sum_compl q)) open equiv variables {ε : Type*} {p : ε → Prop} [decidable_pred p] variables (ep ep' : perm {a // p a}) (en en' : perm {a // ¬ p a}) /-- Combining permutations on `ε` that permute only inside or outside the subtype split induced by `p : ε → Prop` constructs a permutation on `ε`. -/ def perm.subtype_congr : equiv.perm ε := perm_congr (sum_compl p) (sum_congr ep en) lemma perm.subtype_congr.apply (a : ε) : ep.subtype_congr en a = if h : p a then ep ⟨a, h⟩ else en ⟨a, h⟩ := by { by_cases h : p a; simp [perm.subtype_congr, h] } @[simp] lemma perm.subtype_congr.left_apply {a : ε} (h : p a) : ep.subtype_congr en a = ep ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.left_apply_subtype (a : {a // p a}) : ep.subtype_congr en a = ep a := by { convert perm.subtype_congr.left_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.right_apply {a : ε} (h : ¬ p a) : ep.subtype_congr en a = en ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.right_apply_subtype (a : {a // ¬ p a}) : ep.subtype_congr en a = en a := by { convert perm.subtype_congr.right_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.refl : perm.subtype_congr (equiv.refl {a // p a}) (equiv.refl {a // ¬ p a}) = equiv.refl ε := by { ext x, by_cases h : p x; simp [h] } @[simp] lemma perm.subtype_congr.symm : (ep.subtype_congr en).symm = perm.subtype_congr ep.symm en.symm := begin ext x, by_cases h : p x, { have : p (ep.symm ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }, { have : ¬ p (en.symm ⟨x, h⟩) := subtype.property (en.symm _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end @[simp] lemma perm.subtype_congr.trans : (ep.subtype_congr en).trans (ep'.subtype_congr en') = perm.subtype_congr (ep.trans ep') (en.trans en') := begin ext x, by_cases h : p x, { have : p (ep ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, this] }, { have : ¬ p (en ⟨x, h⟩) := subtype.property (en _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end end sum_compl section subtype_preimage variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β) /-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`, the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}` is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/ @[simps] def subtype_preimage : {x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) := { to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a, inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩, funext $ λ ⟨a, h⟩, dif_pos h⟩, left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a, (by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }), right_inv := λ x, funext $ λ ⟨a, h⟩, show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } } lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) : ((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ := dif_pos h lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) : ((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ := dif_neg h end subtype_preimage section /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ /-- Given `φ : α → β → Sort*`, we have an equivalence between `Π a b, φ a b` and `Π b a, φ a b`. This is `function.swap` as an `equiv`. -/ @[simps apply] def Pi_comm {α β} (φ : α → β → Sort*) : (Π a b, φ a b) ≃ (Π b a, φ a b) := ⟨swap, swap, λ x, rfl, λ y, rfl⟩ @[simp] lemma Pi_comm_symm {α β} {φ : α → β → Sort*} : (Pi_comm φ).symm = (Pi_comm $ swap φ) := rfl /-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent to the type of dependent functions of two arguments (i.e., functions to the space of functions). This is `sigma.curry` and `sigma.uncurry` together as an equiv. -/ def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) := { to_fun := sigma.curry, inv_fun := sigma.uncurry, left_inv := sigma.uncurry_curry, right_inv := sigma.curry_uncurry } end section /-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/ @[simps apply symm_apply] def psigma_equiv_sigma {α} (β : α → Type*) : (Σ' i, β i) ≃ Σ i, β i := ⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/ @[simps apply symm_apply] def psigma_equiv_sigma_plift {α} (β : α → Sort*) : (Σ' i, β i) ≃ Σ i : plift α, plift (β i.down) := ⟨λ a, ⟨plift.up a.1, plift.up a.2⟩, λ a, ⟨a.1.down, a.2.down⟩, λ ⟨a, b⟩, rfl, λ ⟨⟨a⟩, ⟨b⟩⟩, rfl⟩ /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ' a, β₁ a` and `Σ' a, β₂ a`. -/ @[simps apply] def psigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Σ' a, β₁ a) ≃ Σ' a, β₂ a := ⟨λ a, ⟨a.1, F a.1 a.2⟩, λ a, ⟨a.1, (F a.1).symm a.2⟩, λ ⟨a, b⟩, congr_arg (psigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (psigma.mk a) $ apply_symm_apply (F a) b⟩ @[simp] lemma psigma_congr_right_trans {α} {β₁ β₂ β₃ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) (G : Π a, β₂ a ≃ β₃ a) : (psigma_congr_right F).trans (psigma_congr_right G) = psigma_congr_right (λ a, (F a).trans (G a)) := by { ext1 x, cases x, refl } @[simp] lemma psigma_congr_right_symm {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (psigma_congr_right F).symm = psigma_congr_right (λ a, (F a).symm) := by { ext1 x, cases x, refl } @[simp] lemma psigma_congr_right_refl {α} {β : α → Sort*} : (psigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ' a, β a) := by { ext1 x, cases x, refl } /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and `Σ a, β₂ a`. -/ @[simps apply] def sigma_congr_right {α} {β₁ β₂ : α → Type*} (F : Π a, β₁ a ≃ β₂ a) : (Σ a, β₁ a) ≃ Σ a, β₂ a := ⟨λ a, ⟨a.1, F a.1 a.2⟩, λ a, ⟨a.1, (F a.1).symm a.2⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩ @[simp] lemma sigma_congr_right_trans {α} {β₁ β₂ β₃ : α → Type*} (F : Π a, β₁ a ≃ β₂ a) (G : Π a, β₂ a ≃ β₃ a) : (sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) := by { ext1 x, cases x, refl } @[simp] lemma sigma_congr_right_symm {α} {β₁ β₂ : α → Type*} (F : Π a, β₁ a ≃ β₂ a) : (sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) := by { ext1 x, cases x, refl } @[simp] lemma sigma_congr_right_refl {α} {β : α → Type*} : (sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) := by { ext1 x, cases x, refl } /-- A `psigma` with `Prop` fibers is equivalent to the subtype. -/ def psigma_equiv_subtype {α : Type v} (P : α → Prop) : (Σ' i, P i) ≃ subtype P := { to_fun := λ x, ⟨x.1, x.2⟩, inv_fun := λ x, ⟨x.1, x.2⟩, left_inv := λ x, by { cases x, refl, }, right_inv := λ x, by { cases x, refl, }, } /-- A `sigma` with `plift` fibers is equivalent to the subtype. -/ def sigma_plift_equiv_subtype {α : Type v} (P : α → Prop) : (Σ i, plift (P i)) ≃ subtype P := ((psigma_equiv_sigma _).symm.trans (psigma_congr_right (λ a, equiv.plift))).trans (psigma_equiv_subtype P) /-- A `sigma` with `λ i, ulift (plift (P i))` fibers is equivalent to `{ x // P x }`. Variant of `sigma_plift_equiv_subtype`. -/ def sigma_ulift_plift_equiv_subtype {α : Type v} (P : α → Prop) : (Σ i, ulift (plift (P i))) ≃ subtype P := (sigma_congr_right (λ a, equiv.ulift)).trans (sigma_plift_equiv_subtype P) namespace perm /-- A family of permutations `Π a, perm (β a)` generates a permuation `perm (Σ a, β₁ a)`. -/ @[reducible] def sigma_congr_right {α} {β : α → Sort*} (F : Π a, perm (β a)) : perm (Σ a, β a) := equiv.sigma_congr_right F @[simp] lemma sigma_congr_right_trans {α} {β : α → Sort*} (F : Π a, perm (β a)) (G : Π a, perm (β a)) : (sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) := equiv.sigma_congr_right_trans F G @[simp] lemma sigma_congr_right_symm {α} {β : α → Sort*} (F : Π a, perm (β a)) : (sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) := equiv.sigma_congr_right_symm F @[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} : (sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) := equiv.sigma_congr_right_refl end perm /-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/ @[simps apply] def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} (e : α₁ ≃ α₂) : (Σ a:α₁, β (e a)) ≃ (Σ a:α₂, β a) := ⟨λ a, ⟨e a.1, a.2⟩, λ a, ⟨e.symm a.1, @@eq.rec β a.2 (e.right_inv a.1).symm⟩, λ ⟨a, b⟩, match e.symm (e a), e.left_inv a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ e) _ (@@eq.rec β b (congr_arg e h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match e (e.symm a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ /-- Transporting a sigma type through an equivalence of the base -/ def sigma_congr_left' {α₁ α₂} {β : α₁ → Sort*} (f : α₁ ≃ α₂) : (Σ a:α₁, β a) ≃ (Σ a:α₂, β (f.symm a)) := (sigma_congr_left f.symm).symm /-- Transporting a sigma type through an equivalence of the base and a family of equivalences of matching fibers -/ def sigma_congr {α₁ α₂} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} (f : α₁ ≃ α₂) (F : ∀ a, β₁ a ≃ β₂ (f a)) : sigma β₁ ≃ sigma β₂ := (sigma_congr_right F).trans (sigma_congr_left f) /-- `sigma` type with a constant fiber is equivalent to the product. -/ @[simps apply symm_apply] def sigma_equiv_prod (α β : Type*) : (Σ_:α, β) ≃ α × β := ⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- If each fiber of a `sigma` type is equivalent to a fixed type, then the sigma type is equivalent to the product. -/ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : Π a, β₁ a ≃ β) : sigma β₁ ≃ α × β := (sigma_congr_right F).trans (sigma_equiv_prod α β) /-- Dependent product of types is associative up to an equivalence. -/ def sigma_assoc {α : Type*} {β : α → Type*} (γ : Π (a : α), β a → Type*) : (Σ (ab : Σ (a : α), β a), γ ab.1 ab.2) ≃ Σ (a : α), (Σ (b : β a), γ a b) := { to_fun := λ x, ⟨x.1.1, ⟨x.1.2, x.2⟩⟩, inv_fun := λ x, ⟨⟨x.1, x.2.1⟩, x.2.2⟩, left_inv := λ ⟨⟨a, b⟩, c⟩, rfl, right_inv := λ ⟨a, ⟨b, c⟩⟩, rfl } end section prod_congr variables {α₁ β₁ β₂ : Type*} (e : α₁ → β₁ ≃ β₂) /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `β₁ × α₁` and `β₂ × α₁`. -/ def prod_congr_left : β₁ × α₁ ≃ β₂ × α₁ := { to_fun := λ ab, ⟨e ab.2 ab.1, ab.2⟩, inv_fun := λ ab, ⟨(e ab.2).symm ab.1, ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) : prod_congr_left e (b, a) = (e a b, a) := rfl lemma prod_congr_refl_right (e : β₁ ≃ β₂) : prod_congr e (equiv.refl α₁) = prod_congr_left (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `α₁ × β₁` and `α₁ × β₂`. -/ def prod_congr_right : α₁ × β₁ ≃ α₁ × β₂ := { to_fun := λ ab, ⟨ab.1, e ab.1 ab.2⟩, inv_fun := λ ab, ⟨ab.1, (e ab.1).symm ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) : prod_congr_right e (a, b) = (a, e a b) := rfl lemma prod_congr_refl_left (e : β₁ ≃ β₂) : prod_congr (equiv.refl α₁) e = prod_congr_right (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_left_trans_prod_comm : (prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_right_trans_prod_comm : (prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_congr_right_sigma_equiv_prod : (sigma_congr_right e).trans (sigma_equiv_prod α₁ β₂) = (sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_equiv_prod_sigma_congr_right : (sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) = (prod_congr_right e).trans (sigma_equiv_prod α₁ β₂).symm := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences between fibers gives an equivalence between domains. -/ -- See also `equiv.of_preimage_equiv`. @[simps] def of_fiber_equiv {α β γ : Type*} {f : α → γ} {g : β → γ} (e : Π c, {a // f a = c} ≃ {b // g b = c}) : α ≃ β := (sigma_fiber_equiv f).symm.trans $ (equiv.sigma_congr_right e).trans (sigma_fiber_equiv g) lemma of_fiber_equiv_map {α β γ} {f : α → γ} {g : β → γ} (e : Π c, {a // f a = c} ≃ {b // g b = c}) (a : α) : g (of_fiber_equiv e a) = f a := (_ : {b // g b = _}).prop /-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend on the first component. A typical example is a shear mapping, explaining the name of this declaration. -/ @[simps {fully_applied := ff}] def prod_shear {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := { to_fun := λ x : α₁ × β₁, (e₁ x.1, e₂ x.1 x.2), inv_fun := λ y : α₂ × β₂, (e₁.symm y.1, (e₂ $ e₁.symm y.1).symm y.2), left_inv := by { rintro ⟨x₁, y₁⟩, simp only [symm_apply_apply] }, right_inv := by { rintro ⟨x₁, y₁⟩, simp only [apply_symm_apply] } } end prod_congr namespace perm variables {α₁ β₁ β₂ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁) /-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to `(a, e b)` and keeping the other `(a', b)` fixed. -/ def prod_extend_right : perm (α₁ × β₁) := { to_fun := λ ab, if ab.fst = a then (a, e ab.snd) else ab, inv_fun := λ ab, if ab.fst = a then (a, e.symm ab.snd) else ab, left_inv := by { rintros ⟨k', x⟩, dsimp only, split_ifs with h; simp [h] }, right_inv := by { rintros ⟨k', x⟩, dsimp only, split_ifs with h; simp [h] } } @[simp] lemma prod_extend_right_apply_eq (b : β₁) : prod_extend_right a e (a, b) = (a, e b) := if_pos rfl lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) : prod_extend_right a e (a', b) = (a', b) := if_neg h lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁} (h : prod_extend_right a e (a', b) ≠ (a', b)) : a' = a := by { contrapose! h, exact prod_extend_right_apply_ne _ h _ } @[simp] lemma fst_prod_extend_right (ab : α₁ × β₁) : (prod_extend_right a e ab).fst = ab.fst := begin rw [prod_extend_right, coe_fn_mk], split_ifs with h, { rw h }, { refl } end end perm section /-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions `γ → α` and `γ → β`. -/ def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by { cases p, refl }⟩ open sum /-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions on `α` and on `β`. -/ def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p, sum.elim p.1 p.2, λ f, by { ext ⟨⟩; refl }, λ p, by { cases p, refl }⟩ @[simp] lemma sum_arrow_equiv_prod_arrow_apply_fst {α β γ} (f : (α ⊕ β) → γ) (a : α) : (sum_arrow_equiv_prod_arrow α β γ f).1 a = f (inl a) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_apply_snd {α β γ} (f : (α ⊕ β) → γ) (b : β) : (sum_arrow_equiv_prod_arrow α β γ f).2 b = f (inr b) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inl {α β γ} (f : α → γ) (g : β → γ) (a : α) : ((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inl a) = f a := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inr {α β γ} (f : α → γ) (g : β → γ) (b : β) : ((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inr b) = g b := rfl /-- Type product is right distributive with respect to type sum up to an equivalence. -/ def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) := ⟨λ p, p.1.map (λ x, (x, p.2)) (λ x, (x, p.2)), λ s, s.elim (prod.map inl id) (prod.map inr id), by rintro ⟨_ | _, _⟩; refl, by rintro (⟨_, _⟩ | ⟨_, _⟩); refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl @[simp] theorem sum_prod_distrib_symm_apply_left {α β γ} (a : α × γ) : (sum_prod_distrib α β γ).symm (inl a) = (inl a.1, a.2) := rfl @[simp] theorem sum_prod_distrib_symm_apply_right {α β γ} (b : β × γ) : (sum_prod_distrib α β γ).symm (inr b) = (inr b.1, b.2) := rfl /-- Type product is left distributive with respect to type sum up to an equivalence. -/ def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _ ... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _ ... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl @[simp] theorem prod_sum_distrib_symm_apply_left {α β γ} (a : α × β) : (prod_sum_distrib α β γ).symm (inl a) = (a.1, inl a.2) := rfl @[simp] theorem prod_sum_distrib_symm_apply_right {α β γ} (a : α × γ) : (prod_sum_distrib α β γ).symm (inr a) = (a.1, inr a.2) := rfl /-- An indexed sum of disjoint sums of types is equivalent to the sum of the indexed sums. -/ @[simps] def sigma_sum_distrib {ι : Type*} (α β : ι → Type*) : (Σ i, α i ⊕ β i) ≃ (Σ i, α i) ⊕ Σ i, β i := ⟨λ p, p.2.map (sigma.mk p.1) (sigma.mk p.1), sum.elim (sigma.map id (λ _, sum.inl)) (sigma.map id (λ _, sum.inr)), λ p, by { rcases p with ⟨i, (a | b)⟩; refl }, λ p, by { rcases p with (⟨i, a⟩ | ⟨i, b⟩); refl }⟩ /-- The product of an indexed sum of types (formally, a `sigma`-type `Σ i, α i`) by a type `β` is equivalent to the sum of products `Σ i, (α i × β)`. -/ def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) : ((Σ i, α i) × β) ≃ (Σ i, (α i × β)) := ⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩, λ p, (⟨p.1, p.2.1⟩, p.2.2), λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl }, λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩ /-- An equivalence that separates out the 0th fiber of `(Σ (n : ℕ), f n)`. -/ def sigma_nat_succ (f : ℕ → Type u) : (Σ n, f n) ≃ f 0 ⊕ Σ n, f (n + 1) := ⟨λ x, @sigma.cases_on ℕ f (λ _, f 0 ⊕ Σ n, f (n + 1)) x (λ n, @nat.cases_on (λ i, f i → (f 0 ⊕ Σ (n : ℕ), f (n + 1))) n (λ (x : f 0), sum.inl x) (λ (n : ℕ) (x : f n.succ), sum.inr ⟨n, x⟩)), sum.elim (sigma.mk 0) (sigma.map nat.succ (λ _, id)), by { rintro ⟨(n | n), x⟩; refl }, by { rintro (x | ⟨n, x⟩); refl }⟩ /-- The product `bool × α` is equivalent to `α ⊕ α`. -/ def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α := calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (unit × α) ⊕ (unit × α) : sum_prod_distrib _ _ _ ... ≃ α ⊕ α : sum_congr (punit_prod _) (punit_prod _) /-- The function type `bool → α` is equivalent to `α × α`. -/ @[simps] def bool_arrow_equiv_prod (α : Type u) : (bool → α) ≃ α × α := { to_fun := λ f, (f tt, f ff), inv_fun := λ p b, cond b p.1 p.2, left_inv := λ f, funext $ bool.forall_bool.2 ⟨rfl, rfl⟩, right_inv := λ ⟨x, y⟩, rfl } end section open sum nat /-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/ def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ /-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/ def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ := nat_equiv_nat_sum_punit.symm /-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/ def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end /-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/ def list_equiv_of_equiv {α β : Type*} (e : α ≃ β) : list α ≃ list β := { to_fun := list.map e, inv_fun := list.map e.symm, left_inv := λ l, by rw [list.map_map, e.symm_comp_self, list.map_id], right_inv := λ l, by rw [list.map_map, e.self_comp_symm, list.map_id] } /-- If `α` is equivalent to `β`, then `unique α` is equivalent to `unique β`. -/ def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := λ h, @equiv.unique _ _ h e.symm, inv_fun := λ h, @equiv.unique _ _ h e, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- If `α` is equivalent to `β`, then `is_empty α` is equivalent to `is_empty β`. -/ lemma is_empty_congr (e : α ≃ β) : is_empty α ↔ is_empty β := ⟨λ h, @function.is_empty _ _ h e.symm, λ h, @function.is_empty _ _ h e⟩ protected lemma is_empty (e : α ≃ β) [is_empty β] : is_empty α := e.is_empty_congr.mpr ‹_› section open subtype /-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. For the statement where `α = β`, that is, `e : perm α`, see `perm.subtype_perm`. -/ def subtype_equiv {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := { to_fun := λ a, ⟨e a, (h _).mp a.prop⟩, inv_fun := λ b, ⟨e.symm b, (h _).mpr ((e.apply_symm_apply b).symm ▸ b.prop)⟩, left_inv := λ a, subtype.ext $ by simp, right_inv := λ b, subtype.ext $ by simp } @[simp] lemma subtype_equiv_refl {p : α → Prop} (h : ∀ a, p a ↔ p (equiv.refl _ a) := λ a, iff.rfl) : (equiv.refl α).subtype_equiv h = equiv.refl {a : α // p a} := by { ext, refl } @[simp] lemma subtype_equiv_symm {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) : (e.subtype_equiv h).symm = e.symm.subtype_equiv (λ a, by { convert (h $ e.symm a).symm, exact (e.apply_symm_apply a).symm }) := rfl @[simp] lemma subtype_equiv_trans {p : α → Prop} {q : β → Prop} {r : γ → Prop} (e : α ≃ β) (f : β ≃ γ) (h : ∀ (a : α), p a ↔ q (e a)) (h' : ∀ (b : β), q b ↔ r (f b)): (e.subtype_equiv h).trans (f.subtype_equiv h') = (e.trans f).subtype_equiv (λ a, (h a).trans (h' $ e a)) := rfl @[simp] lemma subtype_equiv_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) : e.subtype_equiv h x = ⟨e x, (h _).1 x.2⟩ := rfl /-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to `{x // q x}`. -/ @[simps] def subtype_equiv_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} := subtype_equiv (equiv.refl _) e /-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent to the subtype `{b // p b}`. -/ def subtype_equiv_of_subtype {p : β → Prop} (e : α ≃ β) : {a : α // p (e a)} ≃ {b : β // p b} := subtype_equiv e $ by simp /-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/ def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := e.symm.subtype_equiv_of_subtype.symm /-- If two predicates are equal, then the corresponding subtypes are equivalent. -/ def subtype_equiv_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_equiv (equiv.refl α) (assume a, h ▸ iff.rfl) /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This version allows the “inner” predicate to depend on `h : p a`. -/ @[simps] def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ a, ⟨a, a.1.2, by { rcases a with ⟨⟨a, hap⟩, haq⟩, exact haq }⟩, λ a, ⟨⟨a, a.2.fst⟩, a.2.snd⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/ @[simps] def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) : {x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) := (subtype_subtype_equiv_subtype_exists p _).trans $ subtype_equiv_right $ λ x, exists_prop /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ @[simps] def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) : {x : subtype p // q x.1} ≃ subtype q := (subtype_subtype_equiv_subtype_inter p _).trans $ subtype_equiv_right $ λ x, and_iff_right_of_imp h /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ @[simps apply symm_apply] def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) : subtype p ≃ α := ⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : { y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 := ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ ⟨⟨x, h⟩, y⟩, rfl, λ ⟨⟨x, y⟩, h⟩, rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop) (h : ∀ x, p x → q x) : (Σ x : subtype q, p x) ≃ Σ x : α, p x := (subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2 /-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then `Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/ def sigma_subtype_fiber_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop) (h : ∀ x, p (f x)) : (Σ y : subtype p, {x : α // f x = y}) ≃ α := calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x) ... ≃ α : sigma_fiber_equiv f /-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent to `{x // p x}`. -/ def sigma_subtype_fiber_equiv_subtype {α : Type u} {β : Type v} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) : (Σ y : subtype q, {x : α // f x = y}) ≃ subtype p := calc (Σ y : subtype q, {x : α // f x = y}) ≃ Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} : begin apply sigma_congr_right, assume y, symmetry, refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_equiv_right _), assume x, exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩ end ... ≃ subtype p : sigma_fiber_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q)) /-- A sigma type over an `option` is equivalent to the sigma set over the original type, if the fiber is empty at none. -/ def sigma_option_equiv_of_some {α : Type u} (p : option α → Type v) (h : p none → false) : (Σ x : option α, p x) ≃ (Σ x : α, p (some x)) := begin have h' : ∀ x, p x → x.is_some, { intro x, cases x, { intro n, exfalso, exact h n }, { intro s, exact rfl } }, exact (sigma_subtype_equiv_of_subset _ _ h').symm.trans (sigma_congr_left' (option_is_some_equiv α)), end /-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the `sigma` type such that for all `i` we have `(f i).fst = i`. -/ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Π i, π i) ≃ {f : ι → Σ i, π i // ∀ i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ /-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent to the set of functions `Π a, {b : β a // p a b}`. -/ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.ext_val rfl }⟩ /-- A subtype of a product defined by componentwise conditions is equivalent to a product of subtypes. -/ def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} : {c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) := ⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩ /-- A subtype of a `prod` is equivalent to a sigma type whose fibers are subtypes. -/ def subtype_prod_equiv_sigma_subtype {α β : Type*} (p : α → β → Prop) : {x : α × β // p x.1 x.2} ≃ Σ a, {b : β // p a b} := { to_fun := λ x, ⟨x.1.1, x.1.2, x.prop⟩, inv_fun := λ x, ⟨⟨x.1, x.2⟩, x.2.prop⟩, left_inv := λ x, by ext; refl, right_inv := λ ⟨a, b, pab⟩, rfl } /-- The type `Π (i : α), β i` can be split as a product by separating the indices in `α` depending on whether they satisfy a predicate `p` or not. -/ @[simps] def pi_equiv_pi_subtype_prod {α : Type*} (p : α → Prop) (β : α → Type*) [decidable_pred p] : (Π (i : α), β i) ≃ (Π (i : {x // p x}), β i) × (Π (i : {x // ¬ p x}), β i) := { to_fun := λ f, (λ x, f x, λ x, f x), inv_fun := λ f x, if h : p x then f.1 ⟨x, h⟩ else f.2 ⟨x, h⟩, right_inv := begin rintros ⟨f, g⟩, ext1; { ext y, rcases y, simp only [y_property, dif_pos, dif_neg, not_false_iff, subtype.coe_mk], refl }, end, left_inv := λ f, begin ext x, by_cases h : p x; { simp only [h, dif_neg, dif_pos, not_false_iff], refl }, end } end section subtype_equiv_codomain variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X} /-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x` is equivalent to the codomain `Y`. -/ def subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : {g : X → Y // g ∘ coe = f} ≃ Y := (subtype_preimage _ f).trans $ @fun_unique {x' // ¬ x' ≠ x} _ $ show unique {x' // ¬ x' ≠ x}, from @equiv.unique _ _ (show unique {x' // x' = x}, from { default := ⟨x, rfl⟩, uniq := λ ⟨x', h⟩, subtype.val_injective h }) (subtype_equiv_right $ λ a, not_not) @[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : (subtype_equiv_codomain f : {g : X → Y // g ∘ coe = f} → Y) = λ g, (g : X → Y) x := rfl @[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' ≠ x} → Y) (g : {g : X → Y // g ∘ coe = f}) : subtype_equiv_codomain f g = (g : X → Y) x := rfl lemma coe_subtype_equiv_codomain_symm (f : {x' // x' ≠ x} → Y) : ((subtype_equiv_codomain f).symm : Y → {g : X → Y // g ∘ coe = f}) = λ y, ⟨λ x', if h : x' ≠ x then f ⟨x', h⟩ else y, by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl @[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) : ((subtype_equiv_codomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y := rfl @[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' ≠ x} → Y) (y : Y) : ((subtype_equiv_codomain f).symm y : X → Y) x = y := dif_neg (not_not.mpr rfl) lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) (h : x' ≠ x) : ((subtype_equiv_codomain f).symm y : X → Y) x' = f ⟨x', h⟩ := dif_pos h end subtype_equiv_codomain /-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/ @[simps apply] noncomputable def of_bijective (f : α → β) (hf : bijective f) : α ≃ β := { to_fun := f, inv_fun := function.surj_inv hf.surjective, left_inv := function.left_inverse_surj_inv hf, right_inv := function.right_inverse_surj_inv _} lemma of_bijective_apply_symm_apply (f : α → β) (hf : bijective f) (x : β) : f ((of_bijective f hf).symm x) = x := (of_bijective f hf).apply_symm_apply x @[simp] lemma of_bijective_symm_apply_apply (f : α → β) (hf : bijective f) (x : α) : (of_bijective f hf).symm (f x) = x := (of_bijective f hf).symm_apply_apply x instance : can_lift (α → β) (α ≃ β) := { coe := coe_fn, cond := bijective, prf := λ f hf, ⟨of_bijective f hf, rfl⟩ } section variables {α' β' : Type*} (e : perm α') {p : β' → Prop} [decidable_pred p] (f : α' ≃ subtype p) /-- Extend the domain of `e : equiv.perm α` to one that is over `β` via `f : α → subtype p`, where `p : β → Prop`, permuting only the `b : β` that satisfy `p b`. This can be used to extend the domain across a function `f : α → β`, keeping everything outside of `set.range f` fixed. For this use-case `equiv` given by `f` can be constructed by `equiv.of_left_inverse'` or `equiv.of_left_inverse` when there is a known inverse, or `equiv.of_injective` in the general case.`. -/ def perm.extend_domain : perm β' := (perm_congr f e).subtype_congr (equiv.refl _) @[simp] lemma perm.extend_domain_apply_image (a : α') : e.extend_domain f (f a) = f (e a) := by simp [perm.extend_domain] lemma perm.extend_domain_apply_subtype {b : β'} (h : p b) : e.extend_domain f b = f (e (f.symm ⟨b, h⟩)) := by simp [perm.extend_domain, h] lemma perm.extend_domain_apply_not_subtype {b : β'} (h : ¬ p b) : e.extend_domain f b = b := by simp [perm.extend_domain, h] @[simp] lemma perm.extend_domain_refl : perm.extend_domain (equiv.refl _) f = equiv.refl _ := by simp [perm.extend_domain] @[simp] lemma perm.extend_domain_symm : (e.extend_domain f).symm = perm.extend_domain e.symm f := rfl lemma perm.extend_domain_trans (e e' : perm α') : (e.extend_domain f).trans (e'.extend_domain f) = perm.extend_domain (e.trans e') f := by simp [perm.extend_domain, perm_congr_trans] end /-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`. Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/ def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } @[simp] lemma subtype_quotient_equiv_quotient_subtype_mk (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) (x hx) : subtype_quotient_equiv_quotient_subtype p₁ p₂ hp₂ h ⟨⟦x⟧, hx⟩ = ⟦⟨x, (hp₂ _).2 hx⟩⟧ := rfl @[simp] lemma subtype_quotient_equiv_quotient_subtype_symm_mk (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) (x) : (subtype_quotient_equiv_quotient_subtype p₁ p₂ hp₂ h).symm ⟦x⟧ = ⟨⟦x⟧, (hp₂ _).1 x.prop⟩ := rfl section swap variable [decidable_eq α] /-- A helper function for `equiv.swap`. -/ def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ @[simp] theorem swap_self (a : α) : swap a a = equiv.refl _ := ext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := ext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by { by_cases h : b = a; simp [swap_apply_def, h], } theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := ext $ λ x, swap_core_swap_core _ _ _ @[simp] lemma symm_swap (a b : α) : (swap a b).symm = swap a b := rfl @[simp] lemma swap_eq_refl_iff {x y : α} : swap x y = equiv.refl _ ↔ x = y := begin refine ⟨λ h, (equiv.refl _).injective _, λ h, h ▸ (swap_self _)⟩, rw [←h, swap_apply_left, h, refl_apply] end theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by { cases π, refl } lemma swap_eq_update (i j : α) : (equiv.swap i j : α → α) = update (update id j i) i j := funext $ λ x, by rw [update_apply _ i j, update_apply _ j i, equiv.swap_apply_def, id.def] lemma comp_swap_eq_update (i j : α) (f : α → β) : f ∘ equiv.swap i j = update (update f j (f i)) i (f j) := by rw [swap_eq_update, comp_update, comp_update, comp.right_id] @[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma trans_swap_trans_symm [decidable_eq β] (a b : β) (e : α ≃ β) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) := symm_trans_swap_trans a b e.symm @[simp] lemma swap_apply_self (i j a : α) : swap i j (swap i j a) = a := by rw [← equiv.trans_apply, equiv.swap_swap, equiv.refl_apply] /-- A function is invariant to a swap if it is equal at both elements -/ lemma apply_swap_eq_self {v : α → β} {i j : α} (hv : v i = v j) (k : α) : v (swap i j k) = v k := begin by_cases hi : k = i, { rw [hi, swap_apply_left, hv] }, by_cases hj : k = j, { rw [hj, swap_apply_right, hv] }, rw swap_apply_of_ne_of_ne hi hj, end lemma swap_apply_eq_iff {x y z w : α} : swap x y z = w ↔ z = swap x y w := by rw [apply_eq_iff_eq_symm_apply, symm_swap] lemma swap_apply_ne_self_iff {a b x : α} : swap a b x ≠ x ↔ a ≠ b ∧ (x = a ∨ x = b) := begin by_cases hab : a = b, { simp [hab] }, by_cases hax : x = a, { simp [hax, eq_comm] }, by_cases hbx : x = b, { simp [hbx] }, simp [hab, hax, hbx, swap_apply_of_ne_of_ne] end namespace perm @[simp] lemma sum_congr_swap_refl {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : α) : equiv.perm.sum_congr (equiv.swap i j) (equiv.refl β) = equiv.swap (sum.inl i) (sum.inl j) := begin ext x, cases x, { simp [sum.map, swap_apply_def], split_ifs; refl}, { simp [sum.map, swap_apply_of_ne_of_ne] }, end @[simp] lemma sum_congr_refl_swap {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : β) : equiv.perm.sum_congr (equiv.refl α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := begin ext x, cases x, { simp [sum.map, swap_apply_of_ne_of_ne] }, { simp [sum.map, swap_apply_def], split_ifs; refl}, end end perm /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap end equiv namespace function.involutive /-- Convert an involutive function `f` to a permutation with `to_fun = inv_fun = f`. -/ def to_perm (f : α → α) (h : involutive f) : equiv.perm α := ⟨f, f, h.left_inverse, h.right_inverse⟩ @[simp] lemma coe_to_perm {f : α → α} (h : involutive f) : (h.to_perm f : α → α) = f := rfl @[simp] lemma to_perm_symm {f : α → α} (h : involutive f) : (h.to_perm f).symm = h.to_perm f := rfl lemma to_perm_involutive {f : α → α} (h : involutive f) : involutive (h.to_perm f) := h end function.involutive lemma plift.eq_up_iff_down_eq {x : plift α} {y : α} : x = plift.up y ↔ x.down = y := equiv.plift.eq_symm_apply lemma function.injective.map_swap {α β : Type*} [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : f (equiv.swap x y z) = equiv.swap (f x) (f y) (f z) := begin conv_rhs { rw equiv.swap_apply_def }, split_ifs with h₁ h₂, { rw [hf h₁, equiv.swap_apply_left] }, { rw [hf h₂, equiv.swap_apply_right] }, { rw [equiv.swap_apply_of_ne_of_ne (mt (congr_arg f) h₁) (mt (congr_arg f) h₂)] } end namespace equiv protected lemma exists_unique_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∃! x, p x) ↔ ∃! y, q y := begin split, { rintro ⟨a, ha₁, ha₂⟩, exact ⟨f a, h.1 ha₁, λ b hb, f.symm_apply_eq.1 (ha₂ (f.symm b) (h.2 (by simpa using hb)))⟩ }, { rintro ⟨b, hb₁, hb₂⟩, exact ⟨f.symm b, h.2 (by simpa using hb₁), λ y hy, (eq_symm_apply f).2 (hb₂ _ (h.1 hy))⟩ } end protected lemma exists_unique_congr_left' {p : α → Prop} (f : α ≃ β) : (∃! x, p x) ↔ (∃! y, p (f.symm y)) := equiv.exists_unique_congr f (λx, by simp) protected lemma exists_unique_congr_left {p : β → Prop} (f : α ≃ β) : (∃! x, p (f x)) ↔ (∃! y, p y) := (equiv.exists_unique_congr_left' f.symm).symm protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) := begin split; intros h₂ x, { rw [←f.right_inv x], apply h.mp, apply h₂ }, apply h.mpr, apply h₂ end protected lemma forall_congr' {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p (f.symm x) ↔ q x) : (∀x, p x) ↔ (∀y, q y) := (equiv.forall_congr f.symm (λ x, h.symm)).symm -- We next build some higher arity versions of `equiv.forall_congr`. -- Although they appear to just be repeated applications of `equiv.forall_congr`, -- unification of metavariables works better with these versions. -- In particular, they are necessary in `equiv_rw`. -- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics, -- it's rare to have axioms involving more than 3 elements at once.) universes ua1 ua2 ub1 ub2 ug1 ug2 variables {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {γ₁ : Sort ug1} {γ₂ : Sort ug2} protected lemma forall₂_congr {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p x y ↔ q (eα x) (eβ y)) : (∀x y, p x y) ↔ (∀x y, q x y) := begin apply equiv.forall_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₂_congr' {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) : (∀x y, p x y) ↔ (∀x y, q x y) := (equiv.forall₂_congr eα.symm eβ.symm (λ x y, h.symm)).symm protected lemma forall₃_congr {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := begin apply equiv.forall₂_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₃_congr' {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := (equiv.forall₃_congr eα.symm eβ.symm eγ.symm (λ x y z, h.symm)).symm protected lemma forall_congr_left' {p : α → Prop} (f : α ≃ β) : (∀x, p x) ↔ (∀y, p (f.symm y)) := equiv.forall_congr f (λx, by simp) protected lemma forall_congr_left {p : β → Prop} (f : α ≃ β) : (∀x, p (f x)) ↔ (∀y, p y) := (equiv.forall_congr_left' f.symm).symm protected lemma exists_congr_left {α β} (f : α ≃ β) {p : α → Prop} : (∃ a, p a) ↔ (∃ b, p (f.symm b)) := ⟨λ ⟨a, h⟩, ⟨f a, by simpa using h⟩, λ ⟨b, h⟩, ⟨_, h⟩⟩ section variables (P : α → Sort w) (e : α ≃ β) /-- Transport dependent functions through an equivalence of the base space. -/ @[simps] def Pi_congr_left' : (Π a, P a) ≃ (Π b, P (e.symm b)) := { to_fun := λ f x, f (e.symm x), inv_fun := λ f x, begin rw [← e.symm_apply_apply x], exact f (e x) end, left_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { dsimp, rw e.symm_apply_apply })), right_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { rw e.apply_symm_apply })) } end section variables (P : β → Sort w) (e : α ≃ β) /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". -/ def Pi_congr_left : (Π a, P (e a)) ≃ (Π b, P b) := (Pi_congr_left' P e.symm).symm end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π a : α, (W a ≃ Z (h₁ a))) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibers. -/ def Pi_congr : (Π a, W a) ≃ (Π b, Z b) := (equiv.Pi_congr_right h₂).trans (equiv.Pi_congr_left _ h₁) @[simp] lemma coe_Pi_congr_symm : ((h₁.Pi_congr h₂).symm : (Π b, Z b) → (Π a, W a)) = λ f a, (h₂ a).symm (f (h₁ a)) := rfl lemma Pi_congr_symm_apply (f : Π b, Z b) : (h₁.Pi_congr h₂).symm f = λ a, (h₂ a).symm (f (h₁ a)) := rfl @[simp] lemma Pi_congr_apply_apply (f : Π a, W a) (a : α) : h₁.Pi_congr h₂ f (h₁ a) = h₂ a (f a) := begin change cast _ ((h₂ (h₁.symm (h₁ a))) (f (h₁.symm (h₁ a)))) = (h₂ a) (f a), generalize_proofs hZa, revert hZa, rw h₁.symm_apply_apply a, simp, end end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π b : β, (W (h₁.symm b) ≃ Z b)) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def Pi_congr' : (Π a, W a) ≃ (Π b, Z b) := (Pi_congr h₁.symm (λ b, (h₂ b).symm)).symm @[simp] lemma coe_Pi_congr' : (h₁.Pi_congr' h₂ : (Π a, W a) → (Π b, Z b)) = λ f b, h₂ b $ f $ h₁.symm b := rfl lemma Pi_congr'_apply (f : Π a, W a) : h₁.Pi_congr' h₂ f = λ b, h₂ b $ f $ h₁.symm b := rfl @[simp] lemma Pi_congr'_symm_apply_symm_apply (f : Π b, Z b) (b : β) : (h₁.Pi_congr' h₂).symm f (h₁.symm b) = (h₂ b).symm (f b) := begin change cast _ ((h₂ (h₁ (h₁.symm b))).symm (f (h₁ (h₁.symm b)))) = (h₂ b).symm (f b), generalize_proofs hWb, revert hWb, generalize hb : h₁ (h₁.symm b) = b', rw h₁.apply_symm_apply b at hb, subst hb, simp, end end end equiv lemma function.injective.swap_apply [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := begin by_cases hx : z = x, by simp [hx], by_cases hy : z = y, by simp [hy], rw [equiv.swap_apply_of_ne_of_ne hx hy, equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)] end lemma function.injective.swap_comp [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := funext $ λ z, hf.swap_apply _ _ _ /-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/ def subsingleton_prod_self_equiv {α : Type*} [subsingleton α] : α × α ≃ α := { to_fun := λ p, p.1, inv_fun := λ a, (a, a), left_inv := λ p, subsingleton.elim _ _, right_inv := λ p, subsingleton.elim _ _, } /-- To give an equivalence between two subsingleton types, it is sufficient to give any two functions between them. -/ def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β] (f : α → β) (g : β → α) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- A nonempty subsingleton type is (noncomputably) equivalent to `punit`. -/ noncomputable def equiv.punit_of_nonempty_of_subsingleton {α : Sort*} [h : nonempty α] [subsingleton α] : α ≃ punit.{v} := equiv_of_subsingleton_of_subsingleton (λ _, punit.star) (λ _, h.some) /-- `unique (unique α)` is equivalent to `unique α`. -/ def unique_unique_equiv : unique (unique α) ≃ unique α := equiv_of_subsingleton_of_subsingleton (λ h, h.default) (λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }) namespace quot /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : quot ra ≃ quot rb := { to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1), inv_fun := quot.map e.symm (assume b₁ b₂ h, (eq (e.symm b₁) (e.symm b₂)).2 ((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)), left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] }, right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } } @[simp] lemma congr_mk {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀ (a₁ a₂ : α), ra a₁ a₂ ↔ rb (e a₁) (e a₂)) (a : α) : quot.congr e eq (quot.mk ra a) = quot.mk rb (e a) := rfl /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : quot r ≃ quot r' := quot.congr (equiv.refl α) eq /-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α` by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/ protected def congr_left {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := @quot.congr α β r (λ b b', r (e.symm b) (e.symm b')) e (λ a₁ a₂, by simp only [e.symm_apply_apply]) end quot namespace quotient /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) : quotient ra ≃ quotient rb := quot.congr e eq @[simp] lemma congr_mk {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀ (a₁ a₂ : α), setoid.r a₁ a₂ ↔ setoid.r (e a₁) (e a₂)) (a : α): quotient.congr e eq (quotient.mk a) = quotient.mk (e a) := rfl /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : setoid α} (eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' := quot.congr_right eq end quotient namespace function lemma update_comp_equiv {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) : update f a v ∘ g = update (f ∘ g) (g.symm a) v := by rw [← update_comp_eq_of_injective _ g.injective, g.apply_symm_apply] lemma update_apply_equiv_apply {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') : update f a v (g a') = update (f ∘ g) (g.symm a) v a' := congr_fun (update_comp_equiv f g a v) a' lemma Pi_congr_left'_update [decidable_eq α] [decidable_eq β] (P : α → Sort*) (e : α ≃ β) (f : Π a, P a) (b : β) (x : P (e.symm b)) : e.Pi_congr_left' P (update f (e.symm b) x) = update (e.Pi_congr_left' P f) b x := begin ext b', rcases eq_or_ne b' b with rfl | h, { simp, }, { simp [h], }, end lemma Pi_congr_left'_symm_update [decidable_eq α] [decidable_eq β] (P : α → Sort*) (e : α ≃ β) (f : Π b, P (e.symm b)) (b : β) (x : P (e.symm b)) : (e.Pi_congr_left' P).symm (update f b x) = update ((e.Pi_congr_left' P).symm f) (e.symm b) x := by simp [(e.Pi_congr_left' P).symm_apply_eq, Pi_congr_left'_update] end function
24fd3f5ce811a913f9f3d7eae04a6487a8298cee
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/termination_by.lean
5a817b5eef2b7fd7d5fe813191a3bb9530e903b3
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
727
lean
mutual inductive Even : Nat → Prop | base : Even 0 | step : Odd n → Even (n+1) inductive Odd : Nat → Prop | step : Even n → Odd (n+1) end termination_by measure mutual def f (n : Nat) := if n == 0 then 0 else f (n / 2) + 1 termination_by measure end def g' (n : Nat) := match n with | 0 => 1 | n+1 => g' n * 3 termination_by h => measure namespace Test mutual def f : Nat → α → α → α | 0, a, b => a | n+1, a, b => g n a b |>.1 def g : Nat → α → α → (α × α) | 0, a, b => (a, b) | n+1, a, b => (h n a b, a) def h : Nat → α → α → α | 0, a, b => b | n+1, a, b => f n a b end termination_by f => measure g => measure end Test
578f4645df29bee017e77cc4f2d5e65872903151
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/real/hyperreal.lean
ecf22c62f5f256585ef8fea107b4549288096ce7
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
37,204
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir -/ import order.filter.filter_product import analysis.specific_limits /-! # Construction of the hyperreal numbers as an ultraproduct of real sequences. -/ open filter filter.germ open_locale topological_space classical /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ def hyperreal : Type := germ (@hyperfilter ℕ) ℝ namespace hyperreal notation `ℝ*` := hyperreal private def U : is_ultrafilter (@hyperfilter ℕ) := is_ultrafilter_hyperfilter noncomputable instance : discrete_linear_ordered_field ℝ* := germ.discrete_linear_ordered_field U noncomputable instance : inhabited ℝ* := ⟨0⟩ noncomputable instance : has_coe_t ℝ ℝ* := ⟨λ x, (↑x : germ _ _)⟩ @[simp, norm_cast] lemma coe_eq_coe {x y : ℝ} : (x : ℝ*) = y ↔ x = y := germ.const_inj U.1 @[simp, norm_cast] lemma coe_eq_zero {x : ℝ} : (x : ℝ*) = 0 ↔ x = 0 := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one {x : ℝ} : (x : ℝ*) = 1 ↔ x = 1 := coe_eq_coe @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ) = (1 : ℝ*) := rfl @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ) = (0 : ℝ*) := rfl @[simp, norm_cast] lemma coe_inv (x : ℝ) : ↑(x⁻¹) = (x⁻¹ : ℝ*) := rfl @[simp, norm_cast] lemma coe_neg (x : ℝ) : ↑(-x) = (-x : ℝ*) := rfl @[simp, norm_cast] lemma coe_add (x y : ℝ) : ↑(x + y) = (x + y : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit0 (x : ℝ) : ↑(bit0 x) = (bit0 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit1 (x : ℝ) : ↑(bit1 x) = (bit1 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ) : ↑(x * y) = (x * y : ℝ*) := rfl @[simp, norm_cast] lemma coe_div (x y : ℝ) : ↑(x / y) = (x / y : ℝ*) := rfl @[simp, norm_cast] lemma coe_sub (x y : ℝ) : ↑(x - y) = (x - y : ℝ*) := rfl @[simp, norm_cast] lemma coe_lt_coe {x y : ℝ} : (x : ℝ*) < y ↔ x < y := germ.const_lt U @[simp, norm_cast] lemma coe_pos {x : ℝ} : 0 < (x : ℝ*) ↔ 0 < x := coe_lt_coe @[simp, norm_cast] lemma coe_le_coe {x y : ℝ} : (x : ℝ*) ≤ y ↔ x ≤ y := germ.const_le_iff U.1 @[simp, norm_cast] lemma coe_abs (x : ℝ) : ((abs x : ℝ) : ℝ*) = abs x := germ.const_abs _ _ @[simp, norm_cast] lemma coe_max (x y : ℝ) : ((max x y : ℝ) : ℝ*) = max x y := germ.const_max _ _ _ @[simp, norm_cast] lemma coe_min (x y : ℝ) : ((min x y : ℝ) : ℝ*) = min x y := germ.const_min _ _ _ /-- Construct a hyperreal number from a sequence of real numbers. -/ noncomputable def of_seq (f : ℕ → ℝ) : ℝ* := (↑f : germ (@hyperfilter ℕ) ℝ) /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := of_seq $ λ n, n⁻¹ /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := of_seq coe localized "notation `ε` := hyperreal.epsilon" in hyperreal localized "notation `ω` := hyperreal.omega" in hyperreal lemma epsilon_eq_inv_omega : ε = ω⁻¹ := rfl lemma inv_epsilon_eq_omega : ε⁻¹ = ω := @inv_inv' _ _ ω lemma epsilon_pos : 0 < ε := suffices ∀ᶠ i in hyperfilter, (0 : ℝ) < (i : ℕ)⁻¹, by rwa lt_def U, have h0' : {n : ℕ | ¬ n > 0} = {0} := by simp only [not_lt, (set.set_of_eq_eq_singleton).symm]; ext; exact nat.le_zero_iff, begin simp only [inv_pos, nat.cast_pos], exact mem_hyperfilter_of_finite_compl (by convert set.finite_singleton _), end lemma epsilon_ne_zero : ε ≠ 0 := ne_of_gt epsilon_pos lemma omega_pos : 0 < ω := by rw ←inv_epsilon_eq_omega; exact inv_pos.2 epsilon_pos lemma omega_ne_zero : ω ≠ 0 := ne_of_gt omega_pos theorem epsilon_mul_omega : ε * ω = 1 := @inv_mul_cancel _ _ ω omega_ne_zero lemma lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → of_seq f < (r : ℝ*) := begin simp only [metric.tendsto_at_top, dist_zero_right, norm, lt_def U] at hf ⊢, intros r hr, cases hf r hr with N hf', have hs : {i : ℕ | f i < r}ᶜ ⊆ {i : ℕ | i ≤ N} := λ i hi1, le_of_lt (by simp only [lt_iff_not_ge]; exact λ hi2, hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N), exact mem_hyperfilter_of_finite_compl ((set.finite_le_nat N).subset hs) end lemma neg_lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r > 0 → (-r : ℝ*) < of_seq f := λ r hr, have hg : _ := hf.neg, neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr) lemma gt_of_tendsto_zero_of_neg {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r < 0 → (r : ℝ*) < of_seq f := λ r hr, by rw [←neg_neg r, coe_neg]; exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) lemma epsilon_lt_pos (x : ℝ) : 0 < x → ε < x := lt_of_tendsto_zero_of_pos tendsto_inverse_at_top_nhds_0_nat /-- Standard part predicate -/ def is_st (x : ℝ*) (r : ℝ) := ∀ δ : ℝ, 0 < δ → (r - δ : ℝ*) < x ∧ x < r + δ /-- Standard part function: like a "round" to ℝ instead of ℤ -/ noncomputable def st : ℝ* → ℝ := λ x, if h : ∃ r, is_st x r then classical.some h else 0 /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def infinitesimal (x : ℝ*) := is_st x 0 /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def infinite_pos (x : ℝ*) := ∀ r : ℝ, x > r /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def infinite_neg (x : ℝ*) := ∀ r : ℝ, x < r /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def infinite (x : ℝ*) := infinite_pos x ∨ infinite_neg x /-! ### Some facts about `st` -/ private lemma is_st_unique' (x : ℝ*) (r s : ℝ) (hr : is_st x r) (hs : is_st x s) (hrs : r < s) : false := have hrs' : _ := half_pos $ sub_pos_of_lt hrs, have hr' : _ := (hr _ hrs').2, have hs' : _ := (hs _ hrs').1, have h : s - ((s - r) / 2) = r + (s - r) / 2 := by linarith, begin norm_cast at *, rw h at hs', exact not_lt_of_lt hs' hr' end theorem is_st_unique {x : ℝ*} {r s : ℝ} (hr : is_st x r) (hs : is_st x s) : r = s := begin rcases lt_trichotomy r s with h | h | h, { exact false.elim (is_st_unique' x r s hr hs h) }, { exact h }, { exact false.elim (is_st_unique' x s r hs hr h) } end theorem not_infinite_of_exists_st {x : ℝ*} : (∃ r : ℝ, is_st x r) → ¬ infinite x := λ he hi, Exists.dcases_on he $ λ r hr, hi.elim (λ hip, not_lt_of_lt (hr 2 two_pos).2 (hip $ r + 2)) (λ hin, not_lt_of_lt (hr 2 two_pos).1 (hin $ r - 2)) theorem is_st_Sup {x : ℝ*} (hni : ¬ infinite x) : is_st x (Sup {y : ℝ | (y : ℝ*) < x}) := let S : set ℝ := {y : ℝ | (y : ℝ*) < x} in let R : _ := Sup S in have hnile : _ := not_forall.mp (not_or_distrib.mp hni).1, have hnige : _ := not_forall.mp (not_or_distrib.mp hni).2, Exists.dcases_on hnile $ Exists.dcases_on hnige $ λ r₁ hr₁ r₂ hr₂, have HR₁ : ∃ y : ℝ, y ∈ S := ⟨r₁ - 1, lt_of_lt_of_le (coe_lt_coe.2 $ sub_one_lt _) (not_lt.mp hr₁) ⟩, have HR₂ : ∃ z : ℝ, ∀ y ∈ S, y ≤ z := ⟨ r₂, λ y hy, le_of_lt (coe_lt_coe.1 (lt_of_lt_of_le hy (not_lt.mp hr₂))) ⟩, λ δ hδ, ⟨ lt_of_not_ge' $ λ c, have hc : ∀ y ∈ S, y ≤ R - δ := λ y hy, coe_le_coe.1 $ le_of_lt $ lt_of_lt_of_le hy c, not_lt_of_le ((real.Sup_le _ HR₁ HR₂).mpr hc) $ sub_lt_self R hδ, lt_of_not_ge' $ λ c, have hc : ↑(R + δ / 2) < x := lt_of_lt_of_le (add_lt_add_left (coe_lt_coe.2 (half_lt_self hδ)) R) c, not_lt_of_le (real.le_Sup _ HR₂ hc) $ (lt_add_iff_pos_right _).mpr $ half_pos hδ⟩ theorem exists_st_of_not_infinite {x : ℝ*} (hni : ¬ infinite x) : ∃ r : ℝ, is_st x r := ⟨Sup {y : ℝ | (y : ℝ*) < x}, is_st_Sup hni⟩ theorem st_eq_Sup {x : ℝ*} : st x = Sup {y : ℝ | (y : ℝ*) < x} := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) (is_st_Sup (not_infinite_of_exists_st h)) }, { cases not_imp_comm.mp exists_st_of_not_infinite h with H H, { rw (set.ext (λ i, ⟨λ hi, set.mem_univ i, λ hi, H i⟩) : {y : ℝ | (y : ℝ*) < x} = set.univ), exact (real.Sup_univ).symm }, { rw (set.ext (λ i, ⟨λ hi, false.elim (not_lt_of_lt (H i) hi), λ hi, false.elim (set.not_mem_empty i hi)⟩) : {y : ℝ | (y : ℝ*) < x} = ∅), exact (real.Sup_empty).symm } } end theorem exists_st_iff_not_infinite {x : ℝ*} : (∃ r : ℝ, is_st x r) ↔ ¬ infinite x := ⟨ not_infinite_of_exists_st, exists_st_of_not_infinite ⟩ theorem infinite_iff_not_exists_st {x : ℝ*} : infinite x ↔ ¬ ∃ r : ℝ, is_st x r := iff_not_comm.mp exists_st_iff_not_infinite theorem st_infinite {x : ℝ*} (hi : infinite x) : st x = 0 := begin unfold st, split_ifs, { exact false.elim ((infinite_iff_not_exists_st.mp hi) h) }, { refl } end lemma st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : st x = r := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) hxr }, { exact false.elim (h ⟨r, hxr⟩) } end lemma is_st_st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st x (st x) := by rwa [st_of_is_st hxr] lemma is_st_st_of_exists_st {x : ℝ*} (hx : ∃ r : ℝ, is_st x r) : is_st x (st x) := Exists.dcases_on hx (λ r, is_st_st_of_is_st) lemma is_st_st {x : ℝ*} (hx : st x ≠ 0) : is_st x (st x) := begin unfold st, split_ifs, { exact classical.some_spec h }, { exact false.elim (hx (by unfold st; split_ifs; refl)) } end lemma is_st_st' {x : ℝ*} (hx : ¬ infinite x) : is_st x (st x) := is_st_st_of_exists_st $ exists_st_of_not_infinite hx lemma is_st_refl_real (r : ℝ) : is_st r r := λ δ hδ, ⟨ sub_lt_self _ (coe_lt_coe.2 hδ), (lt_add_of_pos_right _ (coe_lt_coe.2 hδ)) ⟩ lemma st_id_real (r : ℝ) : st r = r := st_of_is_st (is_st_refl_real r) lemma eq_of_is_st_real {r s : ℝ} : is_st r s → r = s := is_st_unique (is_st_refl_real r) lemma is_st_real_iff_eq {r s : ℝ} : is_st r s ↔ r = s := ⟨eq_of_is_st_real, λ hrs, by rw [hrs]; exact is_st_refl_real s⟩ lemma is_st_symm_real {r s : ℝ} : is_st r s ↔ is_st s r := by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm] lemma is_st_trans_real {r s t : ℝ} : is_st r s → is_st s t → is_st r t := by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq]; exact eq.trans lemma is_st_inj_real {r₁ r₂ s : ℝ} (h1 : is_st r₁ s) (h2 : is_st r₂ s) : r₁ = r₂ := eq.trans (eq_of_is_st_real h1) (eq_of_is_st_real h2).symm lemma is_st_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : is_st x r ↔ ∀ (δ : ℝ), δ > 0 → abs (x - r) < δ := by simp only [abs_sub_lt_iff, @sub_lt _ _ (r : ℝ*) x _, @sub_lt_iff_lt_add' _ _ x (r : ℝ*) _, and_comm]; refl lemma is_st_add {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x + y) (r + s) := λ hxr hys d hd, have hxr' : _ := hxr (d / 2) (half_pos hd), have hys' : _ := hys (d / 2) (half_pos hd), ⟨by convert add_lt_add hxr'.1 hys'.1 using 1; norm_cast; linarith, by convert add_lt_add hxr'.2 hys'.2 using 1; norm_cast; linarith⟩ lemma is_st_neg {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st (-x) (-r) := λ d hd, by show -(r : ℝ*) - d < -x ∧ -x < -r + d; cases (hxr d hd); split; linarith lemma is_st_sub {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x - y) (r - s) := λ hxr hys, by rw [sub_eq_add_neg, sub_eq_add_neg]; exact is_st_add hxr (is_st_neg hys) /- (st x < st y) → (x < y) → (x ≤ y) → (st x ≤ st y) -/ lemma lt_of_is_st_lt {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : r < s → x < y := λ hrs, have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs), have hxr' : _ := (hxr _ hrs').2, have hys' : _ := (hys _ hrs').1, have H1 : r + ((s - r) / 2) = (r + s) / 2 := by linarith, have H2 : s - ((s - r) / 2) = (r + s) / 2 := by linarith, begin norm_cast at *, rw H1 at hxr', rw H2 at hys', exact lt_trans hxr' hys' end lemma is_st_le_of_le {x y : ℝ*} {r s : ℝ} (hrx : is_st x r) (hsy : is_st y s) : x ≤ y → r ≤ s := by rw [←not_lt, ←not_lt, not_imp_not]; exact lt_of_is_st_lt hsy hrx lemma st_le_of_le {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : x ≤ y → st x ≤ st y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, is_st_le_of_le hx' hy' lemma lt_of_st_lt {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : st x < st y → x < y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, lt_of_is_st_lt hx' hy' /-! ### Basic lemmas about infinite -/ lemma infinite_pos_def {x : ℝ*} : infinite_pos x ↔ ∀ r : ℝ, x > r := by rw iff_eq_eq; refl lemma infinite_neg_def {x : ℝ*} : infinite_neg x ↔ ∀ r : ℝ, x < r := by rw iff_eq_eq; refl lemma ne_zero_of_infinite {x : ℝ*} : infinite x → x ≠ 0 := λ hI h0, or.cases_on hI (λ hip, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_pos 0) 0)) (λ hin, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_neg 0) 0)) lemma not_infinite_zero : ¬ infinite 0 := λ hI, ne_zero_of_infinite hI rfl lemma pos_of_infinite_pos {x : ℝ*} : infinite_pos x → x > 0 := λ hip, hip 0 lemma neg_of_infinite_neg {x : ℝ*} : infinite_neg x → x < 0 := λ hin, hin 0 lemma not_infinite_pos_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinite_pos x := λ hn hp, not_lt_of_lt (hn 1) (hp 1) lemma not_infinite_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinite_neg x := imp_not_comm.mp not_infinite_pos_of_infinite_neg lemma infinite_neg_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → infinite_neg (-x) := λ hp r, neg_lt.mp (hp (-r)) lemma infinite_pos_neg_of_infinite_neg {x : ℝ*} : infinite_neg x → infinite_pos (-x) := λ hp r, lt_neg.mp (hp (-r)) lemma infinite_pos_iff_infinite_neg_neg {x : ℝ*} : infinite_pos x ↔ infinite_neg (-x) := ⟨ infinite_neg_neg_of_infinite_pos, λ hin, neg_neg x ▸ infinite_pos_neg_of_infinite_neg hin ⟩ lemma infinite_neg_iff_infinite_pos_neg {x : ℝ*} : infinite_neg x ↔ infinite_pos (-x) := ⟨ infinite_pos_neg_of_infinite_neg, λ hin, neg_neg x ▸ infinite_neg_neg_of_infinite_pos hin ⟩ lemma infinite_iff_infinite_neg {x : ℝ*} : infinite x ↔ infinite (-x) := ⟨ λ hi, or.cases_on hi (λ hip, or.inr (infinite_neg_neg_of_infinite_pos hip)) (λ hin, or.inl (infinite_pos_neg_of_infinite_neg hin)), λ hi, or.cases_on hi (λ hipn, or.inr (infinite_neg_iff_infinite_pos_neg.mpr hipn)) (λ hinp, or.inl (infinite_pos_iff_infinite_neg_neg.mpr hinp))⟩ lemma not_infinite_of_infinitesimal {x : ℝ*} : infinitesimal x → ¬ infinite x := λ hi hI, have hi' : _ := (hi 2 two_pos), or.dcases_on hI (λ hip, have hip' : _ := hip 2, not_lt_of_lt hip' (by convert hi'.2; exact (zero_add 2).symm)) (λ hin, have hin' : _ := hin (-2), not_lt_of_lt hin' (by convert hi'.1; exact (zero_sub 2).symm)) lemma not_infinitesimal_of_infinite {x : ℝ*} : infinite x → ¬ infinitesimal x := imp_not_comm.mp not_infinite_of_infinitesimal lemma not_infinitesimal_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinitesimal x := λ hp, not_infinitesimal_of_infinite (or.inl hp) lemma not_infinitesimal_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinitesimal x := λ hn, not_infinitesimal_of_infinite (or.inr hn) lemma infinite_pos_iff_infinite_and_pos {x : ℝ*} : infinite_pos x ↔ (infinite x ∧ x > 0) := ⟨ λ hip, ⟨or.inl hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hip, hip) (λ hin, false.elim (not_lt_of_lt hp (hin 0))) ⟩ lemma infinite_neg_iff_infinite_and_neg {x : ℝ*} : infinite_neg x ↔ (infinite x ∧ x < 0) := ⟨ λ hip, ⟨or.inr hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hin, false.elim (not_lt_of_lt hp (hin 0))) (λ hip, hip) ⟩ lemma infinite_pos_iff_infinite_of_pos {x : ℝ*} (hp : x > 0) : infinite_pos x ↔ infinite x := by rw [infinite_pos_iff_infinite_and_pos]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hp⟩⟩ lemma infinite_pos_iff_infinite_of_nonneg {x : ℝ*} (hp : x ≥ 0) : infinite_pos x ↔ infinite x := or.cases_on (lt_or_eq_of_le hp) (infinite_pos_iff_infinite_of_pos) (λ h, by rw h.symm; exact ⟨λ hIP, false.elim (not_infinite_zero (or.inl hIP)), λ hI, false.elim (not_infinite_zero hI)⟩) lemma infinite_neg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : infinite_neg x ↔ infinite x := by rw [infinite_neg_iff_infinite_and_neg]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hn⟩⟩ lemma infinite_pos_abs_iff_infinite_abs {x : ℝ*} : infinite_pos (abs x) ↔ infinite (abs x) := infinite_pos_iff_infinite_of_nonneg (abs_nonneg _) lemma infinite_iff_infinite_pos_abs {x : ℝ*} : infinite x ↔ infinite_pos (abs x) := ⟨ λ hi d, or.cases_on hi (λ hip, by rw [abs_of_pos (hip 0)]; exact hip d) (λ hin, by rw [abs_of_neg (hin 0)]; exact lt_neg.mp (hin (-d))), λ hipa, by { rcases (lt_trichotomy x 0) with h | h | h, { exact or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa abs_of_neg h at hipa)) }, { exact false.elim (ne_zero_of_infinite (or.inl (by rw [h]; rwa [h, abs_zero] at hipa)) h) }, { exact or.inl (by rwa abs_of_pos h at hipa) } } ⟩ lemma infinite_iff_infinite_abs {x : ℝ*} : infinite x ↔ infinite (abs x) := by rw [←infinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs] lemma infinite_iff_abs_lt_abs {x : ℝ*} : infinite x ↔ ∀ r : ℝ, (abs r : ℝ*) < abs x := ⟨ λ hI r, (coe_abs r) ▸ infinite_iff_infinite_pos_abs.mp hI (abs r), λ hR, or.cases_on (max_choice x (-x)) (λ h, or.inl $ λ r, lt_of_le_of_lt (le_abs_self _) (h ▸ (hR r))) (λ h, or.inr $ λ r, neg_lt_neg_iff.mp $ lt_of_le_of_lt (neg_le_abs_self _) (h ▸ (hR r)))⟩ lemma infinite_pos_add_not_infinite_neg {x y : ℝ*} : infinite_pos x → ¬ infinite_neg y → infinite_pos (x + y) := begin intros hip hnin r, cases not_forall.mp hnin with r₂ hr₂, convert add_lt_add_of_lt_of_le (hip (r + -r₂)) (not_lt.mp hr₂) using 1, simp end lemma not_infinite_neg_add_infinite_pos {x y : ℝ*} : ¬ infinite_neg x → infinite_pos y → infinite_pos (x + y) := λ hx hy, by rw [add_comm]; exact infinite_pos_add_not_infinite_neg hy hx lemma infinite_neg_add_not_infinite_pos {x y : ℝ*} : infinite_neg x → ¬ infinite_pos y → infinite_neg (x + y) := by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y, @infinite_neg_iff_infinite_pos_neg (x + y), neg_add]; exact infinite_pos_add_not_infinite_neg lemma not_infinite_pos_add_infinite_neg {x y : ℝ*} : ¬ infinite_pos x → infinite_neg y → infinite_neg (x + y) := λ hx hy, by rw [add_comm]; exact infinite_neg_add_not_infinite_pos hy hx lemma infinite_pos_add_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_infinite_neg_of_infinite_pos hy) lemma infinite_neg_add_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_infinite_pos_of_infinite_neg hy) lemma infinite_pos_add_not_infinite {x y : ℝ*} : infinite_pos x → ¬ infinite y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_or_distrib.mp hy).2 lemma infinite_neg_add_not_infinite {x y : ℝ*} : infinite_neg x → ¬ infinite y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_or_distrib.mp hy).1 theorem infinite_pos_of_tendsto_top {f : ℕ → ℝ} (hf : tendsto f at_top at_top) : infinite_pos (of_seq f) := λ r, have hf' : _ := (tendsto_at_top_at_top _).mp hf, Exists.cases_on (hf' (r + 1)) $ λ i hi, have hi' : ∀ (a : ℕ), f a < (r + 1) → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | r < f a}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))), (germ.coe_lt U).2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS theorem infinite_neg_of_tendsto_bot {f : ℕ → ℝ} (hf : tendsto f at_top at_bot) : infinite_neg (of_seq f) := λ r, have hf' : _ := (tendsto_at_top_at_bot _).mp hf, Exists.cases_on (hf' (r - 1)) $ λ i hi, have hi' : ∀ (a : ℕ), r - 1 < f a → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | f a < r}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)), (germ.coe_lt U).2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS lemma not_infinite_neg {x : ℝ*} : ¬ infinite x → ¬ infinite (-x) := not_imp_not.mpr infinite_iff_infinite_neg.mpr lemma not_infinite_add {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x + y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s + r, is_st_add hs hr⟩ theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : ¬ infinite x ↔ ∃ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨ λ hni, Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).1) $ Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).2) $ λ r hr s hs, by rw [not_lt] at hr hs; exact ⟨r - 1, s + 1, ⟨ lt_of_lt_of_le (by rw sub_eq_add_neg; norm_num) hr, lt_of_le_of_lt hs (by norm_num)⟩ ⟩, λ hrs, Exists.dcases_on hrs $ λ r hr, Exists.dcases_on hr $ λ s hs, not_or_distrib.mpr ⟨not_forall.mpr ⟨s, lt_asymm (hs.2)⟩, not_forall.mpr ⟨r, lt_asymm (hs.1) ⟩⟩⟩ theorem not_infinite_real (r : ℝ) : ¬ infinite r := by rw not_infinite_iff_exist_lt_gt; exact ⟨ r - 1, r + 1, coe_lt_coe.2 $ sub_one_lt r, coe_lt_coe.2 $ lt_add_one r⟩ theorem not_real_of_infinite {x : ℝ*} : infinite x → ∀ r : ℝ, x ≠ r := λ hi r hr, not_infinite_real r $ @eq.subst _ infinite _ _ hr hi /-! ### Facts about `st` that require some infinite machinery -/ private lemma is_st_mul' {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) (hs : s ≠ 0) : is_st (x * y) (r * s) := have hxr' : _ := is_st_iff_abs_sub_lt_delta.mp hxr, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys, have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, is_st_iff_abs_sub_lt_delta.mpr $ λ d hd, calc abs (x * y - r * s) = abs (x * (y - s) + (x - r) * s) : by rw [mul_sub, sub_mul, add_sub, sub_add_cancel] ... ≤ abs (x * (y - s)) + abs ((x - r) * s) : abs_add _ _ ... ≤ abs x * abs (y - s) + abs (x - r) * abs s : by simp only [abs_mul] ... ≤ abs x * ((d / t) / 2 : ℝ) + ((d / abs s) / 2 : ℝ) * abs s : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt $ hys' _ $ half_pos $ div_pos hd $ coe_pos.1 $ lt_of_le_of_lt (abs_nonneg x) ht) $ abs_nonneg _) (mul_le_mul_of_nonneg_right (le_of_lt $ hxr' _ $ half_pos $ div_pos hd $ abs_pos_of_ne_zero hs) $ abs_nonneg _) ... = (d / 2 * (abs x / t) + d / 2 : ℝ*) : by { push_cast, have : (abs s : ℝ*) ≠ 0, by simpa, field_simp [this, @two_ne_zero ℝ* _, add_mul, mul_add, mul_assoc, mul_comm, mul_left_comm] } ... < (d / 2 * 1 + d / 2 : ℝ*) : add_lt_add_right (mul_lt_mul_of_pos_left ((div_lt_one_iff_lt $ lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) $ half_pos $ coe_pos.2 hd) _ ... = (d : ℝ*) : by rw [mul_one, add_halves] lemma is_st_mul {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : is_st (x * y) (r * s) := have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, begin by_cases hs : s = 0, { apply is_st_iff_abs_sub_lt_delta.mpr, intros d hd, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t) (div_pos hd (coe_pos.1 (lt_of_le_of_lt (abs_nonneg x) ht))), rw [hs, coe_zero, sub_zero] at hys', rw [hs, mul_zero, coe_zero, sub_zero, abs_mul, mul_comm, ←div_mul_cancel (d : ℝ*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)), ←coe_div], exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) }, exact is_st_mul' hxr hys hs, end --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY lemma not_infinite_mul {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x * y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s * r, is_st_mul hs hr⟩ --- lemma st_add {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x + y) = st x + st y := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_add hx hy), have hxy' : _ := is_st_add hx' hy', is_st_unique hxy hxy' lemma st_neg (x : ℝ*) : st (-x) = - st x := if h : infinite x then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero] else is_st_unique (is_st_st' (not_infinite_neg h)) (is_st_neg (is_st_st' h)) lemma st_mul {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x * y) = (st x) * (st y) := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_mul hx hy), have hxy' : _ := is_st_mul hx' hy', is_st_unique hxy hxy' /-! ### Basic lemmas about infinitesimal -/ theorem infinitesimal_def {x : ℝ*} : infinitesimal x ↔ (∀ r : ℝ, 0 < r → -(r : ℝ*) < x ∧ x < r) := ⟨ λ hi r hr, by { convert (hi r hr); simp }, λ hi d hd, by { convert (hi d hd); simp } ⟩ theorem lt_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r > 0 → x < r := λ hi r hr, ((infinitesimal_def.mp hi) r hr).2 theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r > 0 → x > -r := λ hi r hr, ((infinitesimal_def.mp hi) r hr).1 theorem gt_of_neg_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r < 0 → x > r := λ hi r hr, by convert ((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1; exact (neg_neg ↑r).symm theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : infinitesimal x ↔ ∀ r : ℝ, r ≠ 0 → abs x < abs r := ⟨ λ hi r hr, abs_lt.mpr (by rw ←coe_abs; exact infinitesimal_def.mp hi (abs r) (abs_pos_of_ne_zero hr)), λ hR, infinitesimal_def.mpr $ λ r hr, abs_lt.mp $ (abs_of_pos $ coe_pos.2 hr) ▸ hR r $ ne_of_gt hr ⟩ lemma infinitesimal_zero : infinitesimal 0 := is_st_refl_real 0 lemma zero_of_infinitesimal_real {r : ℝ} : infinitesimal r → r = 0 := eq_of_is_st_real lemma zero_iff_infinitesimal_real {r : ℝ} : infinitesimal r ↔ r = 0 := ⟨zero_of_infinitesimal_real, λ hr, by rw hr; exact infinitesimal_zero⟩ lemma infinitesimal_add {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x + y) := by simpa only [add_zero] using is_st_add hx hy lemma infinitesimal_neg {x : ℝ*} (hx : infinitesimal x) : infinitesimal (-x) := by simpa only [neg_zero] using is_st_neg hx lemma infinitesimal_neg_iff {x : ℝ*} : infinitesimal x ↔ infinitesimal (-x) := ⟨infinitesimal_neg, λ h, (neg_neg x) ▸ @infinitesimal_neg (-x) h⟩ lemma infinitesimal_mul {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x * y) := by simpa only [mul_zero] using is_st_mul hx hy theorem infinitesimal_of_tendsto_zero {f : ℕ → ℝ} : tendsto f at_top (𝓝 0) → infinitesimal (of_seq f) := λ hf d hd, by rw [sub_eq_add_neg, ←coe_neg, ←coe_add, ←coe_add, zero_add, zero_add]; exact ⟨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hd⟩ theorem infinitesimal_epsilon : infinitesimal ε := infinitesimal_of_tendsto_zero tendsto_inverse_at_top_nhds_0_nat lemma not_real_of_infinitesimal_ne_zero (x : ℝ*) : infinitesimal x → x ≠ 0 → ∀ r : ℝ, x ≠ r := λ hi hx r hr, hx $ hr.trans $ coe_eq_zero.2 $ is_st_unique (hr.symm ▸ is_st_refl_real r : is_st x r) hi theorem infinitesimal_sub_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : infinitesimal (x - r) := show is_st (x + -r) 0, by rw ←add_neg_self r; exact is_st_add hxr (is_st_refl_real (-r)) theorem infinitesimal_sub_st {x : ℝ*} (hx : ¬infinite x) : infinitesimal (x - st x) := infinitesimal_sub_is_st $ is_st_st' hx lemma infinite_pos_iff_infinitesimal_inv_pos {x : ℝ*} : infinite_pos x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ > 0) := ⟨ λ hip, ⟨ infinitesimal_def.mpr $ λ r hr, ⟨ lt_trans (coe_lt_coe.2 (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)), (inv_lt (coe_lt_coe.2 hr) (hip 0)).mp (by convert hip r⁻¹) ⟩, inv_pos.2 $ hip 0 ⟩, λ ⟨hi, hp⟩ r, @classical.by_cases (r = 0) (x > (r : ℝ*)) (λ h, eq.substr h (inv_pos.mp hp)) $ λ h, lt_of_le_of_lt (coe_le_coe.2 (le_abs_self r)) ((inv_lt_inv (inv_pos.mp hp) (coe_lt_coe.2 (abs_pos_of_ne_zero h))).mp ((infinitesimal_def.mp hi) ((abs r)⁻¹) (inv_pos.2 (abs_pos_of_ne_zero h))).2) ⟩ lemma infinite_neg_iff_infinitesimal_inv_neg {x : ℝ*} : infinite_neg x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ < 0) := ⟨ λ hin, have hin' : _ := infinite_pos_iff_infinitesimal_inv_pos.mp (infinite_pos_neg_of_infinite_neg hin), by rwa [infinitesimal_neg_iff, ←neg_pos, neg_inv], λ hin, have h0 : x ≠ 0 := λ h0, (lt_irrefl (0 : ℝ*) (by convert hin.2; rw [h0, inv_zero])), by rwa [←neg_pos, infinitesimal_neg_iff, neg_inv, ←infinite_pos_iff_infinitesimal_inv_pos, ←infinite_neg_iff_infinite_pos_neg] at hin ⟩ theorem infinitesimal_inv_of_infinite {x : ℝ*} : infinite x → infinitesimal x⁻¹ := λ hi, or.cases_on hi (λ hip, (infinite_pos_iff_infinitesimal_inv_pos.mp hip).1) (λ hin, (infinite_neg_iff_infinitesimal_inv_neg.mp hin).1) theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) (hi : infinitesimal x⁻¹ ) : infinite x := begin cases (lt_or_gt_of_ne h0) with hn hp, { exact or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_lt_zero.mpr hn⟩) }, { exact or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos.mpr hp⟩) } end theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) : infinite x ↔ infinitesimal x⁻¹ := ⟨ infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0 ⟩ lemma infinitesimal_pos_iff_infinite_pos_inv {x : ℝ*} : infinite_pos x⁻¹ ↔ (infinitesimal x ∧ x > 0) := by convert infinite_pos_iff_infinitesimal_inv_pos; simp only [inv_inv'] lemma infinitesimal_neg_iff_infinite_neg_inv {x : ℝ*} : infinite_neg x⁻¹ ↔ (infinitesimal x ∧ x < 0) := by convert infinite_neg_iff_infinitesimal_inv_neg; simp only [inv_inv'] theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x ≠ 0) : infinitesimal x ↔ infinite x⁻¹ := by convert (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm; simp only [inv_inv'] /-! ### `st` stuff that requires infinitesimal machinery -/ theorem is_st_of_tendsto {f : ℕ → ℝ} {r : ℝ} (hf : tendsto f at_top (𝓝 r)) : is_st (of_seq f) r := have hg : tendsto (λ n, f n - r) at_top (𝓝 0) := (sub_self r) ▸ (hf.sub tendsto_const_nhds), by rw [←(zero_add r), ←(sub_add_cancel f (λ n, r))]; exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r) lemma is_st_inv {x : ℝ*} {r : ℝ} (hi : ¬ infinitesimal x) : is_st x r → is_st x⁻¹ r⁻¹ := λ hxr, have h : x ≠ 0 := (λ h, hi (h.symm ▸ infinitesimal_zero)), have H : _ := exists_st_of_not_infinite $ not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi, Exists.cases_on H $ λ s hs, have H' : is_st 1 (r * s) := mul_inv_cancel h ▸ is_st_mul hxr hs, have H'' : s = r⁻¹ := one_div_eq_inv r ▸ eq_one_div_of_mul_eq_one (eq_of_is_st_real H').symm, H'' ▸ hs lemma st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := begin by_cases h0 : x = 0, rw [h0, inv_zero, ←coe_zero, st_id_real, inv_zero], by_cases h1 : infinitesimal x, rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero], by_cases h2 : infinite x, rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero], exact st_of_is_st (is_st_inv h1 (is_st_st' h2)), end /-! ### Infinite stuff that requires infinitesimal machinery -/ lemma infinite_pos_omega : infinite_pos ω := infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ lemma infinite_omega : infinite ω := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon lemma infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → y > 0 → infinite_pos (x * y) := λ hx hy₁ hy₂ r, have hy₁' : _ := not_forall.mp (by rw infinitesimal_def at hy₁; exact hy₁), Exists.dcases_on hy₁' $ λ r₁ hy₁'', have hyr : _ := by rw [not_imp, ←abs_lt, not_lt, abs_of_pos hy₂] at hy₁''; exact hy₁'', by rw [←div_mul_cancel r (ne_of_gt hyr.1), coe_mul]; exact mul_lt_mul (hx (r / r₁)) hyr.2 (coe_lt_coe.2 hyr.1) (le_of_lt (hx 0)) lemma infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_pos y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → y < 0 → infinite_pos (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, ←neg_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_neg y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → y < 0 → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_pos y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → 0 < y → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → x > 0 → infinite_neg y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_neg_mul_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_pos_mul_infinite_neg {x y : ℝ*} : infinite_pos x → infinite_neg y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_neg_mul_infinite_pos {x y : ℝ*} : infinite_neg x → infinite_pos y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : infinite x → ¬ infinitesimal y → infinite (x * y) := λ hx hy, have h0 : y < 0 ∨ y > 0 := lt_or_gt_of_ne (λ H0, hy (eq.substr H0 (is_st_refl_real 0))), or.dcases_on hx (or.dcases_on h0 (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hx hy H0))) (or.dcases_on h0 (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hx hy H0))) lemma infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : ¬ infinitesimal x → infinite y → infinite (x * y) := λ hx hy, by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx lemma infinite_mul_infinite {x y : ℝ*} : infinite x → infinite y → infinite (x * y) := λ hx hy, infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy) end hyperreal
46812b74955e35f161379e1041b9ca09b764ce5a
ce40a712ea5395b5e4eb6388d6ec7cbe44a2cc0d
/zsh-zimfw/.p10k.zsh.lean
31020be0101b2a6aa76e39ec64f8fe94f5a0c7ff
[]
no_license
dcabooter/tools
f24a6bf7e44a2506f941f763040ca80fbc8230c6
18cc9665ab79c51df375aa0c19baf3dbd0ac26ac
refs/heads/main
1,651,240,778,324
1,649,322,811,000
1,649,322,811,000
247,667,259
0
1
null
null
null
null
UTF-8
Lean
false
false
82,921
lean
# Generated by Powerlevel10k configuration wizard on 2021-03-04 at 11:24 CET. # Based on romkatv/powerlevel10k/config/p10k-lean.zsh, checksum 9871. # Wizard options: nerdfont-complete + powerline, small icons, unicode, lean, 24h time, # 2 lines, disconnected, left frame, lightest-ornaments, sparse, many icons, fluent, # transient_prompt, instant_prompt=verbose. # Type `p10k configure` to generate another config. # # Config for Powerlevel10k with lean prompt style. Type `p10k configure` to generate # your own config based on it. # # Tip: Looking for a nice color? Here's a one-liner to print colormap. # # for i in {0..255}; do print -Pn "%K{$i} %k%F{$i}${(l:3::0:)i}%f " ${${(M)$((i%6)):#3}:+$'\n'}; done # Temporarily change options. 'builtin' 'local' '-a' 'p10k_config_opts' [[ ! -o 'aliases' ]] || p10k_config_opts+=('aliases') [[ ! -o 'sh_glob' ]] || p10k_config_opts+=('sh_glob') [[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand') 'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' () { emulate -L zsh -o extended_glob # Unset all configuration options. This allows you to apply configuration changes without # restarting zsh. Edit ~/.p10k.zsh and type `source ~/.p10k.zsh`. unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR' # Zsh >= 5.1 is required. autoload -Uz is-at-least && is-at-least 5.1 || return # The list of segments shown on the left. Fill it with the most important segments. typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=( # =========================[ Line #1 ]========================= os_icon # os identifier dir # current directory vcs # git status # =========================[ Line #2 ]========================= newline # \n prompt_char # prompt symbol ) # The list of segments shown on the right. Fill it with less important segments. # Right prompt on the last prompt line (where you are typing your commands) gets # automatically hidden when the input line reaches it. Right prompt above the # last prompt line gets hidden if it would overlap with left prompt. typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=( # =========================[ Line #1 ]========================= status # exit code of the last command command_execution_time # duration of the last command background_jobs # presence of background jobs direnv # direnv status (https://direnv.net/) asdf # asdf version manager (https://github.com/asdf-vm/asdf) virtualenv # python virtual environment (https://docs.python.org/3/library/venv.html) anaconda # conda environment (https://conda.io/) pyenv # python environment (https://github.com/pyenv/pyenv) goenv # go environment (https://github.com/syndbg/goenv) nodenv # node.js version from nodenv (https://github.com/nodenv/nodenv) nvm # node.js version from nvm (https://github.com/nvm-sh/nvm) nodeenv # node.js environment (https://github.com/ekalinin/nodeenv) # node_version # node.js version # go_version # go version (https://golang.org) # rust_version # rustc version (https://www.rust-lang.org) # dotnet_version # .NET version (https://dotnet.microsoft.com) # php_version # php version (https://www.php.net/) # laravel_version # laravel php framework version (https://laravel.com/) # java_version # java version (https://www.java.com/) # package # name@version from package.json (https://docs.npmjs.com/files/package.json) rbenv # ruby version from rbenv (https://github.com/rbenv/rbenv) rvm # ruby version from rvm (https://rvm.io) fvm # flutter version management (https://github.com/leoafarias/fvm) luaenv # lua version from luaenv (https://github.com/cehoffman/luaenv) jenv # java version from jenv (https://github.com/jenv/jenv) plenv # perl version from plenv (https://github.com/tokuhirom/plenv) phpenv # php version from phpenv (https://github.com/phpenv/phpenv) scalaenv # scala version from scalaenv (https://github.com/scalaenv/scalaenv) haskell_stack # haskell version from stack (https://haskellstack.org/) kubecontext # current kubernetes context (https://kubernetes.io/) terraform # terraform workspace (https://www.terraform.io) aws # aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) aws_eb_env # aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) azure # azure account name (https://docs.microsoft.com/en-us/cli/azure) gcloud # google cloud cli account and project (https://cloud.google.com/) google_app_cred # google application credentials (https://cloud.google.com/docs/authentication/production) context # user@hostname nordvpn # nordvpn connection status, linux only (https://nordvpn.com/) ranger # ranger shell (https://github.com/ranger/ranger) nnn # nnn shell (https://github.com/jarun/nnn) vim_shell # vim shell indicator (:sh) midnight_commander # midnight commander shell (https://midnight-commander.org/) nix_shell # nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) # vpn_ip # virtual private network indicator # load # CPU load # disk_usage # disk usage # ram # free RAM # swap # used swap todo # todo items (https://github.com/todotxt/todo.txt-cli) timewarrior # timewarrior tracking status (https://timewarrior.net/) taskwarrior # taskwarrior task count (https://taskwarrior.org/) time # current time # =========================[ Line #2 ]========================= newline # ip # ip address and bandwidth usage for a specified network interface # public_ip # public IP address # proxy # system-wide http/https/ftp proxy # battery # internal battery # wifi # wifi speed # example # example user-defined segment (see prompt_example function below) ) # Defines character set used by powerlevel10k. It's best to let `p10k configure` set it for you. typeset -g POWERLEVEL9K_MODE=nerdfont-complete # When set to `moderate`, some icons will have an extra space after them. This is meant to avoid # icon overlap when using non-monospace fonts. When set to `none`, spaces are not added. typeset -g POWERLEVEL9K_ICON_PADDING=none # Basic style options that define the overall look of your prompt. You probably don't want to # change them. typeset -g POWERLEVEL9K_BACKGROUND= # transparent background typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE= # no surrounding whitespace typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' ' # separate segments with a space typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR= # no end-of-line symbol # When set to true, icons appear before content on both sides of the prompt. When set # to false, icons go after content. If empty or not set, icons go before content in the left # prompt and after content in the right prompt. # # You can also override it for a specific segment: # # POWERLEVEL9K_STATUS_ICON_BEFORE_CONTENT=false # # Or for a specific segment in specific state: # # POWERLEVEL9K_DIR_NOT_WRITABLE_ICON_BEFORE_CONTENT=false typeset -g POWERLEVEL9K_ICON_BEFORE_CONTENT=true # Add an empty line before each prompt. typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true # Connect left prompt lines with these symbols. typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX='%244F╭─' typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_PREFIX='%244F├─' typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX='%244F╰─' # Connect right prompt lines with these symbols. typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX= typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX= typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX= # The left end of left prompt. typeset -g POWERLEVEL9K_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL=' ' # The right end of right prompt. typeset -g POWERLEVEL9K_RIGHT_PROMPT_LAST_SEGMENT_END_SYMBOL= # Ruler, a.k.a. the horizontal line before each prompt. If you set it to true, you'll # probably want to set POWERLEVEL9K_PROMPT_ADD_NEWLINE=false above and # POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' below. typeset -g POWERLEVEL9K_SHOW_RULER=false typeset -g POWERLEVEL9K_RULER_CHAR='─' # reasonable alternative: '·' typeset -g POWERLEVEL9K_RULER_FOREGROUND=244 # Filler between left and right prompt on the first prompt line. You can set it to '·' or '─' # to make it easier to see the alignment between left and right prompt and to separate prompt # from command output. It serves the same purpose as ruler (see above) without increasing # the number of prompt lines. You'll probably want to set POWERLEVEL9K_SHOW_RULER=false # if using this. You might also like POWERLEVEL9K_PROMPT_ADD_NEWLINE=false for more compact # prompt. typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' if [[ $POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR != ' ' ]]; then # The color of the filler. typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND=244 # Add a space between the end of left prompt and the filler. typeset -g POWERLEVEL9K_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=' ' # Add a space between the filler and the start of right prompt. typeset -g POWERLEVEL9K_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL=' ' # Start filler from the edge of the screen if there are no left segments on the first line. typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_FIRST_SEGMENT_END_SYMBOL='%{%}' # End filler on the edge of the screen if there are no right segments on the first line. typeset -g POWERLEVEL9K_EMPTY_LINE_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='%{%}' fi #################################[ os_icon: os identifier ]################################## # OS identifier color. typeset -g POWERLEVEL9K_OS_ICON_FOREGROUND= # Custom icon. # typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='⭐' ################################[ prompt_char: prompt symbol ]################################ # Green prompt symbol if the last command succeeded. typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=76 # Red prompt symbol if the last command failed. typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=196 # Default prompt symbol. typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='❯' # Prompt symbol in command vi mode. typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='❮' # Prompt symbol in visual vi mode. typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='V' # Prompt symbol in overwrite vi mode. typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIOWR_CONTENT_EXPANSION='▶' typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=true # No line terminator if prompt_char is the last segment. typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL='' # No line introducer if prompt_char is the first segment. typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= ##################################[ dir: current directory ]################################## # Default current directory color. typeset -g POWERLEVEL9K_DIR_FOREGROUND=31 # If directory is too long, shorten some of its segments to the shortest possible unique # prefix. The shortened directory can be tab-completed to the original. typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_unique # Replace removed segment suffixes with this symbol. typeset -g POWERLEVEL9K_SHORTEN_DELIMITER= # Color of the shortened directory segments. typeset -g POWERLEVEL9K_DIR_SHORTENED_FOREGROUND=103 # Color of the anchor directory segments. Anchor segments are never shortened. The first # segment is always an anchor. typeset -g POWERLEVEL9K_DIR_ANCHOR_FOREGROUND=39 # Display anchor directory segments in bold. typeset -g POWERLEVEL9K_DIR_ANCHOR_BOLD=true # Don't shorten directories that contain any of these files. They are anchors. local anchor_files=( .bzr .citc .git .hg .node-version .python-version .go-version .ruby-version .lua-version .java-version .perl-version .php-version .tool-version .shorten_folder_marker .svn .terraform CVS Cargo.toml composer.json go.mod package.json stack.yaml ) typeset -g POWERLEVEL9K_SHORTEN_FOLDER_MARKER="(${(j:|:)anchor_files})" # If set to "first" ("last"), remove everything before the first (last) subdirectory that contains # files matching $POWERLEVEL9K_SHORTEN_FOLDER_MARKER. For example, when the current directory is # /foo/bar/git_repo/nested_git_repo/baz, prompt will display git_repo/nested_git_repo/baz (first) # or nested_git_repo/baz (last). This assumes that git_repo and nested_git_repo contain markers # and other directories don't. # # Optionally, "first" and "last" can be followed by ":<offset>" where <offset> is an integer. # This moves the truncation point to the right (positive offset) or to the left (negative offset) # relative to the marker. Plain "first" and "last" are equivalent to "first:0" and "last:0" # respectively. typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=false # Don't shorten this many last directory segments. They are anchors. typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1 # Shorten directory if it's longer than this even if there is space for it. The value can # be either absolute (e.g., '80') or a percentage of terminal width (e.g, '50%'). If empty, # directory will be shortened only when prompt doesn't fit or when other parameters demand it # (see POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS and POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT below). # If set to `0`, directory will always be shortened to its minimum length. typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=80 # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least this # many columns for typing commands. typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS=40 # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least # COLUMNS * POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT * 0.01 columns for typing commands. typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT=50 # If set to true, embed a hyperlink into the directory. Useful for quickly # opening a directory in the file manager simply by clicking the link. # Can also be handy when the directory is shortened, as it allows you to see # the full directory that was used in previous commands. typeset -g POWERLEVEL9K_DIR_HYPERLINK=false # Enable special styling for non-writable and non-existent directories. See POWERLEVEL9K_LOCK_ICON # and POWERLEVEL9K_DIR_CLASSES below. typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v3 # The default icon shown next to non-writable and non-existent directories when # POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3. # typeset -g POWERLEVEL9K_LOCK_ICON='⭐' # POWERLEVEL9K_DIR_CLASSES allows you to specify custom icons and colors for different # directories. It must be an array with 3 * N elements. Each triplet consists of: # # 1. A pattern against which the current directory ($PWD) is matched. Matching is done with # extended_glob option enabled. # 2. Directory class for the purpose of styling. # 3. An empty string. # # Triplets are tried in order. The first triplet whose pattern matches $PWD wins. # # If POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3, non-writable and non-existent directories # acquire class suffix _NOT_WRITABLE and NON_EXISTENT respectively. # # For example, given these settings: # # typeset -g POWERLEVEL9K_DIR_CLASSES=( # '~/work(|/*)' WORK '' # '~(|/*)' HOME '' # '*' DEFAULT '') # # Whenever the current directory is ~/work or a subdirectory of ~/work, it gets styled with one # of the following classes depending on its writability and existence: WORK, WORK_NOT_WRITABLE or # WORK_NON_EXISTENT. # # Simply assigning classes to directories doesn't have any visible effects. It merely gives you an # option to define custom colors and icons for different directory classes. # # # Styling for WORK. # typeset -g POWERLEVEL9K_DIR_WORK_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_DIR_WORK_FOREGROUND=31 # typeset -g POWERLEVEL9K_DIR_WORK_SHORTENED_FOREGROUND=103 # typeset -g POWERLEVEL9K_DIR_WORK_ANCHOR_FOREGROUND=39 # # # Styling for WORK_NOT_WRITABLE. # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND=31 # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_SHORTENED_FOREGROUND=103 # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_ANCHOR_FOREGROUND=39 # # # Styling for WORK_NON_EXISTENT. # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_FOREGROUND=31 # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_SHORTENED_FOREGROUND=103 # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_ANCHOR_FOREGROUND=39 # # If a styling parameter isn't explicitly defined for some class, it falls back to the classless # parameter. For example, if POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND is not set, it falls # back to POWERLEVEL9K_DIR_FOREGROUND. # # typeset -g POWERLEVEL9K_DIR_CLASSES=() # Custom prefix. # typeset -g POWERLEVEL9K_DIR_PREFIX='%fin ' #####################################[ vcs: git status ]###################################### # Branch icon. Set this parameter to '\uF126 ' for the popular Powerline branch icon. typeset -g POWERLEVEL9K_VCS_BRANCH_ICON='\uF126 ' # Untracked files icon. It's really a question mark, your font isn't broken. # Change the value of this parameter to show a different icon. typeset -g POWERLEVEL9K_VCS_UNTRACKED_ICON='?' # Formatter for Git status. # # Example output: master ⇣42⇡42 *42 merge ~42 +42 !42 ?42. # # You can edit the function to customize how Git status looks. # # VCS_STATUS_* parameters are set by gitstatus plugin. See reference: # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh. function my_git_formatter() { emulate -L zsh if [[ -n $P9K_CONTENT ]]; then # If P9K_CONTENT is not empty, use it. It's either "loading" or from vcs_info (not from # gitstatus plugin). VCS_STATUS_* parameters are not available in this case. typeset -g my_git_format=$P9K_CONTENT return fi if (( $1 )); then # Styling for up-to-date Git status. local meta='%f' # default foreground local clean='%76F' # green foreground local modified='%178F' # yellow foreground local untracked='%39F' # blue foreground local conflicted='%196F' # red foreground else # Styling for incomplete and stale Git status. local meta='%244F' # grey foreground local clean='%244F' # grey foreground local modified='%244F' # grey foreground local untracked='%244F' # grey foreground local conflicted='%244F' # grey foreground fi local res if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then local branch=${(V)VCS_STATUS_LOCAL_BRANCH} # If local branch name is at most 32 characters long, show it in full. # Otherwise show the first 12 … the last 12. # Tip: To always show local branch name in full without truncation, delete the next line. (( $#branch > 32 )) && branch[13,-13]="…" # <-- this line res+="${clean}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\%/%%}" fi if [[ -n $VCS_STATUS_TAG # Show tag only if not on a branch. # Tip: To always show tag, delete the next line. && -z $VCS_STATUS_LOCAL_BRANCH # <-- this line ]]; then local tag=${(V)VCS_STATUS_TAG} # If tag name is at most 32 characters long, show it in full. # Otherwise show the first 12 … the last 12. # Tip: To always show tag name in full without truncation, delete the next line. (( $#tag > 32 )) && tag[13,-13]="…" # <-- this line res+="${meta}#${clean}${tag//\%/%%}" fi # Display the current Git commit if there is no branch and no tag. # Tip: To always display the current Git commit, delete the next line. [[ -z $VCS_STATUS_LOCAL_BRANCH && -z $VCS_STATUS_LOCAL_BRANCH ]] && # <-- this line res+="${meta}@${clean}${VCS_STATUS_COMMIT[1,8]}" # Show tracking branch name if it differs from local branch. if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then res+="${meta}:${clean}${(V)VCS_STATUS_REMOTE_BRANCH//\%/%%}" fi # ⇣42 if behind the remote. (( VCS_STATUS_COMMITS_BEHIND )) && res+=" ${clean}⇣${VCS_STATUS_COMMITS_BEHIND}" # ⇡42 if ahead of the remote; no leading space if also behind the remote: ⇣42⇡42. (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && res+=" " (( VCS_STATUS_COMMITS_AHEAD )) && res+="${clean}⇡${VCS_STATUS_COMMITS_AHEAD}" # ⇠42 if behind the push remote. (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" ${clean}⇠${VCS_STATUS_PUSH_COMMITS_BEHIND}" (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" " # ⇢42 if ahead of the push remote; no leading space if also behind: ⇠42⇢42. (( VCS_STATUS_PUSH_COMMITS_AHEAD )) && res+="${clean}⇢${VCS_STATUS_PUSH_COMMITS_AHEAD}" # *42 if have stashes. (( VCS_STATUS_STASHES )) && res+=" ${clean}*${VCS_STATUS_STASHES}" # 'merge' if the repo is in an unusual state. [[ -n $VCS_STATUS_ACTION ]] && res+=" ${conflicted}${VCS_STATUS_ACTION}" # ~42 if have merge conflicts. (( VCS_STATUS_NUM_CONFLICTED )) && res+=" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}" # +42 if have staged changes. (( VCS_STATUS_NUM_STAGED )) && res+=" ${modified}+${VCS_STATUS_NUM_STAGED}" # !42 if have unstaged changes. (( VCS_STATUS_NUM_UNSTAGED )) && res+=" ${modified}!${VCS_STATUS_NUM_UNSTAGED}" # ?42 if have untracked files. It's really a question mark, your font isn't broken. # See POWERLEVEL9K_VCS_UNTRACKED_ICON above if you want to use a different icon. # Remove the next line if you don't want to see untracked files at all. (( VCS_STATUS_NUM_UNTRACKED )) && res+=" ${untracked}${(g::)POWERLEVEL9K_VCS_UNTRACKED_ICON}${VCS_STATUS_NUM_UNTRACKED}" # "─" if the number of unstaged files is unknown. This can happen due to # POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY (see below) being set to a non-negative number lower # than the number of files in the Git index, or due to bash.showDirtyState being set to false # in the repository config. The number of staged and untracked files may also be unknown # in this case. (( VCS_STATUS_HAS_UNSTAGED == -1 )) && res+=" ${modified}─" typeset -g my_git_format=$res } functions -M my_git_formatter 2>/dev/null # Don't count the number of unstaged, untracked and conflicted files in Git repositories with # more than this many files in the index. Negative value means infinity. # # If you are working in Git repositories with tens of millions of files and seeing performance # sagging, try setting POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY to a number lower than the output # of `git ls-files | wc -l`. Alternatively, add `bash.showDirtyState = false` to the repository's # config: `git config bash.showDirtyState false`. typeset -g POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY=-1 # Don't show Git status in prompt for repositories whose workdir matches this pattern. # For example, if set to '~', the Git repository at $HOME/.git will be ignored. # Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'. typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~' # Disable the default Git status formatting. typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true # Install our own Git status formatter. typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter(1)))+${my_git_format}}' typeset -g POWERLEVEL9K_VCS_LOADING_CONTENT_EXPANSION='${$((my_git_formatter(0)))+${my_git_format}}' # Enable counters for staged, unstaged, etc. typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED,COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=-1 # Icon color. typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_COLOR=76 typeset -g POWERLEVEL9K_VCS_LOADING_VISUAL_IDENTIFIER_COLOR=244 # Custom icon. # typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_EXPANSION='⭐' # Custom prefix. typeset -g POWERLEVEL9K_VCS_PREFIX='%fon ' # Show status of repositories of these types. You can add svn and/or hg if you are # using them. If you do, your prompt may become slow even when your current directory # isn't in an svn or hg reposotiry. typeset -g POWERLEVEL9K_VCS_BACKENDS=(git) # These settings are used for repositories other than Git or when gitstatusd fails and # Powerlevel10k has to fall back to using vcs_info. typeset -g POWERLEVEL9K_VCS_CLEAN_FOREGROUND=76 typeset -g POWERLEVEL9K_VCS_UNTRACKED_FOREGROUND=76 typeset -g POWERLEVEL9K_VCS_MODIFIED_FOREGROUND=178 ##########################[ status: exit code of the last command ]########################### # Enable OK_PIPE, ERROR_PIPE and ERROR_SIGNAL status states to allow us to enable, disable and # style them independently from the regular OK and ERROR state. typeset -g POWERLEVEL9K_STATUS_EXTENDED_STATES=true # Status on success. No content, just an icon. No need to show it if prompt_char is enabled as # it will signify success by turning green. typeset -g POWERLEVEL9K_STATUS_OK=false typeset -g POWERLEVEL9K_STATUS_OK_FOREGROUND=70 typeset -g POWERLEVEL9K_STATUS_OK_VISUAL_IDENTIFIER_EXPANSION='✔' # Status when some part of a pipe command fails but the overall exit status is zero. It may look # like this: 1|0. typeset -g POWERLEVEL9K_STATUS_OK_PIPE=true typeset -g POWERLEVEL9K_STATUS_OK_PIPE_FOREGROUND=70 typeset -g POWERLEVEL9K_STATUS_OK_PIPE_VISUAL_IDENTIFIER_EXPANSION='✔' # Status when it's just an error code (e.g., '1'). No need to show it if prompt_char is enabled as # it will signify error by turning red. typeset -g POWERLEVEL9K_STATUS_ERROR=false typeset -g POWERLEVEL9K_STATUS_ERROR_FOREGROUND=160 typeset -g POWERLEVEL9K_STATUS_ERROR_VISUAL_IDENTIFIER_EXPANSION='✘' # Status when the last command was terminated by a signal. typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL=true typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_FOREGROUND=160 # Use terse signal names: "INT" instead of "SIGINT(2)". typeset -g POWERLEVEL9K_STATUS_VERBOSE_SIGNAME=false typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_VISUAL_IDENTIFIER_EXPANSION='✘' # Status when some part of a pipe command fails and the overall exit status is also non-zero. # It may look like this: 1|0. typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE=true typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_FOREGROUND=160 typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_VISUAL_IDENTIFIER_EXPANSION='✘' ###################[ command_execution_time: duration of the last command ]################### # Show duration of the last command if takes at least this many seconds. typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3 # Show this many fractional digits. Zero means round to seconds. typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0 # Execution time color. typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=101 # Duration format: 1d 2h 3m 4s. typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s' # Custom icon. # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' # Custom prefix. typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PREFIX='%ftook ' #######################[ background_jobs: presence of background jobs ]####################### # Don't show the number of background jobs. typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false # Background jobs color. typeset -g POWERLEVEL9K_BACKGROUND_JOBS_FOREGROUND=70 # Custom icon. # typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_EXPANSION='⭐' #######################[ direnv: direnv status (https://direnv.net/) ]######################## # Direnv color. typeset -g POWERLEVEL9K_DIRENV_FOREGROUND=178 # Custom icon. # typeset -g POWERLEVEL9K_DIRENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ###############[ asdf: asdf version manager (https://github.com/asdf-vm/asdf) ]############### # Default asdf color. Only used to display tools for which there is no color override (see below). # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_FOREGROUND. typeset -g POWERLEVEL9K_ASDF_FOREGROUND=66 # There are four parameters that can be used to hide asdf tools. Each parameter describes # conditions under which a tool gets hidden. Parameters can hide tools but not unhide them. If at # least one parameter decides to hide a tool, that tool gets hidden. If no parameter decides to # hide a tool, it gets shown. # # Special note on the difference between POWERLEVEL9K_ASDF_SOURCES and # POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW. Consider the effect of the following commands: # # asdf local python 3.8.1 # asdf global python 3.8.1 # # After running both commands the current python version is 3.8.1 and its source is "local" as # it takes precedence over "global". If POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW is set to false, # it'll hide python version in this case because 3.8.1 is the same as the global version. # POWERLEVEL9K_ASDF_SOURCES will hide python version only if the value of this parameter doesn't # contain "local". # Hide tool versions that don't come from one of these sources. # # Available sources: # # - shell `asdf current` says "set by ASDF_${TOOL}_VERSION environment variable" # - local `asdf current` says "set by /some/not/home/directory/file" # - global `asdf current` says "set by /home/username/file" # # Note: If this parameter is set to (shell local global), it won't hide tools. # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SOURCES. typeset -g POWERLEVEL9K_ASDF_SOURCES=(shell local global) # If set to false, hide tool versions that are the same as global. # # Note: The name of this parameter doesn't reflect its meaning at all. # Note: If this parameter is set to true, it won't hide tools. # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_PROMPT_ALWAYS_SHOW. typeset -g POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW=false # If set to false, hide tool versions that are equal to "system". # # Note: If this parameter is set to true, it won't hide tools. # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_SYSTEM. typeset -g POWERLEVEL9K_ASDF_SHOW_SYSTEM=true # If set to non-empty value, hide tools unless there is a file matching the specified file pattern # in the current directory, or its parent directory, or its grandparent directory, and so on. # # Note: If this parameter is set to empty value, it won't hide tools. # Note: SHOW_ON_UPGLOB isn't specific to asdf. It works with all prompt segments. # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_ON_UPGLOB. # # Example: Hide nodejs version when there is no package.json and no *.js files in the current # directory, in `..`, in `../..` and so on. # # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.js|package.json' typeset -g POWERLEVEL9K_ASDF_SHOW_ON_UPGLOB= # Ruby version from asdf. typeset -g POWERLEVEL9K_ASDF_RUBY_FOREGROUND=168 # typeset -g POWERLEVEL9K_ASDF_RUBY_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_RUBY_SHOW_ON_UPGLOB='*.foo|*.bar' # Python version from asdf. typeset -g POWERLEVEL9K_ASDF_PYTHON_FOREGROUND=37 # typeset -g POWERLEVEL9K_ASDF_PYTHON_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_PYTHON_SHOW_ON_UPGLOB='*.foo|*.bar' # Go version from asdf. typeset -g POWERLEVEL9K_ASDF_GOLANG_FOREGROUND=37 # typeset -g POWERLEVEL9K_ASDF_GOLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_GOLANG_SHOW_ON_UPGLOB='*.foo|*.bar' # Node.js version from asdf. typeset -g POWERLEVEL9K_ASDF_NODEJS_FOREGROUND=70 # typeset -g POWERLEVEL9K_ASDF_NODEJS_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.foo|*.bar' # Rust version from asdf. typeset -g POWERLEVEL9K_ASDF_RUST_FOREGROUND=37 # typeset -g POWERLEVEL9K_ASDF_RUST_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_RUST_SHOW_ON_UPGLOB='*.foo|*.bar' # .NET Core version from asdf. typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_FOREGROUND=134 # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_DOTNET_SHOW_ON_UPGLOB='*.foo|*.bar' # Flutter version from asdf. typeset -g POWERLEVEL9K_ASDF_FLUTTER_FOREGROUND=38 # typeset -g POWERLEVEL9K_ASDF_FLUTTER_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_FLUTTER_SHOW_ON_UPGLOB='*.foo|*.bar' # Lua version from asdf. typeset -g POWERLEVEL9K_ASDF_LUA_FOREGROUND=32 # typeset -g POWERLEVEL9K_ASDF_LUA_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_LUA_SHOW_ON_UPGLOB='*.foo|*.bar' # Java version from asdf. typeset -g POWERLEVEL9K_ASDF_JAVA_FOREGROUND=32 # typeset -g POWERLEVEL9K_ASDF_JAVA_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_JAVA_SHOW_ON_UPGLOB='*.foo|*.bar' # Perl version from asdf. typeset -g POWERLEVEL9K_ASDF_PERL_FOREGROUND=67 # typeset -g POWERLEVEL9K_ASDF_PERL_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_PERL_SHOW_ON_UPGLOB='*.foo|*.bar' # Erlang version from asdf. typeset -g POWERLEVEL9K_ASDF_ERLANG_FOREGROUND=125 # typeset -g POWERLEVEL9K_ASDF_ERLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_ERLANG_SHOW_ON_UPGLOB='*.foo|*.bar' # Elixir version from asdf. typeset -g POWERLEVEL9K_ASDF_ELIXIR_FOREGROUND=129 # typeset -g POWERLEVEL9K_ASDF_ELIXIR_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_ELIXIR_SHOW_ON_UPGLOB='*.foo|*.bar' # Postgres version from asdf. typeset -g POWERLEVEL9K_ASDF_POSTGRES_FOREGROUND=31 # typeset -g POWERLEVEL9K_ASDF_POSTGRES_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_POSTGRES_SHOW_ON_UPGLOB='*.foo|*.bar' # PHP version from asdf. typeset -g POWERLEVEL9K_ASDF_PHP_FOREGROUND=99 # typeset -g POWERLEVEL9K_ASDF_PHP_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_PHP_SHOW_ON_UPGLOB='*.foo|*.bar' # Haskell version from asdf. typeset -g POWERLEVEL9K_ASDF_HASKELL_FOREGROUND=172 # typeset -g POWERLEVEL9K_ASDF_HASKELL_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_HASKELL_SHOW_ON_UPGLOB='*.foo|*.bar' # Julia version from asdf. typeset -g POWERLEVEL9K_ASDF_JULIA_FOREGROUND=70 # typeset -g POWERLEVEL9K_ASDF_JULIA_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_ASDF_JULIA_SHOW_ON_UPGLOB='*.foo|*.bar' ##########[ nordvpn: nordvpn connection status, linux only (https://nordvpn.com/) ]########### # NordVPN connection indicator color. typeset -g POWERLEVEL9K_NORDVPN_FOREGROUND=39 # Hide NordVPN connection indicator when not connected. typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_CONTENT_EXPANSION= typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_VISUAL_IDENTIFIER_EXPANSION= # Custom icon. # typeset -g POWERLEVEL9K_NORDVPN_VISUAL_IDENTIFIER_EXPANSION='⭐' #################[ ranger: ranger shell (https://github.com/ranger/ranger) ]################## # Ranger shell color. typeset -g POWERLEVEL9K_RANGER_FOREGROUND=178 # Custom icon. # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='⭐' ######################[ nnn: nnn shell (https://github.com/jarun/nnn) ]####################### # Nnn shell color. typeset -g POWERLEVEL9K_NNN_FOREGROUND=72 # Custom icon. # typeset -g POWERLEVEL9K_NNN_VISUAL_IDENTIFIER_EXPANSION='⭐' ###########################[ vim_shell: vim shell indicator (:sh) ]########################### # Vim shell indicator color. typeset -g POWERLEVEL9K_VIM_SHELL_FOREGROUND=34 # Custom icon. # typeset -g POWERLEVEL9K_VIM_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' ######[ midnight_commander: midnight commander shell (https://midnight-commander.org/) ]###### # Midnight Commander shell color. typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_FOREGROUND=178 # Custom icon. # typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_VISUAL_IDENTIFIER_EXPANSION='⭐' #[ nix_shell: nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) ]## # Nix shell color. typeset -g POWERLEVEL9K_NIX_SHELL_FOREGROUND=74 # Tip: If you want to see just the icon without "pure" and "impure", uncomment the next line. # typeset -g POWERLEVEL9K_NIX_SHELL_CONTENT_EXPANSION= # Custom icon. # typeset -g POWERLEVEL9K_NIX_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' ##################################[ disk_usage: disk usage ]################################## # Colors for different levels of disk usage. typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_FOREGROUND=35 typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_FOREGROUND=220 typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_FOREGROUND=160 # Thresholds for different levels of disk usage (percentage points). typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL=90 typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_LEVEL=95 # If set to true, hide disk usage when below $POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL percent. typeset -g POWERLEVEL9K_DISK_USAGE_ONLY_WARNING=false # Custom icon. # typeset -g POWERLEVEL9K_DISK_USAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' ######################################[ ram: free RAM ]####################################### # RAM color. typeset -g POWERLEVEL9K_RAM_FOREGROUND=66 # Custom icon. # typeset -g POWERLEVEL9K_RAM_VISUAL_IDENTIFIER_EXPANSION='⭐' #####################################[ swap: used swap ]###################################### # Swap color. typeset -g POWERLEVEL9K_SWAP_FOREGROUND=96 # Custom icon. # typeset -g POWERLEVEL9K_SWAP_VISUAL_IDENTIFIER_EXPANSION='⭐' ######################################[ load: CPU load ]###################################### # Show average CPU load over this many last minutes. Valid values are 1, 5 and 15. typeset -g POWERLEVEL9K_LOAD_WHICH=5 # Load color when load is under 50%. typeset -g POWERLEVEL9K_LOAD_NORMAL_FOREGROUND=66 # Load color when load is between 50% and 70%. typeset -g POWERLEVEL9K_LOAD_WARNING_FOREGROUND=178 # Load color when load is over 70%. typeset -g POWERLEVEL9K_LOAD_CRITICAL_FOREGROUND=166 # Custom icon. # typeset -g POWERLEVEL9K_LOAD_VISUAL_IDENTIFIER_EXPANSION='⭐' ################[ todo: todo items (https://github.com/todotxt/todo.txt-cli) ]################ # Todo color. typeset -g POWERLEVEL9K_TODO_FOREGROUND=110 # Hide todo when the total number of tasks is zero. typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_TOTAL=true # Hide todo when the number of tasks after filtering is zero. typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_FILTERED=false # Todo format. The following parameters are available within the expansion. # # - P9K_TODO_TOTAL_TASK_COUNT The total number of tasks. # - P9K_TODO_FILTERED_TASK_COUNT The number of tasks after filtering. # # These variables correspond to the last line of the output of `todo.sh -p ls`: # # TODO: 24 of 42 tasks shown # # Here 24 is P9K_TODO_FILTERED_TASK_COUNT and 42 is P9K_TODO_TOTAL_TASK_COUNT. # # typeset -g POWERLEVEL9K_TODO_CONTENT_EXPANSION='$P9K_TODO_FILTERED_TASK_COUNT' # Custom icon. # typeset -g POWERLEVEL9K_TODO_VISUAL_IDENTIFIER_EXPANSION='⭐' ###########[ timewarrior: timewarrior tracking status (https://timewarrior.net/) ]############ # Timewarrior color. typeset -g POWERLEVEL9K_TIMEWARRIOR_FOREGROUND=110 # If the tracked task is longer than 24 characters, truncate and append "…". # Tip: To always display tasks without truncation, delete the following parameter. # Tip: To hide task names and display just the icon when time tracking is enabled, set the # value of the following parameter to "". typeset -g POWERLEVEL9K_TIMEWARRIOR_CONTENT_EXPANSION='${P9K_CONTENT:0:24}${${P9K_CONTENT:24}:+…}' # Custom icon. # typeset -g POWERLEVEL9K_TIMEWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' ##############[ taskwarrior: taskwarrior task count (https://taskwarrior.org/) ]############## # Taskwarrior color. typeset -g POWERLEVEL9K_TASKWARRIOR_FOREGROUND=74 # Taskwarrior segment format. The following parameters are available within the expansion. # # - P9K_TASKWARRIOR_PENDING_COUNT The number of pending tasks: `task +PENDING count`. # - P9K_TASKWARRIOR_OVERDUE_COUNT The number of overdue tasks: `task +OVERDUE count`. # # Zero values are represented as empty parameters. # # The default format: # # '${P9K_TASKWARRIOR_OVERDUE_COUNT:+"!$P9K_TASKWARRIOR_OVERDUE_COUNT/"}$P9K_TASKWARRIOR_PENDING_COUNT' # # typeset -g POWERLEVEL9K_TASKWARRIOR_CONTENT_EXPANSION='$P9K_TASKWARRIOR_PENDING_COUNT' # Custom icon. # typeset -g POWERLEVEL9K_TASKWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' ##################################[ context: user@hostname ]################################## # Context color when running with privileges. typeset -g POWERLEVEL9K_CONTEXT_ROOT_FOREGROUND=178 # Context color in SSH without privileges. typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_FOREGROUND=180 # Default context color (no privileges, no SSH). typeset -g POWERLEVEL9K_CONTEXT_FOREGROUND=180 # Context format when running with privileges: bold user@hostname. typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE='%B%n@%m' # Context format when in SSH without privileges: user@hostname. typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_TEMPLATE='%n@%m' # Default context format (no privileges, no SSH): user@hostname. typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE='%n@%m' # Don't show context unless running with privileges or in SSH. # Tip: Remove the next line to always show context. typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION= # Custom icon. # typeset -g POWERLEVEL9K_CONTEXT_VISUAL_IDENTIFIER_EXPANSION='⭐' # Custom prefix. typeset -g POWERLEVEL9K_CONTEXT_PREFIX='%fwith ' ###[ virtualenv: python virtual environment (https://docs.python.org/3/library/venv.html) ]### # Python virtual environment color. typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=37 # Don't show Python version next to the virtual environment name. typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false # If set to "false", won't show virtualenv if pyenv is already shown. # If set to "if-different", won't show virtualenv if it's the same as pyenv. typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=false # Separate environment name from Python version only with a space. typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER= # Custom icon. # typeset -g POWERLEVEL9K_VIRTUALENV_VISUAL_IDENTIFIER_EXPANSION='⭐' #####################[ anaconda: conda environment (https://conda.io/) ]###################### # Anaconda environment color. typeset -g POWERLEVEL9K_ANACONDA_FOREGROUND=37 # Anaconda segment format. The following parameters are available within the expansion. # # - CONDA_PREFIX Absolute path to the active Anaconda/Miniconda environment. # - CONDA_DEFAULT_ENV Name of the active Anaconda/Miniconda environment. # - CONDA_PROMPT_MODIFIER Configurable prompt modifier (see below). # - P9K_ANACONDA_PYTHON_VERSION Current python version (python --version). # # CONDA_PROMPT_MODIFIER can be configured with the following command: # # conda config --set env_prompt '({default_env}) ' # # The last argument is a Python format string that can use the following variables: # # - prefix The same as CONDA_PREFIX. # - default_env The same as CONDA_DEFAULT_ENV. # - name The last segment of CONDA_PREFIX. # - stacked_env Comma-separated list of names in the environment stack. The first element is # always the same as default_env. # # Note: '({default_env}) ' is the default value of env_prompt. # # The default value of POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION expands to $CONDA_PROMPT_MODIFIER # without the surrounding parentheses, or to the last path component of CONDA_PREFIX if the former # is empty. typeset -g POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION='${${${${CONDA_PROMPT_MODIFIER#\(}% }%\)}:-${CONDA_PREFIX:t}}' # Custom icon. # typeset -g POWERLEVEL9K_ANACONDA_VISUAL_IDENTIFIER_EXPANSION='⭐' ################[ pyenv: python environment (https://github.com/pyenv/pyenv) ]################ # Pyenv color. typeset -g POWERLEVEL9K_PYENV_FOREGROUND=37 # Hide python version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_PYENV_SOURCES=(shell local global) # If set to false, hide python version if it's the same as global: # $(pyenv version-name) == $(pyenv global). typeset -g POWERLEVEL9K_PYENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide python version if it's equal to "system". typeset -g POWERLEVEL9K_PYENV_SHOW_SYSTEM=true # Pyenv segment format. The following parameters are available within the expansion. # # - P9K_CONTENT Current pyenv environment (pyenv version-name). # - P9K_PYENV_PYTHON_VERSION Current python version (python --version). # # The default format has the following logic: # # 1. Display "$P9K_CONTENT $P9K_PYENV_PYTHON_VERSION" if $P9K_PYENV_PYTHON_VERSION is not # empty and unequal to $P9K_CONTENT. # 2. Otherwise display just "$P9K_CONTENT". typeset -g POWERLEVEL9K_PYENV_CONTENT_EXPANSION='${P9K_CONTENT}${${P9K_PYENV_PYTHON_VERSION:#$P9K_CONTENT}:+ $P9K_PYENV_PYTHON_VERSION}' # Custom icon. # typeset -g POWERLEVEL9K_PYENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ################[ goenv: go environment (https://github.com/syndbg/goenv) ]################ # Goenv color. typeset -g POWERLEVEL9K_GOENV_FOREGROUND=37 # Hide go version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_GOENV_SOURCES=(shell local global) # If set to false, hide go version if it's the same as global: # $(goenv version-name) == $(goenv global). typeset -g POWERLEVEL9K_GOENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide go version if it's equal to "system". typeset -g POWERLEVEL9K_GOENV_SHOW_SYSTEM=true # Custom icon. # typeset -g POWERLEVEL9K_GOENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ##########[ nodenv: node.js version from nodenv (https://github.com/nodenv/nodenv) ]########## # Nodenv color. typeset -g POWERLEVEL9K_NODENV_FOREGROUND=70 # Hide node version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_NODENV_SOURCES=(shell local global) # If set to false, hide node version if it's the same as global: # $(nodenv version-name) == $(nodenv global). typeset -g POWERLEVEL9K_NODENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide node version if it's equal to "system". typeset -g POWERLEVEL9K_NODENV_SHOW_SYSTEM=true # Custom icon. # typeset -g POWERLEVEL9K_NODENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ##############[ nvm: node.js version from nvm (https://github.com/nvm-sh/nvm) ]############### # Nvm color. typeset -g POWERLEVEL9K_NVM_FOREGROUND=70 # Custom icon. # typeset -g POWERLEVEL9K_NVM_VISUAL_IDENTIFIER_EXPANSION='⭐' ############[ nodeenv: node.js environment (https://github.com/ekalinin/nodeenv) ]############ # Nodeenv color. typeset -g POWERLEVEL9K_NODEENV_FOREGROUND=70 # Don't show Node version next to the environment name. typeset -g POWERLEVEL9K_NODEENV_SHOW_NODE_VERSION=false # Separate environment name from Node version only with a space. typeset -g POWERLEVEL9K_NODEENV_{LEFT,RIGHT}_DELIMITER= # Custom icon. # typeset -g POWERLEVEL9K_NODEENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ##############################[ node_version: node.js version ]############################### # Node version color. typeset -g POWERLEVEL9K_NODE_VERSION_FOREGROUND=70 # Show node version only when in a directory tree containing package.json. typeset -g POWERLEVEL9K_NODE_VERSION_PROJECT_ONLY=true # Custom icon. # typeset -g POWERLEVEL9K_NODE_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' #######################[ go_version: go version (https://golang.org) ]######################## # Go version color. typeset -g POWERLEVEL9K_GO_VERSION_FOREGROUND=37 # Show go version only when in a go project subdirectory. typeset -g POWERLEVEL9K_GO_VERSION_PROJECT_ONLY=true # Custom icon. # typeset -g POWERLEVEL9K_GO_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' #################[ rust_version: rustc version (https://www.rust-lang.org) ]################## # Rust version color. typeset -g POWERLEVEL9K_RUST_VERSION_FOREGROUND=37 # Show rust version only when in a rust project subdirectory. typeset -g POWERLEVEL9K_RUST_VERSION_PROJECT_ONLY=true # Custom icon. # typeset -g POWERLEVEL9K_RUST_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' ###############[ dotnet_version: .NET version (https://dotnet.microsoft.com) ]################ # .NET version color. typeset -g POWERLEVEL9K_DOTNET_VERSION_FOREGROUND=134 # Show .NET version only when in a .NET project subdirectory. typeset -g POWERLEVEL9K_DOTNET_VERSION_PROJECT_ONLY=true # Custom icon. # typeset -g POWERLEVEL9K_DOTNET_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' #####################[ php_version: php version (https://www.php.net/) ]###################### # PHP version color. typeset -g POWERLEVEL9K_PHP_VERSION_FOREGROUND=99 # Show PHP version only when in a PHP project subdirectory. typeset -g POWERLEVEL9K_PHP_VERSION_PROJECT_ONLY=true # Custom icon. # typeset -g POWERLEVEL9K_PHP_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' ##########[ laravel_version: laravel php framework version (https://laravel.com/) ]########### # Laravel version color. typeset -g POWERLEVEL9K_LARAVEL_VERSION_FOREGROUND=161 # Custom icon. # typeset -g POWERLEVEL9K_LARAVEL_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' ####################[ java_version: java version (https://www.java.com/) ]#################### # Java version color. typeset -g POWERLEVEL9K_JAVA_VERSION_FOREGROUND=32 # Show java version only when in a java project subdirectory. typeset -g POWERLEVEL9K_JAVA_VERSION_PROJECT_ONLY=true # Show brief version. typeset -g POWERLEVEL9K_JAVA_VERSION_FULL=false # Custom icon. # typeset -g POWERLEVEL9K_JAVA_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' ###[ package: name@version from package.json (https://docs.npmjs.com/files/package.json) ]#### # Package color. typeset -g POWERLEVEL9K_PACKAGE_FOREGROUND=117 # Package format. The following parameters are available within the expansion. # # - P9K_PACKAGE_NAME The value of `name` field in package.json. # - P9K_PACKAGE_VERSION The value of `version` field in package.json. # # typeset -g POWERLEVEL9K_PACKAGE_CONTENT_EXPANSION='${P9K_PACKAGE_NAME//\%/%%}@${P9K_PACKAGE_VERSION//\%/%%}' # Custom icon. # typeset -g POWERLEVEL9K_PACKAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' #############[ rbenv: ruby version from rbenv (https://github.com/rbenv/rbenv) ]############## # Rbenv color. typeset -g POWERLEVEL9K_RBENV_FOREGROUND=168 # Hide ruby version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_RBENV_SOURCES=(shell local global) # If set to false, hide ruby version if it's the same as global: # $(rbenv version-name) == $(rbenv global). typeset -g POWERLEVEL9K_RBENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide ruby version if it's equal to "system". typeset -g POWERLEVEL9K_RBENV_SHOW_SYSTEM=true # Custom icon. # typeset -g POWERLEVEL9K_RBENV_VISUAL_IDENTIFIER_EXPANSION='⭐' #######################[ rvm: ruby version from rvm (https://rvm.io) ]######################## # Rvm color. typeset -g POWERLEVEL9K_RVM_FOREGROUND=168 # Don't show @gemset at the end. typeset -g POWERLEVEL9K_RVM_SHOW_GEMSET=false # Don't show ruby- at the front. typeset -g POWERLEVEL9K_RVM_SHOW_PREFIX=false # Custom icon. # typeset -g POWERLEVEL9K_RVM_VISUAL_IDENTIFIER_EXPANSION='⭐' ###########[ fvm: flutter version management (https://github.com/leoafarias/fvm) ]############ # Fvm color. typeset -g POWERLEVEL9K_FVM_FOREGROUND=38 # Custom icon. # typeset -g POWERLEVEL9K_FVM_VISUAL_IDENTIFIER_EXPANSION='⭐' ##########[ luaenv: lua version from luaenv (https://github.com/cehoffman/luaenv) ]########### # Lua color. typeset -g POWERLEVEL9K_LUAENV_FOREGROUND=32 # Hide lua version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_LUAENV_SOURCES=(shell local global) # If set to false, hide lua version if it's the same as global: # $(luaenv version-name) == $(luaenv global). typeset -g POWERLEVEL9K_LUAENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide lua version if it's equal to "system". typeset -g POWERLEVEL9K_LUAENV_SHOW_SYSTEM=true # Custom icon. # typeset -g POWERLEVEL9K_LUAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ###############[ jenv: java version from jenv (https://github.com/jenv/jenv) ]################ # Java color. typeset -g POWERLEVEL9K_JENV_FOREGROUND=32 # Hide java version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_JENV_SOURCES=(shell local global) # If set to false, hide java version if it's the same as global: # $(jenv version-name) == $(jenv global). typeset -g POWERLEVEL9K_JENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide java version if it's equal to "system". typeset -g POWERLEVEL9K_JENV_SHOW_SYSTEM=true # Custom icon. # typeset -g POWERLEVEL9K_JENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ###########[ plenv: perl version from plenv (https://github.com/tokuhirom/plenv) ]############ # Perl color. typeset -g POWERLEVEL9K_PLENV_FOREGROUND=67 # Hide perl version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_PLENV_SOURCES=(shell local global) # If set to false, hide perl version if it's the same as global: # $(plenv version-name) == $(plenv global). typeset -g POWERLEVEL9K_PLENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide perl version if it's equal to "system". typeset -g POWERLEVEL9K_PLENV_SHOW_SYSTEM=true # Custom icon. # typeset -g POWERLEVEL9K_PLENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ############[ phpenv: php version from phpenv (https://github.com/phpenv/phpenv) ]############ # PHP color. typeset -g POWERLEVEL9K_PHPENV_FOREGROUND=99 # Hide php version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_PHPENV_SOURCES=(shell local global) # If set to false, hide php version if it's the same as global: # $(phpenv version-name) == $(phpenv global). typeset -g POWERLEVEL9K_PHPENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide php version if it's equal to "system". typeset -g POWERLEVEL9K_PHPENV_SHOW_SYSTEM=true # Custom icon. # typeset -g POWERLEVEL9K_PHPENV_VISUAL_IDENTIFIER_EXPANSION='⭐' #######[ scalaenv: scala version from scalaenv (https://github.com/scalaenv/scalaenv) ]####### # Scala color. typeset -g POWERLEVEL9K_SCALAENV_FOREGROUND=160 # Hide scala version if it doesn't come from one of these sources. typeset -g POWERLEVEL9K_SCALAENV_SOURCES=(shell local global) # If set to false, hide scala version if it's the same as global: # $(scalaenv version-name) == $(scalaenv global). typeset -g POWERLEVEL9K_SCALAENV_PROMPT_ALWAYS_SHOW=false # If set to false, hide scala version if it's equal to "system". typeset -g POWERLEVEL9K_SCALAENV_SHOW_SYSTEM=true # Custom icon. # typeset -g POWERLEVEL9K_SCALAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ##########[ haskell_stack: haskell version from stack (https://haskellstack.org/) ]########### # Haskell color. typeset -g POWERLEVEL9K_HASKELL_STACK_FOREGROUND=172 # Hide haskell version if it doesn't come from one of these sources. # # shell: version is set by STACK_YAML # local: version is set by stack.yaml up the directory tree # global: version is set by the implicit global project (~/.stack/global-project/stack.yaml) typeset -g POWERLEVEL9K_HASKELL_STACK_SOURCES=(shell local) # If set to false, hide haskell version if it's the same as in the implicit global project. typeset -g POWERLEVEL9K_HASKELL_STACK_ALWAYS_SHOW=true # Custom icon. # typeset -g POWERLEVEL9K_HASKELL_STACK_VISUAL_IDENTIFIER_EXPANSION='⭐' #############[ kubecontext: current kubernetes context (https://kubernetes.io/) ]############# # Show kubecontext only when the the command you are typing invokes one of these tools. # Tip: Remove the next line to always show kubecontext. typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens|kubectx|oc|istioctl|kogito|k9s|helmfile|fluxctl|stern' # Kubernetes context classes for the purpose of using different colors, icons and expansions with # different contexts. # # POWERLEVEL9K_KUBECONTEXT_CLASSES is an array with even number of elements. The first element # in each pair defines a pattern against which the current kubernetes context gets matched. # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) # that gets matched. If you unset all POWERLEVEL9K_KUBECONTEXT_*CONTENT_EXPANSION parameters, # you'll see this value in your prompt. The second element of each pair in # POWERLEVEL9K_KUBECONTEXT_CLASSES defines the context class. Patterns are tried in order. The # first match wins. # # For example, given these settings: # # typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( # '*prod*' PROD # '*test*' TEST # '*' DEFAULT) # # If your current kubernetes context is "deathray-testing/default", its class is TEST # because "deathray-testing/default" doesn't match the pattern '*prod*' but does match '*test*'. # # You can define different colors, icons and content expansions for different classes: # # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_FOREGROUND=28 # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( # '*prod*' PROD # These values are examples that are unlikely # '*test*' TEST # to match your needs. Customize them as needed. '*' DEFAULT) typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_FOREGROUND=134 # typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' # Use POWERLEVEL9K_KUBECONTEXT_CONTENT_EXPANSION to specify the content displayed by kubecontext # segment. Parameter expansions are very flexible and fast, too. See reference: # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. # # Within the expansion the following parameters are always available: # # - P9K_CONTENT The content that would've been displayed if there was no content # expansion defined. # - P9K_KUBECONTEXT_NAME The current context's name. Corresponds to column NAME in the # output of `kubectl config get-contexts`. # - P9K_KUBECONTEXT_CLUSTER The current context's cluster. Corresponds to column CLUSTER in the # output of `kubectl config get-contexts`. # - P9K_KUBECONTEXT_NAMESPACE The current context's namespace. Corresponds to column NAMESPACE # in the output of `kubectl config get-contexts`. If there is no # namespace, the parameter is set to "default". # - P9K_KUBECONTEXT_USER The current context's user. Corresponds to column AUTHINFO in the # output of `kubectl config get-contexts`. # # If the context points to Google Kubernetes Engine (GKE) or Elastic Kubernetes Service (EKS), # the following extra parameters are available: # # - P9K_KUBECONTEXT_CLOUD_NAME Either "gke" or "eks". # - P9K_KUBECONTEXT_CLOUD_ACCOUNT Account/project ID. # - P9K_KUBECONTEXT_CLOUD_ZONE Availability zone. # - P9K_KUBECONTEXT_CLOUD_CLUSTER Cluster. # # P9K_KUBECONTEXT_CLOUD_* parameters are derived from P9K_KUBECONTEXT_CLUSTER. For example, # if P9K_KUBECONTEXT_CLUSTER is "gke_my-account_us-east1-a_my-cluster-01": # # - P9K_KUBECONTEXT_CLOUD_NAME=gke # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=my-account # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east1-a # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 # # If P9K_KUBECONTEXT_CLUSTER is "arn:aws:eks:us-east-1:123456789012:cluster/my-cluster-01": # # - P9K_KUBECONTEXT_CLOUD_NAME=eks # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=123456789012 # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east-1 # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION= # Show P9K_KUBECONTEXT_CLOUD_CLUSTER if it's not empty and fall back to P9K_KUBECONTEXT_NAME. POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${P9K_KUBECONTEXT_CLOUD_CLUSTER:-${P9K_KUBECONTEXT_NAME}}' # Append the current context's namespace if it's not "default". POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${${:-/$P9K_KUBECONTEXT_NAMESPACE}:#/default}' # Custom prefix. typeset -g POWERLEVEL9K_KUBECONTEXT_PREFIX='%fat ' ################[ terraform: terraform workspace (https://www.terraform.io) ]################# # Don't show terraform workspace if it's literally "default". typeset -g POWERLEVEL9K_TERRAFORM_SHOW_DEFAULT=false # POWERLEVEL9K_TERRAFORM_CLASSES is an array with even number of elements. The first element # in each pair defines a pattern against which the current terraform workspace gets matched. # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) # that gets matched. If you unset all POWERLEVEL9K_TERRAFORM_*CONTENT_EXPANSION parameters, # you'll see this value in your prompt. The second element of each pair in # POWERLEVEL9K_TERRAFORM_CLASSES defines the workspace class. Patterns are tried in order. The # first match wins. # # For example, given these settings: # # typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( # '*prod*' PROD # '*test*' TEST # '*' OTHER) # # If your current terraform workspace is "project_test", its class is TEST because "project_test" # doesn't match the pattern '*prod*' but does match '*test*'. # # You can define different colors, icons and content expansions for different classes: # # typeset -g POWERLEVEL9K_TERRAFORM_TEST_FOREGROUND=28 # typeset -g POWERLEVEL9K_TERRAFORM_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_TERRAFORM_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( # '*prod*' PROD # These values are examples that are unlikely # '*test*' TEST # to match your needs. Customize them as needed. '*' OTHER) typeset -g POWERLEVEL9K_TERRAFORM_OTHER_FOREGROUND=38 # typeset -g POWERLEVEL9K_TERRAFORM_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' #[ aws: aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) ]# # Show aws only when the the command you are typing invokes one of these tools. # Tip: Remove the next line to always show aws. typeset -g POWERLEVEL9K_AWS_SHOW_ON_COMMAND='aws|awless|terraform|pulumi|terragrunt' # POWERLEVEL9K_AWS_CLASSES is an array with even number of elements. The first element # in each pair defines a pattern against which the current AWS profile gets matched. # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) # that gets matched. If you unset all POWERLEVEL9K_AWS_*CONTENT_EXPANSION parameters, # you'll see this value in your prompt. The second element of each pair in # POWERLEVEL9K_AWS_CLASSES defines the profile class. Patterns are tried in order. The # first match wins. # # For example, given these settings: # # typeset -g POWERLEVEL9K_AWS_CLASSES=( # '*prod*' PROD # '*test*' TEST # '*' DEFAULT) # # If your current AWS profile is "company_test", its class is TEST # because "company_test" doesn't match the pattern '*prod*' but does match '*test*'. # # You can define different colors, icons and content expansions for different classes: # # typeset -g POWERLEVEL9K_AWS_TEST_FOREGROUND=28 # typeset -g POWERLEVEL9K_AWS_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_AWS_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' typeset -g POWERLEVEL9K_AWS_CLASSES=( # '*prod*' PROD # These values are examples that are unlikely # '*test*' TEST # to match your needs. Customize them as needed. '*' DEFAULT) typeset -g POWERLEVEL9K_AWS_DEFAULT_FOREGROUND=208 # typeset -g POWERLEVEL9K_AWS_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' #[ aws_eb_env: aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) ]# # AWS Elastic Beanstalk environment color. typeset -g POWERLEVEL9K_AWS_EB_ENV_FOREGROUND=70 # Custom icon. # typeset -g POWERLEVEL9K_AWS_EB_ENV_VISUAL_IDENTIFIER_EXPANSION='⭐' ##########[ azure: azure account name (https://docs.microsoft.com/en-us/cli/azure) ]########## # Show azure only when the the command you are typing invokes one of these tools. # Tip: Remove the next line to always show azure. typeset -g POWERLEVEL9K_AZURE_SHOW_ON_COMMAND='az|terraform|pulumi|terragrunt' # Azure account name color. typeset -g POWERLEVEL9K_AZURE_FOREGROUND=32 # Custom icon. # typeset -g POWERLEVEL9K_AZURE_VISUAL_IDENTIFIER_EXPANSION='⭐' ##########[ gcloud: google cloud account and project (https://cloud.google.com/) ]########### # Show gcloud only when the the command you are typing invokes one of these tools. # Tip: Remove the next line to always show gcloud. typeset -g POWERLEVEL9K_GCLOUD_SHOW_ON_COMMAND='gcloud|gcs' # Google cloud color. typeset -g POWERLEVEL9K_GCLOUD_FOREGROUND=32 # Google cloud format. Change the value of POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION and/or # POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION if the default is too verbose or not informative # enough. You can use the following parameters in the expansions. Each of them corresponds to the # output of `gcloud` tool. # # Parameter | Source # -------------------------|-------------------------------------------------------------------- # P9K_GCLOUD_CONFIGURATION | gcloud config configurations list --format='value(name)' # P9K_GCLOUD_ACCOUNT | gcloud config get-value account # P9K_GCLOUD_PROJECT_ID | gcloud config get-value project # P9K_GCLOUD_PROJECT_NAME | gcloud projects describe $P9K_GCLOUD_PROJECT_ID --format='value(name)' # # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced with '%%'. # # Obtaining project name requires sending a request to Google servers. This can take a long time # and even fail. When project name is unknown, P9K_GCLOUD_PROJECT_NAME is not set and gcloud # prompt segment is in state PARTIAL. When project name gets known, P9K_GCLOUD_PROJECT_NAME gets # set and gcloud prompt segment transitions to state COMPLETE. # # You can customize the format, icon and colors of gcloud segment separately for states PARTIAL # and COMPLETE. You can also hide gcloud in state PARTIAL by setting # POWERLEVEL9K_GCLOUD_PARTIAL_VISUAL_IDENTIFIER_EXPANSION and # POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION to empty. typeset -g POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_ID//\%/%%}' typeset -g POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_NAME//\%/%%}' # Send a request to Google (by means of `gcloud projects describe ...`) to obtain project name # this often. Negative value disables periodic polling. In this mode project name is retrieved # only when the current configuration, account or project id changes. typeset -g POWERLEVEL9K_GCLOUD_REFRESH_PROJECT_NAME_SECONDS=60 # Custom icon. # typeset -g POWERLEVEL9K_GCLOUD_VISUAL_IDENTIFIER_EXPANSION='⭐' #[ google_app_cred: google application credentials (https://cloud.google.com/docs/authentication/production) ]# # Show google_app_cred only when the the command you are typing invokes one of these tools. # Tip: Remove the next line to always show google_app_cred. typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_SHOW_ON_COMMAND='terraform|pulumi|terragrunt' # Google application credentials classes for the purpose of using different colors, icons and # expansions with different credentials. # # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES is an array with even number of elements. The first # element in each pair defines a pattern against which the current kubernetes context gets # matched. More specifically, it's P9K_CONTENT prior to the application of context expansion # (see below) that gets matched. If you unset all POWERLEVEL9K_GOOGLE_APP_CRED_*CONTENT_EXPANSION # parameters, you'll see this value in your prompt. The second element of each pair in # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES defines the context class. Patterns are tried in order. # The first match wins. # # For example, given these settings: # # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( # '*:*prod*:*' PROD # '*:*test*:*' TEST # '*' DEFAULT) # # If your current Google application credentials is "service_account deathray-testing x@y.com", # its class is TEST because it doesn't match the pattern '* *prod* *' but does match '* *test* *'. # # You can define different colors, icons and content expansions for different classes: # # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_FOREGROUND=28 # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_CONTENT_EXPANSION='$P9K_GOOGLE_APP_CRED_PROJECT_ID' typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( # '*:*prod*:*' PROD # These values are examples that are unlikely # '*:*test*:*' TEST # to match your needs. Customize them as needed. '*' DEFAULT) typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_FOREGROUND=32 # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' # Use POWERLEVEL9K_GOOGLE_APP_CRED_CONTENT_EXPANSION to specify the content displayed by # google_app_cred segment. Parameter expansions are very flexible and fast, too. See reference: # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. # # You can use the following parameters in the expansion. Each of them corresponds to one of the # fields in the JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS. # # Parameter | JSON key file field # ---------------------------------+--------------- # P9K_GOOGLE_APP_CRED_TYPE | type # P9K_GOOGLE_APP_CRED_PROJECT_ID | project_id # P9K_GOOGLE_APP_CRED_CLIENT_EMAIL | client_email # # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced by '%%'. typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_CONTENT_EXPANSION='${P9K_GOOGLE_APP_CRED_PROJECT_ID//\%/%%}' ###############################[ public_ip: public IP address ]############################### # Public IP color. typeset -g POWERLEVEL9K_PUBLIC_IP_FOREGROUND=94 # Custom icon. # typeset -g POWERLEVEL9K_PUBLIC_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' ########################[ vpn_ip: virtual private network indicator ]######################### # VPN IP color. typeset -g POWERLEVEL9K_VPN_IP_FOREGROUND=81 # When on VPN, show just an icon without the IP address. # Tip: To display the private IP address when on VPN, remove the next line. typeset -g POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION= # Regular expression for the VPN network interface. Run `ifconfig` or `ip -4 a show` while on VPN # to see the name of the interface. typeset -g POWERLEVEL9K_VPN_IP_INTERFACE='(gpd|wg|(.*tun)|tailscale)[0-9]*' # If set to true, show one segment per matching network interface. If set to false, show only # one segment corresponding to the first matching network interface. # Tip: If you set it to true, you'll probably want to unset POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION. typeset -g POWERLEVEL9K_VPN_IP_SHOW_ALL=false # Custom icon. # typeset -g POWERLEVEL9K_VPN_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' ###########[ ip: ip address and bandwidth usage for a specified network interface ]########### # IP color. typeset -g POWERLEVEL9K_IP_FOREGROUND=38 # The following parameters are accessible within the expansion: # # Parameter | Meaning # ----------------------+--------------- # P9K_IP_IP | IP address # P9K_IP_INTERFACE | network interface # P9K_IP_RX_BYTES | total number of bytes received # P9K_IP_TX_BYTES | total number of bytes sent # P9K_IP_RX_RATE | receive rate (since last prompt) # P9K_IP_TX_RATE | send rate (since last prompt) typeset -g POWERLEVEL9K_IP_CONTENT_EXPANSION='$P9K_IP_IP${P9K_IP_RX_RATE:+ %70F⇣$P9K_IP_RX_RATE}${P9K_IP_TX_RATE:+ %215F⇡$P9K_IP_TX_RATE}' # Show information for the first network interface whose name matches this regular expression. # Run `ifconfig` or `ip -4 a show` to see the names of all network interfaces. typeset -g POWERLEVEL9K_IP_INTERFACE='[ew].*' # Custom icon. # typeset -g POWERLEVEL9K_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' #########################[ proxy: system-wide http/https/ftp proxy ]########################## # Proxy color. typeset -g POWERLEVEL9K_PROXY_FOREGROUND=68 # Custom icon. # typeset -g POWERLEVEL9K_PROXY_VISUAL_IDENTIFIER_EXPANSION='⭐' ################################[ battery: internal battery ]################################# # Show battery in red when it's below this level and not connected to power supply. typeset -g POWERLEVEL9K_BATTERY_LOW_THRESHOLD=20 typeset -g POWERLEVEL9K_BATTERY_LOW_FOREGROUND=160 # Show battery in green when it's charging or fully charged. typeset -g POWERLEVEL9K_BATTERY_{CHARGING,CHARGED}_FOREGROUND=70 # Show battery in yellow when it's discharging. typeset -g POWERLEVEL9K_BATTERY_DISCONNECTED_FOREGROUND=178 # Battery pictograms going from low to high level of charge. typeset -g POWERLEVEL9K_BATTERY_STAGES='\uf58d\uf579\uf57a\uf57b\uf57c\uf57d\uf57e\uf57f\uf580\uf581\uf578' # Don't show the remaining time to charge/discharge. typeset -g POWERLEVEL9K_BATTERY_VERBOSE=false #####################################[ wifi: wifi speed ]##################################### # WiFi color. typeset -g POWERLEVEL9K_WIFI_FOREGROUND=68 # Custom icon. # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='⭐' # Use different colors and icons depending on signal strength ($P9K_WIFI_BARS). # # # Wifi colors and icons for different signal strength levels (low to high). # typeset -g my_wifi_fg=(68 68 68 68 68) # <-- change these values # typeset -g my_wifi_icon=('WiFi' 'WiFi' 'WiFi' 'WiFi' 'WiFi') # <-- change these values # # typeset -g POWERLEVEL9K_WIFI_CONTENT_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}$P9K_WIFI_LAST_TX_RATE Mbps' # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}${my_wifi_icon[P9K_WIFI_BARS+1]}' # # The following parameters are accessible within the expansions: # # Parameter | Meaning # ----------------------+--------------- # P9K_WIFI_SSID | service set identifier, a.k.a. network name # P9K_WIFI_LINK_AUTH | authentication protocol such as "wpa2-psk" or "none"; empty if unknown # P9K_WIFI_LAST_TX_RATE | wireless transmit rate in megabits per second # P9K_WIFI_RSSI | signal strength in dBm, from -120 to 0 # P9K_WIFI_NOISE | noise in dBm, from -120 to 0 # P9K_WIFI_BARS | signal strength in bars, from 0 to 4 (derived from P9K_WIFI_RSSI and P9K_WIFI_NOISE) ####################################[ time: current time ]#################################### # Current time color. typeset -g POWERLEVEL9K_TIME_FOREGROUND=66 # Format for the current time: 09:51:02. See `man 3 strftime`. typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%H:%M:%S}' # If set to true, time will update when you hit enter. This way prompts for the past # commands will contain the start times of their commands as opposed to the default # behavior where they contain the end times of their preceding commands. typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false # Custom icon. # typeset -g POWERLEVEL9K_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' # Custom prefix. typeset -g POWERLEVEL9K_TIME_PREFIX='%fat ' # Example of a user-defined prompt segment. Function prompt_example will be called on every # prompt if `example` prompt segment is added to POWERLEVEL9K_LEFT_PROMPT_ELEMENTS or # POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS. It displays an icon and orange text greeting the user. # # Type `p10k help segment` for documentation and a more sophisticated example. function prompt_example() { p10k segment -f 208 -i '⭐' -t 'hello, %n' } # User-defined prompt segments may optionally provide an instant_prompt_* function. Its job # is to generate the prompt segment for display in instant prompt. See # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. # # Powerlevel10k will call instant_prompt_* at the same time as the regular prompt_* function # and will record all `p10k segment` calls it makes. When displaying instant prompt, Powerlevel10k # will replay these calls without actually calling instant_prompt_*. It is imperative that # instant_prompt_* always makes the same `p10k segment` calls regardless of environment. If this # rule is not observed, the content of instant prompt will be incorrect. # # Usually, you should either not define instant_prompt_* or simply call prompt_* from it. If # instant_prompt_* is not defined for a segment, the segment won't be shown in instant prompt. function instant_prompt_example() { # Since prompt_example always makes the same `p10k segment` calls, we can call it from # instant_prompt_example. This will give us the same `example` prompt segment in the instant # and regular prompts. prompt_example } # User-defined prompt segments can be customized the same way as built-in segments. # typeset -g POWERLEVEL9K_EXAMPLE_FOREGROUND=208 # typeset -g POWERLEVEL9K_EXAMPLE_VISUAL_IDENTIFIER_EXPANSION='⭐' # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt # when accepting a command line. Supported values: # # - off: Don't change prompt when accepting a command line. # - always: Trim down prompt when accepting a command line. # - same-dir: Trim down prompt when accepting a command line unless this is the first command # typed after changing current working directory. typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=always # Instant prompt mode. # # - off: Disable instant prompt. Choose this if you've tried instant prompt and found # it incompatible with your zsh configuration files. # - quiet: Enable instant prompt and don't print warnings when detecting console output # during zsh initialization. Choose this if you've read and understood # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. # - verbose: Enable instant prompt and print a warning when detecting console output during # zsh initialization. Choose this if you've never tried instant prompt, haven't # seen the warning, or if you are unsure what this all means. typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized. # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you # really need it. typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true # If p10k is already loaded, reload configuration. # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true. (( ! $+functions[p10k] )) || p10k reload } # Tell `p10k configure` which file it should overwrite. typeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a} (( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]} 'builtin' 'unset' 'p10k_config_opts'
82691686d16d3f5e93cc4d022f6c53f4584ddc1d
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/linear_algebra/finsupp.lean
06365669fbc22993926044d93a020f7cd7ee3446
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,917
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import data.finsupp.basic import linear_algebra.basic /-! # Properties of the semimodule `α →₀ M` Given an `R`-semimodule `M`, the `R`-semimodule structure on `α →₀ M` is defined in `data.finsupp.basic`. In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}` interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps: * `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map; * `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map; * `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a linear map; * `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`; * `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`; * `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with coefficients `l i`; * `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s` and codomain `submodule.span R (v '' s)`; * `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported on `s` and the functions `s →₀ M`; * `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`; * `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`; * `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to `supported M R t`; * `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃ β` and `e' : M ≃ₗ[R] N`. ## Tags function with finite support, semimodule, linear algebra -/ noncomputable theory open set linear_map submodule open_locale classical big_operators namespace finsupp variables {α : Type*} {M : Type*} {N : Type*} {R : Type*} variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] /-- Interpret `finsupp.single a` as a linear map. -/ def lsingle (a : α) : M →ₗ[R] (α →₀ M) := { map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a } /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) : φ = ψ := lhom_ext $ λ a, linear_map.congr_fun (h a) /-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/ def lapply (a : α) : (α →₀ M) →ₗ[R] M := { map_smul' := assume a b, rfl, ..finsupp.apply_add_hom a } section lsubtype_domain variables (s : set α) /-- Interpret `finsupp.subtype_domain s` as a linear map. -/ def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := ⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩ lemma lsubtype_domain_apply (f : α →₀ M) : (lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain @[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b := rfl @[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ := ker_eq_bot_of_injective (single_injective a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ := begin simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ := begin refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _), rw [← sum_single f], refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem a $ set.mem_image_of_mem _ trivial) end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) := begin refine disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right s) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right t) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨his, hit⟩).elim }, exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set M) (a : α) : submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) := by rw ← span_image; refl variables (M R) /-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/ def supported (s : set α) : submodule R (α →₀ M) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end variables {M} lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s := iff.rfl lemma mem_supported' {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 := by haveI := classical.dec_pred (λ (x : α), x ∈ s); simp [mem_supported, set.subset_def, not_imp_comm] lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h) lemma supported_eq_span_single (s : set α) : supported R R s = span R ((λ i, single i 1) '' s) := begin refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm, { rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp }, { rw ← l.sum_single, refine sum_mem _ (λ i il, _), convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _, { simp }, apply subset_span, apply set.mem_image_of_mem _ (hl il) } end variables (M R) /-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/ def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s := linear_map.cod_restrict _ { to_fun := filter (∈ s), map_add' := λ l₁ l₂, filter_add, map_smul' := λ a l, filter_smul } (λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l) variables {M R} section @[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) : ((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl end theorem restrict_dom_comp_subtype (s : set α) : (restrict_dom M R s).comp (submodule.subtype _) = linear_map.id := begin ext l a, by_cases a ∈ s; simp [h], exact ((mem_supported' R l.1).1 l.2 a h).symm end theorem range_restrict_dom (s : set α) : (restrict_dom M R s).range = ⊤ := begin have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s), rw [restrict_dom_comp_subtype, linear_map.range_id] at this, exact eq_top_mono (submodule.map_mono le_top) this.symm end theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, apply finsupp.induction l, {exact zero_mem _}, refine λ x a l hl a0, add_mem _ _, by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff] theorem supported_inter (s t : set α) : supported M R (s ∩ t) = supported M R s ⊓ supported M R t := by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) : disjoint (supported M R s) (supported M R t) := disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty] theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} : disjoint (supported M R s) (supported M R t) ↔ disjoint s t := begin refine ⟨λ h x hx, _, disjoint_supported_supported⟩, rcases exists_ne (0 : M) with ⟨y, hy⟩, have := h ⟨single_mem_supported R y hx.1, single_mem_supported R y hx.2⟩, rw [mem_bot, single_eq_zero] at this, exact hy this end /-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between `supported M R s` and `s →₀ M`. -/ def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := begin let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M, refine F.to_linear_equiv _, have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))) := rfl, rw this, exact linear_map.is_linear _ end /-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to `N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`. We define this as an additive equivalence. For a commutative `R`, this equivalence can be upgraded further to a linear equivalence. -/ def lsum : (α → M →ₗ[R] N) ≃+ ((α →₀ M) →ₗ[R] N) := { to_fun := λ F, { to_fun := λ d, d.sum (λ i, F i), map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add, map_smul' := λ c f, by simp [sum_smul_index', smul_sum] }, inv_fun := λ F x, F.comp (lsingle x), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp } } @[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) : finsupp.lsum f l = l.sum (λ b, f b) := rfl theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) : finsupp.lsum f (finsupp.single i m) = f i m := finsupp.sum_single_index (f i).map_zero theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) : lsum.symm f x = f.comp (lsingle x) := rfl section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) /-- Interpret `finsupp.lmap_domain` as a linear map. -/ def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := ⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩ @[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) : (lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl @[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id := linear_map.ext $ λ l, map_domain_id theorem lmap_domain_comp (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) := linear_map.ext $ λ l, map_domain_comp theorem supported_comap_lmap_domain (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) := λ l (hl : ↑l.support ⊆ f ⁻¹' s), show ↑(map_domain f l).support ⊆ s, begin rw [← set.image_subset_iff, ← finset.coe_image] at hl, exact set.subset.trans map_domain_support hl end theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) : (supported M R s).map (lmap_domain M R f) = supported M R (f '' s) := begin inhabit α, refine le_antisymm (map_le_iff_le_comap.2 $ le_trans (supported_mono $ set.subset_preimage_image _ _) (supported_comap_lmap_domain _ _ _ _)) _, intros l hl, refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩, { rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩, exact function.inv_fun_on_mem (by simpa using hl hc) }, { rw [← linear_map.comp_apply, ← lmap_domain_comp], refine (map_domain_congr $ λ c hc, _).trans map_domain_id, exact function.inv_fun_on_eq (by simpa using hl hc) } end theorem lmap_domain_disjoint_ker (f : α → α') {s : set α} (H : ∀ a b ∈ s, f a = f b → a = b) : disjoint (supported M R s) (lmap_domain M R f).ker := begin rintro l ⟨h₁, h₂⟩, rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂, simp, ext x, haveI := classical.dec_pred (λ x, x ∈ s), by_cases xs : x ∈ s, { have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl}, rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this, { simpa [finsupp.single_apply] }, { intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] }, { simp {contextual := tt} } }, { by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) } end end lmap_domain section total variables (α) {α' : Type*} (M) {M' : Type*} (R) [add_comm_monoid M'] [semimodule R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total : (α →₀ R) →ₗ M := finsupp.lsum (λ i, linear_map.id.smul_right (v i)) variables {α M v} theorem total_apply (l : α →₀ R) : finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α} (hs : l ∈ supported R R (↑s : set α)) : finsupp.total α M R v l = s.sum (λ i, l i • v i) := finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul] @[simp] theorem total_single (c : R) (a : α) : finsupp.total α M R v (single a c) = c • (v a) := by simp [total_apply, sum_single_index] theorem total_unique [unique α] (l : α →₀ R) (v) : finsupp.total α M R v l = l (default α) • v (default α) := by rw [← total_single, ← unique_single l] theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := begin apply range_eq_top.2, intros x, apply exists.elim (h x), exact λ i hi, ⟨single i 1, by simp [hi]⟩ end lemma range_total : (finsupp.total α M R v).range = span R (range v) := begin ext x, split, { intros hx, rw [linear_map.mem_range] at hx, rcases hx with ⟨l, hl⟩, rw ← hl, rw finsupp.total_apply, unfold finsupp.sum, apply sum_mem (span R (range v)), exact λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i)) }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [mem_coe, linear_map.mem_range], use finsupp.single i 1, simp [hi] } end theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) := by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) : (finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply] theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := begin have : map_domain f l = emb_domain ⟨f, hf⟩ l, { rw emb_domain_eq_map_domain ⟨f, hf⟩, refl }, rw this, apply total_emb_domain R ⟨f, hf⟩ l end theorem span_eq_map_total (s : set α): span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := begin apply span_eq_of_le, { intros x hx, rw set.mem_image at hx, apply exists.elim hx, intros i hi, exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ }, { refine map_le_iff_le_comap.2 (λ z hz, _), have : ∀i, z i • v i ∈ span R (v '' s), { intro c, haveI := classical.dec_pred (λ x, x ∈ s), by_cases c ∈ s, { exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) }, { simp [(finsupp.mem_supported' R _).1 hz _ h] } }, refine sum_mem _ _, simp [this] } end theorem mem_span_iff_total {s : set α} {x : M} : x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x := by rw span_eq_map_total; simp variables (α) (M) (v) /-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a subset of the vectors in `v`, mapping it to the span of those vectors. The subset is indicated by a set `s : set α` of indices. -/ protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) := linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $ λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _) theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := begin ext l, simp [total_apply], rw sum_map_domain_index; simp [add_smul], end lemma total_comap_domain (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) := by rw finsupp.total_apply; refl lemma total_on_finset {s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s): finsupp.total α M R g (finsupp.on_finset s f hf) = finset.sum s (λ (x : α), f x • g x) := begin simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset], rw finset.sum_filter_of_ne, intros x hx h, contrapose! h, simp [h], end end total /-- An equivalence of domains induces a linear equivalence of finitely supported functions. -/ protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv (lmap_domain M R e).map_smul @[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m := by simp [finsupp.dom_lcongr, finsupp.dom_congr, map_domain_single] /-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/ noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) : supported M R s ≃ₗ[R] supported M R t := begin haveI := classical.dec_pred (λ x, x ∈ s), haveI := classical.dec_pred (λ x, x ∈ t), refine linear_equiv.trans (finsupp.supported_equiv_finsupp s) (linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end /-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the corresponding finitely supported functions. -/ def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) := (finsupp.dom_lcongr e₁).trans { to_fun := map_range e₂ e₂.map_zero, inv_fun := map_range e₂.symm e₂.symm.map_zero, left_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih, by rw [map_range_add e₂.map_add, map_range_add e₂.symm.map_add, map_range_single, map_range_single, e₂.symm_apply_apply, ih], right_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih, by rw [map_range_add e₂.symm.map_add, map_range_add e₂.map_add, map_range_single, map_range_single, e₂.apply_symm_apply, ih], map_add' := map_range_add e₂.map_add, map_smul' := λ c f, finsupp.induction f (by rw [smul_zero, map_range_zero, smul_zero]) $ λ a b f ha hb ih, by rw [smul_add, smul_single, map_range_add e₂.map_add, map_range_single, e₂.map_smul, ih, map_range_add e₂.map_add, smul_add, map_range_single, smul_single] } @[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (i : ι) (m : M) : lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) := by simp [lcongr] end finsupp variables {R : Type*} {M : Type*} {N : Type*} variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] lemma linear_map.map_finsupp_total (f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) : f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l := by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul] lemma submodule.exists_finset_of_mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) : ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := begin obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m, { have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _, rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm }, let t : finset M := f.support, have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i, { intros x, rw finsupp.mem_supported at hf, specialize hf x.2, rwa set.mem_Union at hf }, choose g hg using ht, let s : finset ι := finset.univ.image g, use s, simp only [mem_supr, supr_le_iff], assume N hN, rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe], apply N.sum_mem, assume x hx, apply submodule.smul_mem, let i : ι := g ⟨x, hx⟩, have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ }, exact hN i hi (hg _), end lemma mem_span_finset {s : finset M} {x : M} : x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x := ⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_iff_total _).1 (show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in ⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩, λ ⟨f, hf⟩, hf ▸ sum_mem _ (λ i hi, smul_mem _ _ $ subset_span hi)⟩
f4d965c577ee75b5088a25c34ffcf8d27d0c9a08
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/data/quot.lean
55e0da8547ed20d243f8e29a2c486cecf7c58a6f
[ "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
9,374
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 Quotient types. -/ prelude /- We import propext here, otherwise we would need a quot.lift for propositions. -/ import init.data.sigma.basic init.logic init.propext init.data.setoid universes u v -- iff can now be used to do substitutions in a calculation attribute [subst] lemma iff_subst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := eq.subst (propext h₁) h₂ namespace quot constant sound : Π {α : Type u} {r : α → α → Prop} {a b : α}, r a b → quot.mk r a = quot.mk r b attribute [elab_as_eliminator] lift ind protected lemma lift_beta {α : Type u} {r : α → α → Prop} {β : Type v} (f : α → β) (c : ∀ a b, r a b → f a = f b) (a : α) : lift f c (quot.mk r a) = f a := rfl protected lemma ind_beta {α : Type u} {r : α → α → Prop} {β : quot r → Prop} (p : ∀ a, β (quot.mk r a)) (a : α) : (ind p (quot.mk r a) : β (quot.mk r a)) = p a := rfl attribute [reducible, elab_as_eliminator] protected def lift_on {α : Type u} {β : Type v} {r : α → α → Prop} (q : quot r) (f : α → β) (c : ∀ a b, r a b → f a = f b) : β := lift f c q attribute [elab_as_eliminator] protected lemma induction_on {α : Type u} {r : α → α → Prop} {β : quot r → Prop} (q : quot r) (h : ∀ a, β (quot.mk r a)) : β q := ind h q lemma exists_rep {α : Type u} {r : α → α → Prop} (q : quot r) : ∃ a : α, (quot.mk r a) = q := quot.induction_on q (λ a, ⟨a, rfl⟩) section variable {α : Type u} variable {r : α → α → Prop} variable {β : quot r → Type v} local notation `⟦`:max a `⟧` := quot.mk r a attribute [reducible] protected def indep (f : Π a, β ⟦a⟧) (a : α) : Σ q, β q := ⟨⟦a⟧, f a⟩ protected lemma indep_coherent (f : Π a, β ⟦a⟧) (h : ∀ (a b : α) (p : r a b), (eq.rec (f a) (sound p) : β ⟦b⟧) = f b) : ∀ a b, r a b → quot.indep f a = quot.indep f b := λ a b e, sigma.eq (sound e) (h a b e) protected lemma lift_indep_pr1 (f : Π a, β ⟦a⟧) (h : ∀ (a b : α) (p : r a b), (eq.rec (f a) (sound p) : β ⟦b⟧) = f b) (q : quot r) : (lift (quot.indep f) (quot.indep_coherent f h) q).1 = q := quot.ind (λ (a : α), eq.refl (quot.indep f a).1) q attribute [reducible, elab_as_eliminator] protected def rec (f : Π a, β ⟦a⟧) (h : ∀ (a b : α) (p : r a b), (eq.rec (f a) (sound p) : β ⟦b⟧) = f b) (q : quot r) : β q := eq.rec_on (quot.lift_indep_pr1 f h q) ((lift (quot.indep f) (quot.indep_coherent f h) q).2) attribute [reducible, elab_as_eliminator] protected def rec_on (q : quot r) (f : Π a, β ⟦a⟧) (h : ∀ (a b : α) (p : r a b), (eq.rec (f a) (sound p) : β ⟦b⟧) = f b) : β q := quot.rec f h q attribute [reducible, elab_as_eliminator] protected def rec_on_subsingleton [h : ∀ a, subsingleton (β ⟦a⟧)] (q : quot r) (f : Π a, β ⟦a⟧) : β q := quot.rec f (λ a b h, subsingleton.elim _ (f b)) q attribute [reducible, elab_as_eliminator] protected def hrec_on (q : quot r) (f : Π a, β ⟦a⟧) (c : ∀ (a b : α) (p : r a b), f a == f b) : β q := quot.rec_on q f (λ a b p, eq_of_heq (calc (eq.rec (f a) (sound p) : β ⟦b⟧) == f a : eq_rec_heq (sound p) (f a) ... == f b : c a b p)) end end quot def quotient {α : Type u} (s : setoid α) := @quot α setoid.r namespace quotient protected def mk {α : Type u} [s : setoid α] (a : α) : quotient s := quot.mk setoid.r a notation `⟦`:max a `⟧`:0 := quotient.mk a def sound {α : Type u} [s : setoid α] {a b : α} : a ≈ b → ⟦a⟧ = ⟦b⟧ := quot.sound attribute [reducible, elab_as_eliminator] protected def lift {α : Type u} {β : Type v} [s : setoid α] (f : α → β) : (∀ a b, a ≈ b → f a = f b) → quotient s → β := quot.lift f attribute [elab_as_eliminator] protected lemma ind {α : Type u} [s : setoid α] {β : quotient s → Prop} : (∀ a, β ⟦a⟧) → ∀ q, β q := quot.ind attribute [reducible, elab_as_eliminator] protected def lift_on {α : Type u} {β : Type v} [s : setoid α] (q : quotient s) (f : α → β) (c : ∀ a b, a ≈ b → f a = f b) : β := quot.lift_on q f c attribute [elab_as_eliminator] protected lemma induction_on {α : Type u} [s : setoid α] {β : quotient s → Prop} (q : quotient s) (h : ∀ a, β ⟦a⟧) : β q := quot.induction_on q h lemma exists_rep {α : Type u} [s : setoid α] (q : quotient s) : ∃ a : α, ⟦a⟧ = q := quot.exists_rep q section variable {α : Type u} variable [s : setoid α] variable {β : quotient s → Type v} protected def rec (f : Π a, β ⟦a⟧) (h : ∀ (a b : α) (p : a ≈ b), (eq.rec (f a) (quotient.sound p) : β ⟦b⟧) = f b) (q : quotient s) : β q := quot.rec f h q attribute [reducible, elab_as_eliminator] protected def rec_on (q : quotient s) (f : Π a, β ⟦a⟧) (h : ∀ (a b : α) (p : a ≈ b), (eq.rec (f a) (quotient.sound p) : β ⟦b⟧) = f b) : β q := quot.rec_on q f h attribute [reducible, elab_as_eliminator] protected def rec_on_subsingleton [h : ∀ a, subsingleton (β ⟦a⟧)] (q : quotient s) (f : Π a, β ⟦a⟧) : β q := @quot.rec_on_subsingleton _ _ _ h q f attribute [reducible, elab_as_eliminator] protected def hrec_on (q : quotient s) (f : Π a, β ⟦a⟧) (c : ∀ (a b : α) (p : a ≈ b), f a == f b) : β q := quot.hrec_on q f c end section universes u_a u_b u_c variables {α : Type u_a} {β : Type u_b} {φ : Type u_c} variables [s₁ : setoid α] [s₂ : setoid β] include s₁ s₂ attribute [reducible, elab_as_eliminator] protected def lift₂ (f : α → β → φ)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (q₁ : quotient s₁) (q₂ : quotient s₂) : φ := quotient.lift (λ (a₁ : α), quot.lift (f a₁) (λ (a b : β), c a₁ a a₁ b (setoid.refl a₁)) q₂) (λ (a b : α) (h : a ≈ b), @quotient.ind β s₂ (λ (a_1 : quotient s₂), (quotient.lift (f a) (λ (a_1 b : β), c a a_1 a b (setoid.refl a)) a_1) = (quotient.lift (f b) (λ (a b_1 : β), c b a b b_1 (setoid.refl b)) a_1)) (λ (a' : β), c a a' b a' h (setoid.refl a')) q₂) q₁ attribute [reducible, elab_as_eliminator] protected def lift_on₂ (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → φ) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : φ := quotient.lift₂ f c q₁ q₂ attribute [elab_as_eliminator] protected lemma ind₂ {φ : quotient s₁ → quotient s₂ → Prop} (h : ∀ a b, φ ⟦a⟧ ⟦b⟧) (q₁ : quotient s₁) (q₂ : quotient s₂) : φ q₁ q₂ := quotient.ind (λ a₁, quotient.ind (λ a₂, h a₁ a₂) q₂) q₁ attribute [elab_as_eliminator] protected lemma induction_on₂ {φ : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ a b, φ ⟦a⟧ ⟦b⟧) : φ q₁ q₂ := quotient.ind (λ a₁, quotient.ind (λ a₂, h a₁ a₂) q₂) q₁ attribute [elab_as_eliminator] protected lemma induction_on₃ [s₃ : setoid φ] {δ : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ a b c, δ ⟦a⟧ ⟦b⟧ ⟦c⟧) : δ q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, h a₁ a₂ a₃) q₃) q₂) q₁ end section exact variable {α : Type u} variable [s : setoid α] include s private def rel (q₁ q₂ : quotient s) : Prop := quotient.lift_on₂ q₁ q₂ (λ a₁ a₂, a₁ ≈ a₂) (λ a₁ a₂ b₁ b₂ a₁b₁ a₂b₂, propext (iff.intro (λ a₁a₂, setoid.trans (setoid.symm a₁b₁) (setoid.trans a₁a₂ a₂b₂)) (λ b₁b₂, setoid.trans a₁b₁ (setoid.trans b₁b₂ (setoid.symm a₂b₂))))) local infix `~` := rel private lemma rel.refl : ∀ q : quotient s, q ~ q := λ q, quot.induction_on q (λ a, setoid.refl a) private lemma eq_imp_rel {q₁ q₂ : quotient s} : q₁ = q₂ → q₁ ~ q₂ := assume h, eq.rec_on h (rel.refl q₁) lemma exact {a b : α} : ⟦a⟧ = ⟦b⟧ → a ≈ b := assume h, eq_imp_rel h end exact section universes u_a u_b u_c variables {α : Type u_a} {β : Type u_b} variables [s₁ : setoid α] [s₂ : setoid β] include s₁ s₂ attribute [reducible, elab_as_eliminator] protected def rec_on_subsingleton₂ {φ : quotient s₁ → quotient s₂ → Type u_c} [h : ∀ a b, subsingleton (φ ⟦a⟧ ⟦b⟧)] (q₁ : quotient s₁) (q₂ : quotient s₂) (f : Π a b, φ ⟦a⟧ ⟦b⟧) : φ q₁ q₂:= @quotient.rec_on_subsingleton _ s₁ (λ q, φ q q₂) (λ a, quotient.ind (λ b, h a b) q₂) q₁ (λ a, quotient.rec_on_subsingleton q₂ (λ b, f a b)) end end quotient open decidable instance {α : Type u} {s : setoid α} [d : ∀ a b : α, decidable (a ≈ b)] : decidable_eq (quotient s) := λ q₁ q₂ : quotient s, quotient.rec_on_subsingleton₂ q₁ q₂ (λ a₁ a₂, match (d a₁ a₂) with | (is_true h₁) := is_true (quotient.sound h₁) | (is_false h₂) := is_false (λ h, absurd (quotient.exact h) h₂) end)
5cb0269719e27c5dea9a5badb3d16fe2cbf7b3ce
ac60dab17014edd769c9618cc1569ce8c960a6a5
/src/gol.lean
c7c9ec410fa71feb9b47479597f70abae1a06001
[ "MIT" ]
permissive
frankSil/CAExtensions
20e1f856b3ad775d5e8dc8877614dbcd58c77901
f5c74fd9a806696c73497d9abd45b7315f45379f
refs/heads/master
1,608,706,941,607
1,586,193,337,000
1,586,193,337,000
237,077,434
0
0
null
null
null
null
UTF-8
Lean
false
false
3,429
lean
import cautomaton utils data.nat.basic open utils namespace gol section gol open list function inductive cellT | A | D open cellT def cellT_str : cellT → string | A := "X" | D := " " instance cellT_to_str : has_to_string cellT := ⟨cellT_str⟩ instance cellT_repr : has_repr cellT := ⟨cellT_str⟩ instance cellT_deceq : decidable_eq cellT := λl r, begin cases l; cases r; try {exact is_true rfl}; apply is_false; trivial end instance : has_coe cellT bool := ⟨λx, x = A⟩ instance coe_back : has_coe bool cellT := ⟨λx, if x then A else D⟩ def step (cell : cellT) (alive_neighbours : ℕ) : cellT := if cell then if alive_neighbours < 2 then D else if bor (alive_neighbours = 2) (alive_neighbours = 3) then A else D else if alive_neighbours = 3 then A else D def gol_step (cell : cellT) (neigh : list cellT) := step cell (count_at_single neigh A) end gol open cellT attribute [reducible] def gol := cautomaton cellT def mk_gol (g : vec_grid₀ cellT) : gol := ⟨g, D, cautomatons.moore, sum.inl cautomatons.ext_one, gol_step⟩ def empty := fgrid₀.mk 2 2 dec_trivial ⟨0, 1⟩ (λx y, D) def empty_g := vec_grid₀.mk ⟨2, 2, dec_trivial, ⟨[D, D, D, D], rfl⟩⟩ ⟨0, 1⟩ def empty_aut : gol := mk_gol empty def empty_aut_g : gol := mk_gol empty_g def row := fgrid₀.mk 1 3 dec_trivial ⟨0, 0⟩ (λx y, A) def row_gol : gol := mk_gol row def col := vec_grid₀.mk ⟨3, 1, dec_trivial, ⟨[A, A, A], rfl⟩⟩ ⟨1, -1⟩ def col_gol : gol := mk_gol col def box := fgrid₀.mk 2 2 dec_trivial ⟨0, 1⟩ (λx y, A) def box_gol : gol := mk_gol box def dies := vec_grid₀.mk ⟨3, 2, dec_trivial, ⟨[A, D, A, D, D, A], rfl⟩⟩ ⟨0, 1⟩ def dies_gol : gol := mk_gol dies private lemma col_even {n} (h : n % 2 = 0) {a} {g} (h₂ : a = mk_gol g) (h₃ : a = col_gol) : step_n a n = a := begin unfold step_n, rw @periode_cycle _ _ _ _ 2, {rw [h, iterate_zero]}, {rw h₂, subst h₃, rw ← h₂, refl} end lemma col_gol_even {n} (h : n % 2 = 0) : step_n col_gol n = col_gol := col_even h rfl rfl private lemma col_row {n} (h : n % 2 = 1) {a} {g} (h₂ : a = mk_gol g) (h₃ : a = col_gol) : step_n a n = row_gol := begin unfold step_n, rw @periode_cycle _ _ _ _ 2, { rw [ h, iterate_one, iterate_zero, h₃ ]; try { by simp [col_gol, row_gol, mk_gol] }, refl }, {rw h₃, refl} end lemma col_row_odd {n} (h : n % 2 = 1) : step_n col_gol n = row_gol := col_row h rfl rfl open list prod def find_period (max : ℕ) (a : gol) : option ℕ := let incr_iota := list.reverse $ list.iota max in prod.snd <$> list.find ((=tt) ∘ prod.fst) ( list.zip (list.map ((=a.g) ∘ cautomaton.g ∘ (step_n a)) incr_iota) incr_iota ) meta def solve_periodic_gol_n (n : ℕ) : tactic unit := do { `(periodic %%a) ← tactic.target, t ← tactic.infer_type a, aut ← tactic.eval_expr (cautomaton _) a, let val := find_period n aut in do v ← val, tactic.existsi `(v), tactic.split, tactic.exact_dec_trivial, tactic.reflexivity } <|> tactic.fail "Unable to discover periodicity. Try to increase the depth of search." meta def periodic_aut : tactic unit := solve_periodic_gol_n 16 example : periodic col_gol := ⟨2, ⟨dec_trivial, rfl⟩⟩ example : periodic col_gol := by periodic_aut end gol
6c53b1fbc19f4e023b5c633f3da1b616df31313e
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/analysis/convex/basic.lean
e8642c5c93898342dfe16fb856da87f42607562d
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
37,849
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 -/ import data.set.intervals import data.complex.module import algebra.pointwise /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. -/ universes u' u v w x variables {E : Type u} {F : Type v} {ι : Type w} {ι' : Type x} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set E} open set open_locale classical local notation `I` := (Icc 0 1 : set ℝ) local attribute [instance] set.pointwise_add set.smul_set section sets /-! ### Segment -/ /-- 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} local notation `[`x `, ` y `]` := segment x y 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 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 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 segment_eq_image (x y : E) : segment x y = (λ (θ : ℝ), (1 - θ) • x + θ • y) '' I := 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 segment_eq_image' (x y : E) : segment x y = (λ (θ : ℝ), x + θ • (y - x)) '' I := by { convert segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_image₂ (x y : E) : 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 [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (λ t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_add_left_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ 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 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 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 /-! ### Convexity of sets -/ /-- Convexity of sets -/ def convex (s : set E) := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s 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 (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x, y] ⊆ s := by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] 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 /-- 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 rintros hA a b ha hb hab w ⟨au, ⟨u, hu, rfl⟩, bv, ⟨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_pointwise_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- 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 := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (∅ : set E) := by finish 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_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 convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩ a b ha hb hab, exact ⟨a • x + b • y, hs hx hy ha hb hab, by simp only [hf.add,hf.smul]⟩ end lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) := hs.is_linear_image f.is_linear lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (preimage f s) := begin intros x y hx hy a b ha hb hab, convert hs hx hy ha hb hab, simp only [mem_preimage, hf.add, hf.smul] end lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) : convex (preimage f s) := hs.is_linear_preimage f.is_linear 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 lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) := begin rw smul_set_eq_image, exact hs.is_linear_image (is_linear_map.is_linear_map_smul c) end lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) := hs.is_linear_preimage (is_linear_map.is_linear_map_smul c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw pointwise_add_eq_image, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (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.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) := begin convert (convex_singleton z).add hs, ext x, simp [set.mem_image, mem_pointwise_add, eq_comm] end lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) := begin convert (hs.smul c).translate z using 1, erw [smul_set_eq_image, ←image_comp] end lemma convex_real_iff {s : set ℝ} : convex s ↔ ∀ {x y}, x ∈ s → y ∈ s → Icc x y ⊆ s := begin simp only [convex_iff_segment_subset, segment_eq_Icc'], split; intros h x y hx hy, { cases le_or_lt x y with hxy hxy, { simpa [hxy] using h hx hy }, { simp [hxy] } }, { apply h; cases le_total x y; simp [*] } end lemma convex_Iio (r : ℝ) : convex (Iio r) := convex_real_iff.2 $ λ x y hx hy z hz, lt_of_le_of_lt hz.2 hy lemma convex_Ioi (r : ℝ) : convex (Ioi r) := convex_real_iff.2 $ λ x y hx hy z hz, lt_of_lt_of_le hx hz.1 lemma convex_Iic (r : ℝ) : convex (Iic r) := convex_real_iff.2 $ λ x y hx hy z hz, le_trans hz.2 hy lemma convex_Ici (r : ℝ) : convex (Ici r) := convex_real_iff.2 $ λ x y hx hy z hz, le_trans hx hz.1 lemma convex_Ioo (r : ℝ) (s : ℝ) : convex (Ioo r s) := (convex_Ioi _).inter (convex_Iio _) lemma convex_Ico (r : ℝ) (s : ℝ) : convex (Ico r s) := (convex_Ici _).inter (convex_Iio _) lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := (convex_Ioi _).inter (convex_Iic _) lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := (convex_Ici _).inter (convex_Iic _) lemma convex_segment (a b : E) : convex [a, b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λz : E, a + z) ∘ (λt:ℝ, t • (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end 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_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := (convex_Iic 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 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 show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets section functions local notation `[`x `, ` y `]` := segment x y /-! ### Convex functions -/ /-- Convexity of functions -/ def convex_on (s : set E) (f : E → ℝ) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a * f x + b * f y variables {t : set E} {f g : E → ℝ} lemma convex_on_iff_div: convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) * f x + (b/(a+b)) * f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha hab) (div_nonneg hb hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a * f x + b * f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a * f x + b * f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_mul, hab, one_smul, one_mul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end lemma convex_on.subset (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma convex_on.add (hf : convex_on s f) (hg : convex_on s g) : convex_on s (λx, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a * f x + b * f y) + (a * g x + b * g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a * f x + a * g x + b * f y + b * g y : by linarith ... = a * (f x + g x) + b * (f y + g y) : by simp [mul_add] end lemma convex_on.smul {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s (λx, c * f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c * f (a • x + b • y) ≤ c * (a * f x + b * f y) : mul_le_mul_of_nonneg_left (hf.2 hx hy ha hb hab) hc ... = a * (c * f x) + b * (c * f y) : by rw mul_add; ac_refl end lemma convex_on.le_on_segment' {x y : E} {a b : ℝ} (hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a * f x + b * f y : hf.2 hx hy ha hb hab ... ≤ a * max (f x) (f y) + b * max (f x) (f y) : add_le_add (mul_le_mul_of_nonneg_left (le_max_left _ _) ha) (mul_le_mul_of_nonneg_left (le_max_right _ _) hb) ... ≤ max (f x) (f y) : by rw [←add_mul, hab, one_mul] lemma convex_on.le_on_segment (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab lemma convex_on.convex_le (hf : convex_on s f) (r : ℝ) : convex {x ∈ s | f x ≤ r} := convex_iff_segment_subset.2 $ λ x y hx hy z hz, ⟨hf.1.segment_subset hx.1 hy.1 hz, le_trans (hf.le_on_segment hx.1 hy.1 hz) $ max_le hx.2 hy.2⟩ lemma convex_on.convex_lt (hf : convex_on s f) (r : ℝ) : convex {x ∈ s | f x < r} := convex_iff_segment_subset.2 $ λ x y hx hy z hz, ⟨hf.1.segment_subset hx.1 hy.1 hz, lt_of_le_of_lt (hf.le_on_segment hx.1 hy.1 hz) $ max_lt hx.2 hy.2⟩ lemma convex_on.convex_epigraph (hf : convex_on s f) : convex {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a * f x + b * f y : hf.2 hx hy ha hb hab ... ≤ a * r + b * t : add_le_add (mul_le_mul_of_nonneg_left hr ha) (mul_le_mul_of_nonneg_left ht hb) end lemma convex_on_iff_convex_epigraph : convex_on s f ↔ convex {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end end functions section center_mass /-- Center mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ noncomputable def finset.center_mass (t : finset ι) (w : ι → ℝ) (z : ι → E) : E := (t.sum w)⁻¹ • (t.sum (λ i, w i • z i)) variables (i j : ι) (c : ℝ) (t : finset ι) (w : ι → ℝ) (z : ι → E) open finset (hiding singleton) lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i ≠ j) : ({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i ∉ t) (hw : t.sum w ≠ 0) : (insert i t).center_mass w z = (w i / (w i + t.sum w)) • z i + (t.sum w / (w i + t.sum w)) • t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm], congr' 2, { apply mul_comm }, { rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div_eq_inv] } end lemma finset.center_mass_singleton (hw : w i ≠ 0) : (finset.singleton i).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : t.sum w = 1) : t.center_mass w z = t.sum (λ i, w i • z i) := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E) (hws : s.sum ws = 1) (hwt : t.sum wt = 1) (a b : ℝ) (hab : a + b = 1): a • s.center_mass ws zs + b • t.center_mass wt zt = (s.image sum.inl ∪ t.image sum.inr).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr, ext i, cases i; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ι) (w₁ w₂ : ι → ℝ) (z : ι → E) (hw₁ : s.sum w₁ = 1) (hw₂ : s.sum w₂ = 1) (a b : ℝ) (hab : a + b = 1): a • s.center_mass w₁ z + b • s.center_mass w₂ z = s.center_mass (λ i, a * w₁ i + b * w₂ i) z := have hw : s.sum (λ i, a * w₁ i + b * w₂ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (λ j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity t.sum (λ j, if (i = j) then z i else 0), { congr, ext i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t') (h : ∀ i ∈ t', i ∉ t → w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _) $ λ i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- Center mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (∀ i ∈ t, 0 ≤ w i) → (0 < t.sum w) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s := begin refine finset.induction (by simp [lt_irrefl]) (λ i t hi ht h₀ hpos hmem, _) t, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : t.sum w = 0, { have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t, have wz : t.sum (λ j, w j • z j) = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos, { exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact h₀ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : t.sum w = 1) (hz : ∀ i ∈ t, z i ∈ s) : t.sum (λ i, w i • z i) ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (∀ (t : finset E) (w : E → ℝ), (∀ i ∈ t, 0 ≤ w i) → t.sum w = 1 → (∀ x ∈ t, x ∈ s) → t.sum (λx, w x • x) ∈ s ) := begin refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (λ z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (hpos : 0 < t.sum w) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≤ t.center_mass w (f ∘ z) := begin have hmem' : ∀ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}, from λ i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem h₀ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : t.sum w = 1) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.sum (λ i, w i • z i)) ≤ t.sum (λ i, w i * (f (z i))) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center mass of some points `z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E → ℝ} (h : convex_on s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < t.sum w) (hz : ∀ i ∈ t, z i ∈ s) : ∃ i ∈ t, f (t.center_mass w z) ≤ f (z i) := begin set y := t.center_mass w z, have : f y ≤ t.center_mass w (f ∘ z) := h.map_center_mass_le hw₀ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : ∃ i ∈ t.filter (λ i, w i ≠ 0), f y * w i ≤ w i • (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hw₀ i hi.1) hi.2.symm end end center_mass section convex_hull variable {t : set E} /-- Convex hull of a set `s` is the minimal convex set that includes `s` -/ def convex_hull (s : set E) : set E := ⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t variable (s) lemma subset_convex_hull : s ⊆ convex_hull s := set.subset_Inter $ λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst lemma convex_convex_hull : convex (convex_hull s) := convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id variable {s} lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t) lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s) lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < t.sum w) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → ℝ) (z : ι → E) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : t.sum w = 1) (hz : ∀ i ∈ t, z i ∈ s) , t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, finset.singleton punit.star, λ _, 1, λ _, x, λ _ _, zero_le_one, finset.sum_singleton, λ _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwx₀, hwy₀] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E → ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : ∃ y ∈ s, f x ≤ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hw₀, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one) (λ i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : hs.to_finset.sum w = 1), hs.to_finset.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, replace hx : x ∈ hs.to_finset, from finite.mem_to_finset.2 hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hw₀, hw₁, rfl⟩, exact hs.to_finset.center_mass_mem_convex_hull (λ x hx, hw₀ _ $ finite.mem_to_finset.1 hx) (hw₁.symm ▸ zero_lt_one) (λ x hx, finite.mem_to_finset.1 hx) } end lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ι) [fintype ι] {f : ι → ℝ} /-- Standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) := { f | (∀ x, 0 ≤ f x) ∧ finset.univ.sum f = 1 } lemma std_simplex_eq_inter : std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | finset.univ.sum f = 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 _)] ⟩ /-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ λ(i j:ι), if i = j then (1:ℝ) else 0) = std_simplex ι := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ι)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hw₀, hw₁⟩, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i) (hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) } end variable {ι} /-- Convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `s.sum (λ x, w x • x)`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = (⇑((@finset.univ _ hs.fintype).sum (λ x, (linear_map.proj x : (s → ℝ) →ₗ[ℝ] ℝ).smul_right x.1))) '' (@std_simplex _ hs.fintype) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← range_comp, (∘)], apply congr_arg, convert (subtype.range_val s).symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ι) (x) : f x ∈ I := ⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
11640909d93f1f3df113cb5e6c129f7daeae18e2
78269ad0b3c342b20786f60690708b6e328132b0
/src/library_dev/algebra/lattice/boolean_algebra.lean
e2a21b0e58f7b8d023585ffeecdc0ba14d09eeb1
[]
no_license
dselsam/library_dev
e74f46010fee9c7b66eaa704654cad0fcd2eefca
1b4e34e7fb067ea5211714d6d3ecef5132fc8218
refs/heads/master
1,610,372,841,675
1,497,014,421,000
1,497,014,421,000
86,526,137
0
0
null
1,490,752,133,000
1,490,752,132,000
null
UTF-8
Lean
false
false
4,477
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 Type class hierarchy for Boolean algebras. -/ import .bounded_lattice set_option old_structure_cmd true universes u variables {α : Type u} {x y z : α} namespace lattice class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) section distrib_lattice variables [distrib_lattice α] lemma le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf lemma sup_inf_left {x y z : α} : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf lemma sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp [sup_inf_left, λy:α, @sup_comm α _ y x] lemma inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp [inf_assoc, sup_inf_right] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] lemma inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp [inf_sup_left, λy:α, @inf_comm α _ y x] end distrib_lattice class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α class boolean_algebra α extends bounded_distrib_lattice α, has_neg α, has_sub α := (inf_neg_eq_bot : ∀x:α, x ⊓ - x = ⊥) (sup_neg_eq_top : ∀x:α, x ⊔ - x = ⊤) (sub_eq : ∀x y:α, x - y = x ⊓ - y) section boolean_algebra variables [boolean_algebra α] @[simp] lemma inf_neg_eq_bot : x ⊓ - x = ⊥ := boolean_algebra.inf_neg_eq_bot x @[simp] lemma neg_inf_eq_bot : - x ⊓ x = ⊥ := eq.trans inf_comm inf_neg_eq_bot @[simp] lemma sup_neg_eq_top : x ⊔ - x = ⊤ := boolean_algebra.sup_neg_eq_top x @[simp] lemma neg_sup_eq_top : - x ⊔ x = ⊤ := eq.trans sup_comm sup_neg_eq_top lemma sub_eq : x - y = x ⊓ - y := boolean_algebra.sub_eq x y lemma neg_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : - x = y := have (- x ⊓ x) ⊔ (- x ⊓ y) = (y ⊓ x) ⊔ (y ⊓ - x), by rsimp, have - x ⊓ (x ⊔ y) = y ⊓ (x ⊔ - x), begin [smt] eblast_using inf_sup_left end, by rsimp @[simp] lemma neg_top : - ⊤ = (⊥:α) := neg_unique (by simp) (by simp) @[simp] lemma neg_bot : - ⊥ = (⊤:α) := neg_unique (by simp) (by simp) @[simp] lemma neg_neg : - (- x) = x := neg_unique (by simp) (by simp) lemma neg_eq_neg_of_eq (h : - x = - y) : x = y := have - - x = - - y, from congr_arg has_neg.neg h, by simp [neg_neg] at this; assumption @[simp] lemma neg_eq_neg_iff : - x = - y ↔ x = y := ⟨neg_eq_neg_of_eq, congr_arg has_neg.neg⟩ @[simp] lemma neg_inf : - (x ⊓ y) = -x ⊔ -y := neg_unique -- TODO: try rsimp if it supports custom lemmas (calc (x ⊓ y) ⊓ (- x ⊔ - y) = (y ⊓ (x ⊓ - x)) ⊔ (x ⊓ (y ⊓ - y)) : by rw [inf_sup_left]; ac_refl ... = ⊥ : by simp) (calc (x ⊓ y) ⊔ (- x ⊔ - y) = (- y ⊔ (x ⊔ - x)) ⊓ (- x ⊔ (y ⊔ - y)) : by rw [sup_inf_right]; ac_refl ... = ⊤ : by simp) @[simp] lemma neg_sup : - (x ⊔ y) = -x ⊓ -y := begin [smt] eblast_using [neg_neg, neg_inf] end lemma neg_le_neg (h : y ≤ x) : - x ≤ - y := le_of_inf_eq $ calc -x ⊓ -y = - (x ⊔ y) : neg_sup^.symm ... = -x : congr_arg has_neg.neg $ sup_of_le_left h lemma neg_le_neg_iff_le : - y ≤ - x ↔ x ≤ y := ⟨take h, by note h := neg_le_neg h; simp at h; assumption, neg_le_neg⟩ lemma le_neg_of_le_neg (h : y ≤ - x) : x ≤ - y := have - (- x) ≤ - y, from neg_le_neg h, by simp at this; assumption lemma neg_le_of_neg_le (h : - y ≤ x) : - x ≤ y := have - x ≤ - (- y), from neg_le_neg h, by simp at this; assumption lemma neg_le_iff_neg_le : y ≤ - x ↔ x ≤ - y := ⟨le_neg_of_le_neg, le_neg_of_le_neg⟩ lemma sup_sub_same : x ⊔ (y - x) = x ⊔ y := by simp [sub_eq, sup_inf_left] lemma sub_eq_left (h : x ⊓ y = ⊥) : x - y = x := calc x - y = (x ⊓ -y) ⊔ (x ⊓ y) : by simp [h, sub_eq] ... = (-y ⊓ x) ⊔ (y ⊓ x) : by simp [inf_comm] ... = (-y ⊔ y) ⊓ x : inf_sup_right^.symm ... = x : by simp end boolean_algebra end lattice
d409fc673fb4eb5b40c018581ce0bfdb71fc1b9a
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/polynomial/monic.lean
e88963526cb66e85a3cdb4753d58ef0ffcab1b09
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,429
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.reverse import algebra.associated /-! # Theory of monic polynomials We give several tools for proving that polynomials are monic, e.g. `monic_mul`, `monic_map`. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finset open_locale big_operators namespace polynomial universes u v y variables {R : Type u} {S : Type v} {a b : R} {m n : ℕ} {ι : Type y} section semiring variables [semiring R] {p q r : polynomial R} lemma monic.as_sum {p : polynomial R} (hp : p.monic) : p = X^(p.nat_degree) + (∑ i in range p.nat_degree, C (p.coeff i) * X^i) := begin conv_lhs { rw [p.as_sum_range_C_mul_X_pow, sum_range_succ_comm] }, suffices : C (p.coeff p.nat_degree) = 1, { rw [this, one_mul] }, exact congr_arg C hp end lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : R) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 := begin intro h, rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma monic_map [semiring S] (f : R →+* S) (hp : monic p) : monic (p.map f) := if h : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by begin rw [monic, leading_coeff, coeff_map], suffices : p.coeff (map f p).nat_degree = 1, simp [this], suffices : (map f p).nat_degree = p.nat_degree, rw this, exact hp, rwa nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero _ _), end lemma monic_mul_C_of_leading_coeff_mul_eq_one [nontrivial R] {b : R} (hp : p.leading_coeff * b = 1) : monic (p * C b) := by rw [monic, leading_coeff_mul' _]; simp [leading_coeff_C b, hp] theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, eq_of_zero_eq_one (H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : R) : monic (X + C x) := pow_one (X : polynomial R) ▸ monic_X_pow_add degree_C_le lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : R) = 1 then by haveI := subsingleton_of_zero_eq_one h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := by { rw pow_succ, exact monic_mul hp (monic_pow n) } lemma monic_add_of_left {p q : polynomial R} (hp : monic p) (hpq : degree q < degree p) : monic (p + q) := by rwa [monic, add_comm, leading_coeff_add_of_degree_lt hpq] lemma monic_add_of_right {p q : polynomial R} (hq : monic q) (hpq : degree p < degree q) : monic (p + q) := by rwa [monic, leading_coeff_add_of_degree_lt hpq] namespace monic @[simp] lemma degree_eq_zero_iff_eq_one {p : polynomial R} (hp : p.monic) : p.nat_degree = 0 ↔ p = 1 := begin split; intro h, swap, { rw h, exact nat_degree_one }, have : p = C (p.coeff 0), { rw ← polynomial.degree_le_zero_iff, rwa polynomial.nat_degree_eq_zero_iff_degree_le_zero at h }, rw this, convert C_1, rw ← h, apply hp, end lemma nat_degree_mul {p q : polynomial R} (hp : p.monic) (hq : q.monic) : (p * q).nat_degree = p.nat_degree + q.nat_degree := begin nontriviality R, apply nat_degree_mul', simp [hp.leading_coeff, hq.leading_coeff] end lemma next_coeff_mul {p q : polynomial R} (hp : monic p) (hq : monic q) : next_coeff (p * q) = next_coeff p + next_coeff q := begin nontriviality, simp only [← coeff_one_reverse], rw reverse_mul; simp [coeff_mul, nat.antidiagonal, hp.leading_coeff, hq.leading_coeff, add_comm] end end monic end semiring section comm_semiring variables [comm_semiring R] {p : polynomial R} lemma monic_multiset_prod_of_monic (t : multiset ι) (f : ι → polynomial R) (ht : ∀ i ∈ t, monic (f i)) : monic (t.map f).prod := begin revert ht, refine t.induction_on _ _, { simp }, intros a t ih ht, rw [multiset.map_cons, multiset.prod_cons], exact monic_mul (ht _ (multiset.mem_cons_self _ _)) (ih (λ _ hi, ht _ (multiset.mem_cons_of_mem hi))) end lemma monic_prod_of_monic (s : finset ι) (f : ι → polynomial R) (hs : ∀ i ∈ s, monic (f i)) : monic (∏ i in s, f i) := monic_multiset_prod_of_monic s.1 f hs lemma is_unit_C {x : R} : is_unit (C x) ↔ is_unit x := begin rw [is_unit_iff_dvd_one, is_unit_iff_dvd_one], split, { rintros ⟨g, hg⟩, replace hg := congr_arg (eval 0) hg, rw [eval_one, eval_mul, eval_C] at hg, exact ⟨g.eval 0, hg⟩ }, { rintros ⟨y, hy⟩, exact ⟨C y, by rw [← C_mul, ← hy, C_1]⟩ } end lemma eq_one_of_is_unit_of_monic (hm : monic p) (hpu : is_unit p) : p = 1 := have degree p ≤ 0, from calc degree p ≤ degree (1 : polynomial R) : let ⟨u, hu⟩ := is_unit_iff_dvd_one.1 hpu in if hu0 : u = 0 then begin rw [hu0, mul_zero] at hu, rw [← mul_one p, hu, mul_zero], simp end else have p.leading_coeff * u.leading_coeff ≠ 0, by rw [hm.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero]; exact hu0, by rw [hu, degree_mul' this]; exact le_add_of_nonneg_right (degree_nonneg_iff_ne_zero.2 hu0) ... ≤ 0 : degree_one_le, by rw [eq_C_of_degree_le_zero this, ← nat_degree_eq_zero_iff_degree_le_zero.2 this, ← leading_coeff, hm.leading_coeff, C_1] lemma monic.next_coeff_multiset_prod (t : multiset ι) (f : ι → polynomial R) (h : ∀ i ∈ t, monic (f i)) : next_coeff (t.map f).prod = (t.map (λ i, next_coeff (f i))).sum := begin revert h, refine multiset.induction_on t _ (λ a t ih ht, _), { simp only [multiset.not_mem_zero, forall_prop_of_true, forall_prop_of_false, multiset.map_zero, multiset.prod_zero, multiset.sum_zero, not_false_iff, forall_true_iff], rw ← C_1, rw next_coeff_C_eq_zero }, { rw [multiset.map_cons, multiset.prod_cons, multiset.map_cons, multiset.sum_cons, monic.next_coeff_mul, ih], exacts [λ i hi, ht i (multiset.mem_cons_of_mem hi), ht a (multiset.mem_cons_self _ _), monic_multiset_prod_of_monic _ _ (λ b bs, ht _ (multiset.mem_cons_of_mem bs))] } end lemma monic.next_coeff_prod (s : finset ι) (f : ι → polynomial R) (h : ∀ i ∈ s, monic (f i)) : next_coeff (∏ i in s, f i) = ∑ i in s, next_coeff (f i) := monic.next_coeff_multiset_prod s.1 f h end comm_semiring section ring variables [ring R] {p : polynomial R} theorem monic_X_sub_C (x : R) : monic (X - C x) := by simpa only [sub_eq_add_neg, C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := by simpa [sub_eq_add_neg] using monic_X_pow_add (show degree (-p) ≤ n, by rwa ←degree_neg p at H) /-- `X ^ n - a` is monic. -/ lemma monic_X_pow_sub_C {R : Type u} [ring R] (a : R) {n : ℕ} (h : n ≠ 0) : (X ^ n - C a).monic := begin obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero h, convert monic_X_pow_sub _, exact le_trans degree_C_le nat.with_bot.coe_nonneg, end lemma monic_sub_of_left {p q : polynomial R} (hp : monic p) (hpq : degree q < degree p) : monic (p - q) := by { rw sub_eq_add_neg, apply monic_add_of_left hp, rwa degree_neg } lemma monic_sub_of_right {p q : polynomial R} (hq : q.leading_coeff = -1) (hpq : degree p < degree q) : monic (p - q) := have (-q).coeff (-q).nat_degree = 1 := by rw [nat_degree_neg, coeff_neg, show q.coeff q.nat_degree = -1, from hq, neg_neg], by { rw sub_eq_add_neg, apply monic_add_of_right this, rwa degree_neg } section injective open function variables [semiring S] {f : R →+* S} (hf : injective f) include hf lemma leading_coeff_of_injective (p : polynomial R) : leading_coeff (p.map f) = f (leading_coeff p) := begin delta leading_coeff, rw [coeff_map f, nat_degree_map' hf p] end lemma monic_of_injective {p : polynomial R} (hp : (p.map f).monic) : p.monic := begin apply hf, rw [← leading_coeff_of_injective hf, hp.leading_coeff, is_semiring_hom.map_one f] end end injective end ring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma not_monic_zero : ¬monic (0 : polynomial R) := by simpa only [monic, leading_coeff_zero] using (zero_ne_one : (0 : R) ≠ 1) lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero R _ _ (h₁ ▸ h) end nonzero_semiring end polynomial
50d1adc31f1d53c8ffb51700b8182e9711554565
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/star/pi.lean
b7d59f4906bfee9ef3a8c3761adfae3376281115
[ "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,268
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.star.basic import algebra.ring.pi /-! # `star` on pi types We put a `has_star` structure on pi types that operates elementwise, such that it describes the complex conjugation of vectors. -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances namespace pi instance [Π i, has_star (f i)] : has_star (Π i, f i) := { star := λ x i, star (x i) } @[simp] lemma star_apply [Π i, has_star (f i)] (x : Π i, f i) (i : I) : star x i = star (x i) := rfl lemma star_def [Π i, has_star (f i)] (x : Π i, f i) : star x = λ i, star (x i) := rfl instance [Π i, has_involutive_star (f i)] : has_involutive_star (Π i, f i) := { star_involutive := λ _, funext $ λ _, star_star _ } instance [Π i, semigroup (f i)] [Π i, star_semigroup (f i)] : star_semigroup (Π i, f i) := { star_mul := λ _ _, funext $ λ _, star_mul _ _ } instance [Π i, add_monoid (f i)] [Π i, star_add_monoid (f i)] : star_add_monoid (Π i, f i) := { star_add := λ _ _, funext $ λ _, star_add _ _ } instance [Π i, non_unital_semiring (f i)] [Π i, star_ring (f i)] : star_ring (Π i, f i) := { ..pi.star_add_monoid, ..(pi.star_semigroup : star_semigroup (Π i, f i)) } instance {R : Type w} [Π i, has_smul R (f i)] [has_star R] [Π i, has_star (f i)] [Π i, star_module R (f i)] : star_module R (Π i, f i) := { star_smul := λ r x, funext $ λ i, star_smul r (x i) } lemma single_star [Π i, add_monoid (f i)] [Π i, star_add_monoid (f i)] [decidable_eq I] (i : I) (a : f i) : pi.single i (star a) = star (pi.single i a) := single_op (λ i, @star (f i) _) (λ i, star_zero _) i a end pi namespace function lemma update_star [Π i, has_star (f i)] [decidable_eq I] (h : Π (i : I), f i) (i : I) (a : f i) : function.update (star h) i (star a) = star (function.update h i a) := funext $ λ j, (apply_update (λ i, star) h i a j).symm lemma star_sum_elim {I J α : Type*} (x : I → α) (y : J → α) [has_star α] : star (sum.elim x y) = sum.elim (star x) (star y) := by { ext x, cases x; simp } end function
97b7377e780f03ea13913433a070be4899875a93
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/field_theory/finite.lean
f99762ad363fae02dc1062988621f309f2014aa9
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
3,567
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.order_of_element data.polynomial data.equiv.algebra universes u v variables {α : Type u} {β : Type v} open function finset polynomial nat section variables [integral_domain α] [decidable_eq α] (S : set (units α)) [is_subgroup S] [fintype S] lemma card_nth_roots_subgroup_units {n : ℕ} (hn : 0 < n) (a : S) : (univ.filter (λ b : S, b ^ n = a)).card ≤ (nth_roots n ((a : units α) : α)).card := card_le_card_of_inj_on (λ a, ((a : units α) : α)) (by simp [mem_nth_roots hn, (units.coe_pow _ _).symm, -units.coe_pow, units.ext_iff.symm, subtype.coe_ext]) (by simp [units.ext_iff.symm, subtype.coe_ext.symm]) instance subgroup_units_cyclic : is_cyclic S := by haveI := classical.dec_eq α; exact is_cyclic_of_card_pow_eq_one_le (λ n hn, le_trans (card_nth_roots_subgroup_units S hn 1) (card_nth_roots _ _)) end namespace finite_field def field_of_integral_domain [fintype α] [decidable_eq α] [integral_domain α] : discrete_field α := { has_decidable_eq := by apply_instance, inv := λ a, if h : a = 0 then 0 else fintype.bij_inv (show function.bijective (* a), from fintype.injective_iff_bijective.1 $ λ _ _, (domain.mul_right_inj h).1) 1, inv_mul_cancel := λ a ha, show dite _ _ _ * a = _, by rw dif_neg ha; exact fintype.right_inverse_bij_inv (show function.bijective (* a), from _) 1, mul_inv_cancel := λ a ha, show a * dite _ _ _ = _, by rw [dif_neg ha, mul_comm]; exact fintype.right_inverse_bij_inv (show function.bijective (* a), from _) 1, inv_zero := dif_pos rfl, ..show integral_domain α, by apply_instance } section variables [field α] [fintype α] instance [decidable_eq α] : fintype (units α) := by haveI := set_fintype {a : α | a ≠ 0}; exact fintype.of_equiv _ (equiv.units_equiv_ne_zero α).symm lemma card_units [decidable_eq α] : fintype.card (units α) = fintype.card α - 1 := begin rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : α)⟩)], haveI := set_fintype {a : α | a ≠ 0}, haveI := set_fintype (@set.univ α), rw [fintype.card_congr (equiv.units_equiv_ne_zero _), ← @set.card_insert _ _ {a : α | a ≠ 0} _ (not_not.2 (eq.refl (0 : α))) (set.fintype_insert _ _), fintype.card_congr (equiv.set.univ α).symm], congr; simp [set.ext_iff, classical.em] end instance : is_cyclic (units α) := by haveI := classical.dec_eq α; haveI := set_fintype (@set.univ (units α)); exact let ⟨g, hg⟩ := is_cyclic.exists_generator (@set.univ (units α)) in ⟨⟨g, λ x, let ⟨n, hn⟩ := hg ⟨x, trivial⟩ in ⟨n, by rw [← is_subgroup.coe_gpow, hn]; refl⟩⟩⟩ lemma prod_univ_units_id_eq_neg_one [decidable_eq α] : univ.prod (λ x, x) = (-1 : units α) := have ((@univ (units α) _).erase (-1)).prod (λ x, x) = 1, from prod_involution (λ x _, x⁻¹) (by simp) (λ a, by simp [units.inv_eq_self_iff] {contextual := tt}) (λ a, by simp [@inv_eq_iff_inv_eq _ _ a, eq_comm] {contextual := tt}) (by simp), by rw [← insert_erase (mem_univ (-1 : units α)), prod_insert (not_mem_erase _ _), this, mul_one] end lemma pow_card_sub_one_eq_one [discrete_field α] [fintype α] (a : α) (ha : a ≠ 0) : a ^ (fintype.card α - 1) = 1 := calc a ^ (fintype.card α - 1) = (units.mk0 a ha ^ (fintype.card α - 1) : units α) : by rw [units.coe_pow, units.mk0_val] ... = 1 : by rw [← card_units, pow_card_eq_one]; refl end finite_field
11746d2dbc331c60bf4ac0abcedde3aabd7b49dc
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/buffer/parser/basic.lean
69ad6675304a84f13e9a5df0b3d463d0f6cd4a4c
[ "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
110,078
lean
/- Copyright (c) 2020 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.string.basic import data.buffer.basic import data.nat.digits /-! # Parsers `parser α` is the type that describes a computation that can ingest a `char_buffer` and output, if successful, a term of type `α`. This file expands on the definitions in the core library, proving that all the core library parsers are `mono`. There are also lemmas on the composability of parsers. ## Main definitions * `parse_result.pos` : The position of a `char_buffer` at which a `parser α` has finished. * `parser.mono` : The property that a parser only moves forward within a buffer, in both cases of success or failure. ## Implementation details Lemmas about how parsers are mono are in the `mono` namespace. That allows using projection notation for shorter term proofs that are parallel to the definitions of the parsers in structure. -/ open parser parse_result /-- For some `parse_result α`, give the position at which the result was provided, in either the `done` or the `fail` case. -/ @[simp] def parse_result.pos {α} : parse_result α → ℕ | (done n _) := n | (fail n _) := n namespace parser section defn_lemmas variables {α β : Type} (msgs : thunk (list string)) (msg : thunk string) variables (p q : parser α) (cb : char_buffer) (n n' : ℕ) {err : dlist string} variables {a : α} {b : β} /-- A `p : parser α` is defined to be `mono` if the result `p cb n` it gives, for some `cb : char_buffer` and `n : ℕ`, (whether `done` or `fail`), is always at a `parse_result.pos` that is at least `n`. The `mono` property is used mainly for proper `orelse` behavior. -/ class mono : Prop := (le' : ∀ (cb : char_buffer) (n : ℕ), n ≤ (p cb n).pos) lemma mono.le [p.mono] : n ≤ (p cb n).pos := mono.le' cb n /-- A `parser α` is defined to be `static` if it does not move on success. -/ class static : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n = n') /-- A `parser α` is defined to be `err_static` if it does not move on error. -/ class err_static : Prop := (of_fail : ∀ {cb : char_buffer} {n n' : ℕ} {err : dlist string}, p cb n = fail n' err → n = n') /-- A `parser α` is defined to be `step` if it always moves exactly one char forward on success. -/ class step : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n' = n + 1) /-- A `parser α` is defined to be `prog` if it always moves forward on success. -/ class prog : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n < n') /-- A `parser a` is defined to be `bounded` if it produces a `fail` `parse_result` when it is parsing outside the provided `char_buffer`. -/ class bounded : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, cb.size ≤ n → ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err) lemma bounded.exists (p : parser α) [p.bounded] {cb : char_buffer} {n : ℕ} (h : cb.size ≤ n) : ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err := bounded.ex' h /-- A `parser a` is defined to be `unfailing` if it always produces a `done` `parse_result`. -/ class unfailing : Prop := (ex' : ∀ (cb : char_buffer) (n : ℕ), ∃ (n' : ℕ) (a : α), p cb n = done n' a) /-- A `parser a` is defined to be `conditionally_unfailing` if it produces a `done` `parse_result` as long as it is parsing within the provided `char_buffer`. -/ class conditionally_unfailing : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, n < cb.size → ∃ (n' : ℕ) (a : α), p cb n = done n' a) lemma fail_iff : (∀ pos' result, p cb n ≠ done pos' result) ↔ ∃ (pos' : ℕ) (err : dlist string), p cb n = fail pos' err := by cases p cb n; simp lemma success_iff : (∀ pos' err, p cb n ≠ fail pos' err) ↔ ∃ (pos' : ℕ) (result : α), p cb n = done pos' result := by cases p cb n; simp variables {p q cb n n' msgs msg} lemma mono.of_done [p.mono] (h : p cb n = done n' a) : n ≤ n' := by simpa [h] using mono.le p cb n lemma mono.of_fail [p.mono] (h : p cb n = fail n' err) : n ≤ n' := by simpa [h] using mono.le p cb n lemma bounded.of_done [p.bounded] (h : p cb n = done n' a) : n < cb.size := begin contrapose! h, obtain ⟨np, err, hp⟩ := bounded.exists p h, simp [hp] end lemma static.iff : static p ↔ (∀ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a → n = n') := ⟨λ h _ _ _ _ hp, by { haveI := h, exact static.of_done hp}, λ h, ⟨h⟩⟩ lemma exists_done (p : parser α) [p.unfailing] (cb : char_buffer) (n : ℕ) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := unfailing.ex' cb n lemma unfailing.of_fail [p.unfailing] (h : p cb n = fail n' err) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done cb n, simpa [hp] using h end @[priority 100] -- see Note [lower instance priority] instance conditionally_unfailing_of_unfailing [p.unfailing] : conditionally_unfailing p := ⟨λ _ _ _, p.exists_done _ _⟩ lemma exists_done_in_bounds (p : parser α) [p.conditionally_unfailing] {cb : char_buffer} {n : ℕ} (h : n < cb.size) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := conditionally_unfailing.ex' h lemma conditionally_unfailing.of_fail [p.conditionally_unfailing] (h : p cb n = fail n' err) (hn : n < cb.size) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done_in_bounds hn, simpa [hp] using h end lemma decorate_errors_fail (h : p cb n = fail n' err) : @decorate_errors α msgs p cb n = fail n ((dlist.lazy_of_list (msgs ()))) := by simp [decorate_errors, h] lemma decorate_errors_success (h : p cb n = done n' a) : @decorate_errors α msgs p cb n = done n' a := by simp [decorate_errors, h] lemma decorate_error_fail (h : p cb n = fail n' err) : @decorate_error α msg p cb n = fail n ((dlist.lazy_of_list ([msg ()]))) := decorate_errors_fail h lemma decorate_error_success (h : p cb n = done n' a) : @decorate_error α msg p cb n = done n' a := decorate_errors_success h @[simp] lemma decorate_errors_eq_done : @decorate_errors α msgs p cb n = done n' a ↔ p cb n = done n' a := by cases h : p cb n; simp [decorate_errors, h] @[simp] lemma decorate_error_eq_done : @decorate_error α msg p cb n = done n' a ↔ p cb n = done n' a := decorate_errors_eq_done @[simp] lemma decorate_errors_eq_fail : @decorate_errors α msgs p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list (msgs ()) ∧ ∃ np err', p cb n = fail np err' := by cases h : p cb n; simp [decorate_errors, h, eq_comm] @[simp] lemma decorate_error_eq_fail : @decorate_error α msg p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list ([msg ()]) ∧ ∃ np err', p cb n = fail np err' := decorate_errors_eq_fail @[simp] lemma return_eq_pure : (@return parser _ _ a) = pure a := rfl lemma pure_eq_done : (@pure parser _ _ a) = λ _ n, done n a := rfl @[simp] lemma pure_ne_fail : (pure a : parser α) cb n ≠ fail n' err := by simp [pure_eq_done] section bind variable (f : α → parser β) @[simp] lemma bind_eq_bind : p.bind f = p >>= f := rfl variable {f} @[simp] lemma bind_eq_done : (p >>= f) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = done n' b := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma bind_eq_fail : (p >>= f) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = fail n' err) := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma and_then_eq_bind {α β : Type} {m : Type → Type} [monad m] (a : m α) (b : m β) : a >> b = a >>= (λ _, b) := rfl lemma and_then_fail : (p >> return ()) cb n = parse_result.fail n' err ↔ p cb n = fail n' err := by simp [pure_eq_done] lemma and_then_success : (p >> return ()) cb n = parse_result.done n' () ↔ ∃ a, p cb n = done n' a:= by simp [pure_eq_done] end bind section map variable {f : α → β} @[simp] lemma map_eq_done : (f <$> p) cb n = done n' b ↔ ∃ (a : α), p cb n = done n' a ∧ f a = b := by cases hp : p cb n; simp [←is_lawful_monad.bind_pure_comp_eq_map, hp, and_assoc, pure_eq_done] @[simp] lemma map_eq_fail : (f <$> p) cb n = fail n' err ↔ p cb n = fail n' err := by simp [←bind_pure_comp_eq_map, pure_eq_done] @[simp] lemma map_const_eq_done {b'} : (b <$ p) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := by simp [map_const_eq] @[simp] lemma map_const_eq_fail : (b <$ p) cb n = fail n' err ↔ p cb n = fail n' err := by simp only [map_const_eq, map_eq_fail] lemma map_const_rev_eq_done {b'} : (p $> b) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := map_const_eq_done lemma map_rev_const_eq_fail : (p $> b) cb n = fail n' err ↔ p cb n = fail n' err := map_const_eq_fail end map @[simp] lemma orelse_eq_orelse : p.orelse q = (p <|> q) := rfl @[simp] lemma orelse_eq_done : (p <|> q) cb n = done n' a ↔ (p cb n = done n' a ∨ (q cb n = done n' a ∧ ∃ err, p cb n = fail n err)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hn, hq, H, not_lt_of_lt H, lt_irrefl, ←orelse_eq_orelse, parser.orelse] <|> simp [hp, hn, hq, lt_irrefl, ←orelse_eq_orelse, parser.orelse] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end @[simp] lemma orelse_eq_fail_eq : (p <|> q) cb n = fail n err ↔ (p cb n = fail n err ∧ ∃ (nq errq), n < nq ∧ q cb n = fail nq errq) ∨ (∃ (errp errq), p cb n = fail n errp ∧ q cb n = fail n errq ∧ errp ++ errq = err) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, H, ne_of_gt H, ne_of_lt H, not_lt_of_lt H] <|> simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, lt_irrefl] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_not_mono_lt (hn : n' < n) : (p <|> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (q cb n = fail n' err ∧ (∃ (errp), p cb n = fail n errp)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, ne_of_gt hn, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|H|H, { simp [hp, hq, h, H, ne_of_gt hn, not_lt_of_lt H, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt (hn.trans H), ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_of_mono_ne [q.mono] (hn : n ≠ n') : (p <|> q) cb n = fail n' err ↔ p cb n = fail n' err := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, hn, ←orelse_eq_orelse, parser.orelse] }, { have : n ≤ nq := mono.of_fail hq, rcases eq_or_lt_of_le this with rfl|H, { simp [hp, hq, h, hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, hn, H, ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } }, end @[simp] lemma failure_eq_failure : @parser.failure α = failure := rfl @[simp] lemma failure_def : (failure : parser α) cb n = fail n dlist.empty := rfl lemma not_failure_eq_done : ¬ (failure : parser α) cb n = done n' a := by simp lemma failure_eq_fail : (failure : parser α) cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [eq_comm] lemma seq_eq_done {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = done n' b ↔ ∃ (nf : ℕ) (f' : α → β) (a : α), f cb n = done nf f' ∧ p cb nf = done n' a ∧ f' a = b := by simp [seq_eq_bind_map] lemma seq_eq_fail {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = fail n' err ↔ (f cb n = fail n' err) ∨ (∃ (nf : ℕ) (f' : α → β), f cb n = done nf f' ∧ p cb nf = fail n' err) := by simp [seq_eq_bind_map] lemma seq_left_eq_done {p : parser α} {q : parser β} : (p <* q) cb n = done n' a ↔ ∃ (np : ℕ) (b : β), p cb n = done np a ∧ q cb np = done n' b := begin have : ∀ (p q : ℕ → α → Prop), (∃ (np : ℕ) (x : α), p np x ∧ q np x ∧ x = a) ↔ ∃ (np : ℕ), p np a ∧ q np a := λ _ _, ⟨λ ⟨np, x, hp, hq, rfl⟩, ⟨np, hp, hq⟩, λ ⟨np, hp, hq⟩, ⟨np, a, hp, hq, rfl⟩⟩, simp [seq_left_eq, seq_eq_done, map_eq_done, this] end lemma seq_left_eq_fail {p : parser α} {q : parser β} : (p <* q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_left_eq, seq_eq_fail] lemma seq_right_eq_done {p : parser α} {q : parser β} : (p *> q) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = done n' b := by simp [seq_right_eq, seq_eq_done, map_eq_done, and.comm, and.assoc] lemma seq_right_eq_fail {p : parser α} {q : parser β} : (p *> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_right_eq, seq_eq_fail] lemma mmap_eq_done {f : α → parser β} {a : α} {l : list α} {b : β} {l' : list β} : (a :: l).mmap f cb n = done n' (b :: l') ↔ ∃ (np : ℕ), f a cb n = done np b ∧ l.mmap f cb np = done n' l' := by simp [mmap, and.comm, and.assoc, and.left_comm, pure_eq_done] lemma mmap'_eq_done {f : α → parser β} {a : α} {l : list α} : (a :: l).mmap' f cb n = done n' () ↔ ∃ (np : ℕ) (b : β), f a cb n = done np b ∧ l.mmap' f cb np = done n' () := by simp [mmap'] lemma guard_eq_done {p : Prop} [decidable p] {u : unit} : @guard parser _ p _ cb n = done n' u ↔ p ∧ n = n' := by { by_cases hp : p; simp [guard, hp, pure_eq_done] } lemma guard_eq_fail {p : Prop} [decidable p] : @guard parser _ p _ cb n = fail n' err ↔ (¬ p) ∧ n = n' ∧ err = dlist.empty := by { by_cases hp : p; simp [guard, hp, eq_comm, pure_eq_done] } namespace mono variables {sep : parser unit} instance pure : mono (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.mono] [∀ a, (f a).mono] : (p >>= f).mono := begin constructor, intros cb n, cases hx : (p >>= f) cb n, { obtain ⟨n', a, h, h'⟩ := bind_eq_done.mp hx, refine le_trans (of_done h) _, simpa [h'] using of_done h' }, { obtain h | ⟨n', a, h, h'⟩ := bind_eq_fail.mp hx, { simpa [h] using of_fail h }, { refine le_trans (of_done h) _, simpa [h'] using of_fail h' } } end instance and_then {q : parser β} [p.mono] [q.mono] : (p >> q).mono := mono.bind instance map [p.mono] {f : α → β} : (f <$> p).mono := mono.bind instance seq {f : parser (α → β)} [f.mono] [p.mono] : (f <*> p).mono := mono.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.bind, { exact h _ (list.mem_cons_self _ _) }, { intro, convert mono.map, convert mmap, exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap' f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.and_then, { exact h _ (list.mem_cons_self _ _) }, { convert mmap', exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance failure : (failure : parser α).mono := ⟨by simp [le_refl]⟩ instance guard {p : Prop} [decidable p] : mono (guard p) := ⟨by { by_cases h : p; simp [h, pure_eq_done, le_refl] }⟩ instance orelse [p.mono] [q.mono] : (p <|> q).mono := begin constructor, intros cb n, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; simpa [h] using of_done h }, { by_cases h : n = posx, { simp [hx, h] }, { simp only [orelse_eq_fail_of_mono_ne h] at hx, exact of_fail hx } } end instance decorate_errors [p.mono] : (@decorate_errors α msgs p).mono := begin constructor, intros cb n, cases h : p cb n, { simpa [decorate_errors, h] using of_done h }, { simp [decorate_errors, h] } end instance decorate_error [p.mono] : (@decorate_error α msg p).mono := mono.decorate_errors instance any_char : mono any_char := begin constructor, intros cb n, by_cases h : n < cb.size; simp [any_char, h], end instance sat {p : char → Prop} [decidable_pred p] : mono (sat p) := begin constructor, intros cb n, simp only [sat], split_ifs; simp end instance eps : mono eps := mono.pure instance ch {c : char} : mono (ch c) := mono.decorate_error instance char_buf {s : char_buffer} : mono (char_buf s) := mono.decorate_error instance one_of {cs : list char} : (one_of cs).mono := mono.decorate_errors instance one_of' {cs : list char} : (one_of' cs).mono := mono.and_then instance str {s : string} : (str s).mono := mono.decorate_error instance remaining : remaining.mono := ⟨λ _ _, le_rfl⟩ instance eof : eof.mono := mono.decorate_error instance foldr_core {f : α → β → β} {b : β} [p.mono] : ∀ {reps : ℕ}, (foldr_core f p b reps).mono | 0 := mono.failure | (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, @mono.bind _ _ _ _ foldr_core _ } }, { exact mono.pure } end instance foldr {f : α → β → β} [p.mono] : mono (foldr f p b) := ⟨λ _ _, by { convert mono.le (foldr_core f p b _) _ _, exact mono.foldr_core }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.mono] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).mono | _ 0 := mono.failure | _ (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact mono.pure } end instance foldl {f : α → β → α} {p : parser β} [p.mono] : mono (foldl f a p) := ⟨λ _ _, by { convert mono.le (foldl_core f a p _) _ _, exact mono.foldl_core }⟩ instance many [p.mono] : p.many.mono := mono.foldr instance many_char {p : parser char} [p.mono] : p.many_char.mono := mono.map instance many' [p.mono] : p.many'.mono := mono.and_then instance many1 [p.mono] : p.many1.mono := mono.seq instance many_char1 {p : parser char} [p.mono] : p.many_char1.mono := mono.map instance sep_by1 [p.mono] [sep.mono] : mono (sep_by1 sep p) := mono.seq instance sep_by [p.mono] [hs : sep.mono] : mono (sep_by sep p) := mono.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : ∀ (max_depth : ℕ), mono (fix_core F max_depth) | 0 := mono.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.mono := mono.decorate_error instance nat : nat.mono := mono.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : mono (fix F) := ⟨λ _ _, by { convert mono.le (parser.fix_core F _) _ _, exact fix_core hF _ }⟩ end mono @[simp] lemma orelse_pure_eq_fail : (p <|> pure a) cb n = fail n' err ↔ p cb n = fail n' err ∧ n ≠ n' := begin by_cases hn : n = n', { simp [hn, pure_eq_done] }, { simp [orelse_eq_fail_of_mono_ne, hn] } end end defn_lemmas section done variables {α β : Type} {cb : char_buffer} {n n' : ℕ} {a a' : α} {b : β} {c : char} {u : unit} {err : dlist string} lemma any_char_eq_done : any_char cb n = done n' c ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin simp_rw [any_char], split_ifs with h; simp [h, eq_comm] end lemma any_char_eq_fail : any_char cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ cb.size ≤ n := begin simp_rw [any_char], split_ifs with h; simp [←not_lt, h, eq_comm] end lemma sat_eq_done {p : char → Prop} [decidable_pred p] : sat p cb n = done n' c ↔ ∃ (hn : n < cb.size), p c ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin by_cases hn : n < cb.size, { by_cases hp : p (cb.read ⟨n, hn⟩), { simp only [sat, hn, hp, dif_pos, if_true, exists_prop_of_true], split, { rintro ⟨rfl, rfl⟩, simp [hp] }, { rintro ⟨-, rfl, rfl⟩, simp } }, { simp only [sat, hn, hp, dif_pos, false_iff, not_and, exists_prop_of_true, if_false], rintro H - rfl, exact hp H } }, { simp [sat, hn] } end lemma sat_eq_fail {p : char → Prop} [decidable_pred p] : sat p cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ ∀ (h : n < cb.size), ¬ p (cb.read ⟨n, h⟩) := begin dsimp only [sat], split_ifs; simp [*, eq_comm] end lemma eps_eq_done : eps cb n = done n' u ↔ n = n' := by simp [eps, pure_eq_done] lemma ch_eq_done : ch c cb n = done n' u ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [ch, eps_eq_done, sat_eq_done, and.comm, @eq_comm _ n'] lemma char_buf_eq_done {cb' : char_buffer} : char_buf cb' cb n = done n' u ↔ n + cb'.size = n' ∧ cb'.to_list <+: (cb.to_list.drop n) := begin simp only [char_buf, decorate_error_eq_done, ne.def, ←buffer.length_to_list], induction cb'.to_list with hd tl hl generalizing cb n n', { simp [pure_eq_done, mmap'_eq_done, -buffer.length_to_list, list.nil_prefix] }, { simp only [ch_eq_done, and.comm, and.assoc, and.left_comm, hl, mmap', and_then_eq_bind, bind_eq_done, list.length, exists_and_distrib_left, exists_const], split, { rintro ⟨np, h, rfl, rfl, hn, rfl⟩, simp only [add_comm, add_left_comm, h, true_and, eq_self_iff_true, and_true], have : n < cb.to_list.length := by simpa using hn, rwa [←buffer.nth_le_to_list _ this, ←list.cons_nth_le_drop_succ this, list.prefix_cons_inj] }, { rintro ⟨h, rfl⟩, by_cases hn : n < cb.size, { have : n < cb.to_list.length := by simpa using hn, rw [←list.cons_nth_le_drop_succ this, list.cons_prefix_iff] at h, use [n + 1, h.right], simpa [buffer.nth_le_to_list, add_comm, add_left_comm, add_assoc, hn] using h.left.symm }, { have : cb.to_list.length ≤ n := by simpa using hn, rw list.drop_eq_nil_of_le this at h, simpa using h } } } end lemma one_of_eq_done {cs : list char} : one_of cs cb n = done n' c ↔ ∃ (hn : n < cb.size), c ∈ cs ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [one_of, sat_eq_done] lemma one_of'_eq_done {cs : list char} : one_of' cs cb n = done n' u ↔ ∃ (hn : n < cb.size), cb.read ⟨n, hn⟩ ∈ cs ∧ n' = n + 1 := begin simp only [one_of', one_of_eq_done, eps_eq_done, and.comm, and_then_eq_bind, bind_eq_done, exists_eq_left, exists_and_distrib_left], split, { rintro ⟨c, hc, rfl, hn, rfl⟩, exact ⟨rfl, hn, hc⟩ }, { rintro ⟨rfl, hn, hc⟩, exact ⟨cb.read ⟨n, hn⟩, hc, rfl, hn, rfl⟩ } end lemma str_eq_char_buf (s : string) : str s = char_buf s.to_list.to_buffer := begin ext cb n, rw [str, char_buf], congr, { simp [buffer.to_string, string.as_string_inv_to_list] }, { simp } end lemma str_eq_done {s : string} : str s cb n = done n' u ↔ n + s.length = n' ∧ s.to_list <+: (cb.to_list.drop n) := by simp [str_eq_char_buf, char_buf_eq_done] lemma remaining_eq_done {r : ℕ} : remaining cb n = done n' r ↔ n = n' ∧ cb.size - n = r := by simp [remaining] lemma remaining_ne_fail : remaining cb n ≠ fail n' err := by simp [remaining] lemma eof_eq_done {u : unit} : eof cb n = done n' u ↔ n = n' ∧ cb.size ≤ n := by simp [eof, guard_eq_done, remaining_eq_done, tsub_eq_zero_iff_le, and_comm, and_assoc] @[simp] lemma foldr_core_zero_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr_core f p b 0 cb n ≠ done n' b' := by simp [foldr_core] lemma foldr_core_eq_done {f : α → β → β} {p : parser α} {reps : ℕ} {b' : β} : foldr_core f p b (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α) (xs : β), p cb n = done np a ∧ foldr_core f p b reps cb np = done n' xs ∧ f a xs = b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n err)) := by simp [foldr_core, and.comm, and.assoc, pure_eq_done] @[simp] lemma foldr_core_zero_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr_core f p b 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldr_core, eq_comm] lemma foldr_core_succ_eq_fail {f : α → β → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldr_core f p b (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n' err) := by simp [foldr_core, and_comm] lemma foldr_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr f p b cb n = done n' b' ↔ ((∃ (np : ℕ) (a : α) (x : β), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = done n' x ∧ f a x = b') ∨ (n = n' ∧ b = b' ∧ (∃ (err), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ) (x : α), p cb n = done np x ∧ foldr_core f p b (cb.size - n) cb np = fail n err))) := by simp [foldr, foldr_core_eq_done] lemma foldr_eq_fail_iff_mono_at_end {f : α → β → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldr f p b cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := tsub_eq_zero_iff_le.mpr hc, simp only [foldr, foldr_core_succ_eq_fail, this, and.left_comm, foldr_core_zero_eq_fail, ne_iff_lt_iff_le, exists_and_distrib_right, exists_eq_left, and.congr_left_iff, exists_and_distrib_left], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma foldr_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr f p b cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = fail n' err) := by simp [foldr, foldr_core_succ_eq_fail] @[simp] lemma foldl_core_zero_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl_core f b p 0 cb n = done n' b' ↔ false := by simp [foldl_core] lemma foldl_core_eq_done {f : β → α → β} {p : parser α} {reps : ℕ} {b' : β} : foldl_core f b p (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n err)) := by simp [foldl_core, and.assoc, pure_eq_done] @[simp] lemma foldl_core_zero_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl_core f b p 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldl_core, eq_comm] lemma foldl_core_succ_eq_fail {f : β → α → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldl_core f b p (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n' err) := by simp [foldl_core, and_comm] lemma foldl_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl f b p cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n err)) := by simp [foldl, foldl_core_eq_done] lemma foldl_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl f b p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n' err) := by simp [foldl, foldl_core_succ_eq_fail] lemma foldl_eq_fail_iff_mono_at_end {f : β → α → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldl f b p cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := tsub_eq_zero_iff_le.mpr hc, simp only [foldl, foldl_core_succ_eq_fail, this, and.left_comm, ne_iff_lt_iff_le, exists_eq_left, exists_and_distrib_right, and.congr_left_iff, exists_and_distrib_left, foldl_core_zero_eq_fail], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma many_eq_done_nil {p : parser α} : many p cb n = done n' (@list.nil α) ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many, foldr_eq_done] lemma many_eq_done {p : parser α} {x : α} {xs : list α} : many p cb n = done n' (x :: xs) ↔ ∃ (np : ℕ), p cb n = done np x ∧ foldr_core list.cons p [] (cb.size - n) cb np = done n' xs := by simp [many, foldr_eq_done, and.comm, and.assoc, and.left_comm] lemma many_eq_fail {p : parser α} {err : dlist string} : many p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n' err) := by simp [many, foldr_eq_fail] lemma many_char_eq_done_empty {p : parser char} : many_char p cb n = done n' string.empty ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (c : char), p cb n = done np c ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many_char, many_eq_done_nil, map_eq_done, list.as_string_eq] lemma many_char_eq_done_not_empty {p : parser char} {s : string} (h : s ≠ "") : many_char p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ foldr_core list.cons p list.nil (buffer.size cb - n) cb np = done n' (s.popn 1).to_list := by simp [many_char, list.as_string_eq, string.to_list_nonempty h, many_eq_done] lemma many_char_eq_many_of_to_list {p : parser char} {s : string} : many_char p cb n = done n' s ↔ many p cb n = done n' s.to_list := by simp [many_char, list.as_string_eq] lemma many'_eq_done {p : parser α} : many' p cb n = done n' u ↔ many p cb n = done n' [] ∨ ∃ (np : ℕ) (a : α) (l : list α), many p cb n = done n' (a :: l) ∧ p cb n = done np a ∧ foldr_core list.cons p [] (buffer.size cb - n) cb np = done n' l := begin simp only [many', eps_eq_done, many, foldr, and_then_eq_bind, exists_and_distrib_right, bind_eq_done, exists_eq_right], split, { rintro ⟨_ | ⟨hd, tl⟩, hl⟩, { exact or.inl hl }, { have hl2 := hl, simp only [foldr_core_eq_done, or_false, exists_and_distrib_left, and_false, false_and, exists_eq_right_right] at hl, obtain ⟨np, hp, h⟩ := hl, refine or.inr ⟨np, _, _, hl2, hp, h⟩ } }, { rintro (h | ⟨np, a, l, hp, h⟩), { exact ⟨[], h⟩ }, { refine ⟨a :: l, hp⟩ } } end @[simp] lemma many1_ne_done_nil {p : parser α} : many1 p cb n ≠ done n' [] := by simp [many1, seq_eq_done] lemma many1_eq_done {p : parser α} {l : list α} : many1 p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ many p cb np = done n' l := by simp [many1, seq_eq_done, map_eq_done] lemma many1_eq_fail {p : parser α} {err : dlist string} : many1 p cb n = fail n' err ↔ p cb n = fail n' err ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ many p cb np = fail n' err) := by simp [many1, seq_eq_fail] @[simp] lemma many_char1_ne_empty {p : parser char} : many_char1 p cb n ≠ done n' "" := by simp [many_char1, ←string.nil_as_string_eq_empty] lemma many_char1_eq_done {p : parser char} {s : string} (h : s ≠ "") : many_char1 p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ many_char p cb np = done n' (s.popn 1) := by simp [many_char1, list.as_string_eq, string.to_list_nonempty h, many1_eq_done, many_char_eq_many_of_to_list] @[simp] lemma sep_by1_ne_done_nil {sep : parser unit} {p : parser α} : sep_by1 sep p cb n ≠ done n' [] := by simp [sep_by1, seq_eq_done] lemma sep_by1_eq_done {sep : parser unit} {p : parser α} {l : list α} : sep_by1 sep p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ (sep >> p).many cb np = done n' l := by simp [sep_by1, seq_eq_done] lemma sep_by_eq_done_nil {sep : parser unit} {p : parser α} : sep_by sep p cb n = done n' [] ↔ n = n' ∧ ∃ (err), sep_by1 sep p cb n = fail n err := by simp [sep_by, pure_eq_done] @[simp] lemma fix_core_ne_done_zero {F : parser α → parser α} : fix_core F 0 cb n ≠ done n' a := by simp [fix_core] lemma fix_core_eq_done {F : parser α → parser α} {max_depth : ℕ} : fix_core F (max_depth + 1) cb n = done n' a ↔ F (fix_core F max_depth) cb n = done n' a := by simp [fix_core] lemma digit_eq_done {k : ℕ} : digit cb n = done n' k ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ k ≤ 9 ∧ (cb.read ⟨n, hn⟩).to_nat - '0'.to_nat = k ∧ '0' ≤ cb.read ⟨n, hn⟩ ∧ cb.read ⟨n, hn⟩ ≤ '9' := begin have c9 : '9'.to_nat - '0'.to_nat = 9 := rfl, have l09 : '0'.to_nat ≤ '9'.to_nat := dec_trivial, have le_iff_le : ∀ {c c' : char}, c ≤ c' ↔ c.to_nat ≤ c'.to_nat := λ _ _, iff.rfl, split, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9], rintro ⟨np, c, ⟨hn, ⟨ge0, le9⟩, rfl, rfl⟩, rfl, rfl⟩, simpa [hn, ge0, le9, true_and, and_true, eq_self_iff_true, exists_prop_of_true, tsub_le_tsub_iff_right, l09] using (le_iff_le.mp le9) }, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9, le_iff_le], rintro ⟨hn, rfl, -, rfl, ge0, le9⟩, use [n + 1, cb.read ⟨n, hn⟩], simp [hn, ge0, le9] } end lemma digit_eq_fail : digit cb n = fail n' err ↔ n = n' ∧ err = dlist.of_list ["<digit>"] ∧ ∀ (h : n < cb.size), ¬ ((λ c, '0' ≤ c ∧ c ≤ '9') (cb.read ⟨n, h⟩)) := by simp [digit, sat_eq_fail] end done namespace static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = done n' a) (hne : n ≠ n') : ¬ static p := by { introI, exact hne (of_done h) } instance pure : static (pure a) := ⟨λ _ _ _ _, by { simp_rw pure_eq_done, rw [and.comm], simp }⟩ instance bind {f : α → parser β} [p.static] [∀ a, (f a).static] : (p >>= f).static := ⟨λ _ _ _ _, by { rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact trans (of_done hp) (of_done hf) }⟩ instance and_then {q : parser β} [p.static] [q.static] : (p >> q).static := static.bind instance map [p.static] {f : α → β} : (f <$> p).static := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.static] [p.static] : (f <*> p).static := static.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.bind, { exact h _ }, { intro, convert static.bind, { convert mmap, exact h }, { exact λ _, static.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap' f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.and_then, { exact h _ }, { convert mmap', exact h } end instance failure : @parser.static α failure := ⟨λ _ _ _ _, by simp⟩ instance guard {p : Prop} [decidable p] : static (guard p) := ⟨λ _ _ _ _, by simp [guard_eq_done]⟩ instance orelse [p.static] [q.static] : (p <|> q).static := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ instance decorate_errors [p.static] : (@decorate_errors α msgs p).static := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ instance decorate_error [p.static] : (@decorate_error α msg p).static := static.decorate_errors lemma any_char : ¬ static any_char := begin have : any_char "s".to_char_buffer 0 = done 1 's', { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [any_char_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma sat_iff {p : char → Prop} [decidable_pred p] : static (sat p) ↔ ∀ c, ¬ p c := begin split, { introI, intros c hc, have : sat p [c].to_buffer 0 = done 1 c := by simp [sat_eq_done, hc], exact zero_ne_one (of_done this) }, { contrapose!, simp only [iff, sat_eq_done, and_imp, exists_prop, exists_and_distrib_right, exists_and_distrib_left, exists_imp_distrib, not_forall], rintros _ _ _ a h hne rfl hp -, exact ⟨a, hp⟩ } end instance sat : static (sat (λ _, false)) := by { apply sat_iff.mpr, simp } instance eps : static eps := static.pure lemma ch (c : char) : ¬ static (ch c) := begin have : ch c [c].to_buffer 0 = done 1 (), { have : 0 < [c].to_buffer.size := dec_trivial, simp [ch_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma char_buf_iff {cb' : char_buffer} : static (char_buf cb') ↔ cb' = buffer.nil := begin rw ←buffer.size_eq_zero_iff, have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], cases hc : cb'.size with n, { simp only [eq_self_iff_true, iff_true], exact ⟨λ _ _ _ _ h, by simpa [hc] using (char_buf_eq_done.mp h).left⟩ }, { rw hc at this, simpa [nat.succ_ne_zero] using not_of_ne this (nat.succ_ne_zero n).symm } end lemma one_of_iff {cs : list char} : static (one_of cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of, static.decorate_errors] }, { have : one_of (hd :: tl) (hd :: tl).to_buffer 0 = done 1 hd, { simp [one_of_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma one_of'_iff {cs : list char} : static (one_of' cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of', static.bind], }, { have : one_of' (hd :: tl) (hd :: tl).to_buffer 0 = done 1 (), { simp [one_of'_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of' : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma str_iff {s : string} : static (str s) ↔ s = "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] instance remaining : remaining.static := ⟨λ _ _ _ _ h, (remaining_eq_done.mp h).left⟩ instance eof : eof.static := static.decorate_error instance foldr_core {f : α → β → β} [p.static] : ∀ {b : β} {reps : ℕ}, (foldr_core f p b reps).static | _ 0 := static.failure | _ (reps + 1) := begin simp_rw parser.foldr_core, convert static.orelse, { convert static.bind, { apply_instance }, { intro, convert static.bind, { exact foldr_core }, { apply_instance } } }, { exact static.pure } end instance foldr {f : α → β → β} [p.static] : static (foldr f p b) := ⟨λ _ _ _ _, by { dsimp [foldr], exact of_done }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.static] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).static | _ 0 := static.failure | _ (reps + 1) := begin convert static.orelse, { convert static.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact static.pure } end instance foldl {f : α → β → α} {p : parser β} [p.static] : static (foldl f a p) := ⟨λ _ _ _ _, by { dsimp [foldl], exact of_done }⟩ instance many [p.static] : p.many.static := static.foldr instance many_char {p : parser char} [p.static] : p.many_char.static := static.map instance many' [p.static] : p.many'.static := static.and_then instance many1 [p.static] : p.many1.static := static.seq instance many_char1 {p : parser char} [p.static] : p.many_char1.static := static.map instance sep_by1 [p.static] [sep.static] : static (sep_by1 sep p) := static.seq instance sep_by [p.static] [sep.static] : static (sep_by sep p) := static.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : ∀ (max_depth : ℕ), static (fix_core F max_depth) | 0 := static.failure | (max_depth + 1) := hF _ (fix_core _) lemma digit : ¬ digit.static := begin have : digit "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma nat : ¬ nat.static := begin have : nat "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact static.of_done h }⟩ end static namespace bounded variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} lemma done_of_unbounded (h : ¬p.bounded) : ∃ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a ∧ cb.size ≤ n := begin contrapose! h, constructor, intros cb n hn, cases hp : p cb n, { exact absurd hn (h _ _ _ _ hp).not_le }, { simp [hp] } end lemma pure : ¬ bounded (pure a) := begin introI, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end instance bind {f : α → parser β} [p.bounded] : (p >>= f).bounded := begin constructor, intros cb n hn, obtain ⟨_, _, hp⟩ := bounded.exists p hn, simp [hp] end instance and_then {q : parser β} [p.bounded] : (p >> q).bounded := bounded.bind instance map [p.bounded] {f : α → β} : (f <$> p).bounded := bounded.bind instance seq {f : parser (α → β)} [f.bounded] : (f <*> p).bounded := bounded.bind instance mmap {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap f).bounded := bounded.bind instance mmap' {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap' f).bounded := bounded.and_then instance failure : @parser.bounded α failure := ⟨by simp⟩ lemma guard_iff {p : Prop} [decidable p] : bounded (guard p) ↔ ¬ p := by simpa [guard, apply_ite bounded, pure, failure] using λ _, bounded.failure instance orelse [p.bounded] [q.bounded] : (p <|> q).bounded := begin constructor, intros cb n hn, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; exact absurd hn (of_done h).not_le }, { simp } end instance decorate_errors [p.bounded] : (@decorate_errors α msgs p).bounded := begin constructor, intros _ _, simpa using bounded.exists p end lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).bounded ↔ p.bounded := begin split, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists (@parser.decorate_errors α msgs p) hn, simp [decorate_errors_eq_fail] at h, exact h.right.right }, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists p hn, simp [h] } end instance decorate_error [p.bounded] : (@decorate_error α msg p).bounded := bounded.decorate_errors lemma decorate_error_iff : (@parser.decorate_error α msg p).bounded ↔ p.bounded := decorate_errors_iff instance any_char : bounded any_char := ⟨λ cb n hn, by simp [any_char, hn]⟩ instance sat {p : char → Prop} [decidable_pred p] : bounded (sat p) := ⟨λ cb n hn, by simp [sat, hn]⟩ lemma eps : ¬ bounded eps := pure instance ch {c : char} : bounded (ch c) := bounded.decorate_error lemma char_buf_iff {cb' : char_buffer} : bounded (char_buf cb') ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, decorate_error_iff, this], cases cb'.to_list, { simp [pure, ch] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).bounded := bounded.decorate_errors instance one_of' {cs : list char} : (one_of' cs).bounded := bounded.and_then lemma str_iff {s : string} : (str s).bounded ↔ s ≠ "" := begin rw [str, decorate_error_iff], cases hs : s.to_list, { have : s = "", { cases s, rw [string.to_list] at hs, simpa [hs] }, simp [pure, this] }, { have : s ≠ "", { intro H, simpa [H] using hs }, simp only [this, iff_true, ne.def, not_false_iff], apply_instance } end lemma remaining : ¬ remaining.bounded := begin introI, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end lemma eof : ¬ eof.bounded := begin introI, have : eof buffer.nil 0 = done 0 () := by simp [eof_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end section fold instance foldr_core_zero {f : α → β → β} : (foldr_core f p b 0).bounded := bounded.failure instance foldl_core_zero {f : β → α → β} {b : β} : (foldl_core f b p 0).bounded := bounded.failure variables {reps : ℕ} [hpb : p.bounded] (he : ∀ cb n n' err, p cb n = fail n' err → n ≠ n') include hpb he lemma foldr_core {f : α → β → β} : (foldr_core f p b reps).bounded := begin cases reps, { exact bounded.foldr_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldr_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldr {f : α → β → β} : bounded (foldr f p b) := begin constructor, intros cb n hn, haveI : (parser.foldr_core f p b (cb.size - n + 1)).bounded := foldr_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldr_core f p b (cb.size - n + 1)) hn, simp [foldr, hp] end lemma foldl_core {f : β → α → β} : (foldl_core f b p reps).bounded := begin cases reps, { exact bounded.foldl_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldl_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldl {f : β → α → β} : bounded (foldl f b p) := begin constructor, intros cb n hn, haveI : (parser.foldl_core f b p (cb.size - n + 1)).bounded := foldl_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldl_core f b p (cb.size - n + 1)) hn, simp [foldl, hp] end lemma many : p.many.bounded := foldr he omit hpb lemma many_char {pc : parser char} [pc.bounded] (he : ∀ cb n n' err, pc cb n = fail n' err → n ≠ n'): pc.many_char.bounded := by { convert bounded.map, exact many he } include hpb lemma many' : p.many'.bounded := by { convert bounded.and_then, exact many he } end fold instance many1 [p.bounded] : p.many1.bounded := bounded.seq instance many_char1 {p : parser char} [p.bounded] : p.many_char1.bounded := bounded.map instance sep_by1 {sep : parser unit} [p.bounded] : bounded (sep_by1 sep p) := bounded.seq lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : ∀ (max_depth : ℕ), bounded (fix_core F max_depth) | 0 := bounded.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.bounded := bounded.decorate_error instance nat : nat.bounded := bounded.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : bounded (fix F) := begin constructor, intros cb n hn, haveI : (parser.fix_core F (cb.size - n + 1)).bounded := fix_core hF _, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.fix_core F (cb.size - n + 1)) hn, simp [fix, hp] end end bounded namespace unfailing variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma of_bounded [p.bounded] : ¬ unfailing p := begin introI, cases h : p buffer.nil 0, { simpa [lt_irrefl] using bounded.of_done h }, { exact of_fail h } end instance pure : unfailing (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.unfailing] [∀ a, (f a).unfailing] : (p >>= f).unfailing := ⟨λ cb n, begin obtain ⟨np, a, hp⟩ := exists_done p cb n, simpa [hp, and.comm, and.left_comm, and.assoc] using exists_done (f a) cb np end⟩ instance and_then {q : parser β} [p.unfailing] [q.unfailing] : (p >> q).unfailing := unfailing.bind instance map [p.unfailing] {f : α → β} : (f <$> p).unfailing := unfailing.bind instance seq {f : parser (α → β)} [f.unfailing] [p.unfailing] : (f <*> p).unfailing := unfailing.bind instance mmap {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end instance mmap' {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap' f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end lemma failure : ¬ @parser.unfailing α failure := begin introI h, have : (failure : parser α) buffer.nil 0 = fail 0 dlist.empty := by simp, exact of_fail this end instance guard_true : unfailing (guard true) := unfailing.pure lemma guard : ¬ unfailing (guard false) := unfailing.failure instance orelse [p.unfailing] : (p <|> q).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_errors [p.unfailing] : (@decorate_errors α msgs p).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_error [p.unfailing] : (@decorate_error α msg p).unfailing := unfailing.decorate_errors instance any_char : conditionally_unfailing any_char := ⟨λ _ _ hn, by simp [success_iff, any_char_eq_done, hn]⟩ lemma sat : conditionally_unfailing (sat (λ _, true)) := ⟨λ _ _ hn, by simp [success_iff, sat_eq_done, hn]⟩ instance eps : unfailing eps := unfailing.pure instance remaining : remaining.unfailing := ⟨λ _ _, by simp [success_iff, remaining_eq_done]⟩ lemma foldr_core_zero {f : α → β → β} {b : β} : ¬ (foldr_core f p b 0).unfailing := unfailing.failure instance foldr_core_of_static {f : α → β → β} {b : β} {reps : ℕ} [p.static] [p.unfailing] : (foldr_core f p b (reps + 1)).unfailing := begin induction reps with reps hr, { constructor, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { constructor, haveI := hr, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, have : n = np := static.of_done h, subst this, obtain ⟨np, b', hf⟩ := exists_done (foldr_core f p b (reps + 1)) cb n, have : n = np := static.of_done hf, subst this, refine ⟨n, f a b', _⟩, rw foldr_core_eq_done, simp [h, hf, and.comm, and.left_comm, and.assoc] } end instance foldr_core_one_of_err_static {f : α → β → β} {b : β} [p.static] [p.err_static] : (foldr_core f p b 1).unfailing := begin constructor, intros cb n, cases h : p cb n, { simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { simpa [foldr_core_eq_done, h] using (err_static.of_fail h).symm } end -- TODO: add foldr and foldl, many, etc, fix_core lemma digit : ¬ digit.unfailing := of_bounded lemma nat : ¬ nat.unfailing := of_bounded end unfailing namespace err_static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = fail n' err) (hne : n ≠ n') : ¬ err_static p := by { introI, exact hne (of_fail h) } instance pure : err_static (pure a) := ⟨λ _ _ _ _, by { simp [pure_eq_done] }⟩ instance bind {f : α → parser β} [p.static] [p.err_static] [∀ a, (f a).err_static] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact trans (static.of_done hp) (of_fail hf) } end⟩ instance bind_of_unfailing {f : α → parser β} [p.err_static] [∀ a, (f a).unfailing] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact false.elim (unfailing.of_fail hf) } end⟩ instance and_then {q : parser β} [p.static] [p.err_static] [q.err_static] : (p >> q).err_static := err_static.bind instance and_then_of_unfailing {q : parser β} [p.err_static] [q.unfailing] : (p >> q).err_static := err_static.bind_of_unfailing instance map [p.err_static] {f : α → β} : (f <$> p).err_static := ⟨λ _ _ _ _, by { rw map_eq_fail, exact of_fail }⟩ instance seq {f : parser (α → β)} [f.static] [f.err_static] [p.err_static] : (f <*> p).err_static := err_static.bind instance seq_of_unfailing {f : parser (α → β)} [f.err_static] [p.unfailing] : (f <*> p).err_static := err_static.bind_of_unfailing instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind, { exact h _ }, { exact h' _ }, { intro, convert err_static.bind, { convert static.mmap, exact h }, { apply mmap, { exact h }, { exact h' } }, { exact λ _, err_static.pure } } end instance mmap_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind_of_unfailing, { exact h' _ }, { intro, convert unfailing.bind, { convert unfailing.mmap, exact h }, { exact λ _, unfailing.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then, { exact h _ }, { exact h' _ }, { convert mmap', { exact h }, { exact h' } } end instance mmap'_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then_of_unfailing, { exact h' _ }, { convert unfailing.mmap', exact h } end instance failure : @parser.err_static α failure := ⟨λ _ _ _ _ h, (failure_eq_fail.mp h).left⟩ instance guard {p : Prop} [decidable p] : err_static (guard p) := ⟨λ _ _ _ _ h, (guard_eq_fail.mp h).right.left⟩ instance orelse [p.err_static] [q.mono] : (p <|> q).err_static := ⟨λ _ n n' _, begin by_cases hn : n = n', { exact λ _, hn }, { rw orelse_eq_fail_of_mono_ne hn, { exact of_fail }, { apply_instance } } end⟩ instance decorate_errors : (@decorate_errors α msgs p).err_static := ⟨λ _ _ _ _ h, (decorate_errors_eq_fail.mp h).left⟩ instance decorate_error : (@decorate_error α msg p).err_static := err_static.decorate_errors instance any_char : err_static any_char := ⟨λ _ _ _ _, by { rw [any_char_eq_fail, and.comm], simp }⟩ instance sat_iff {p : char → Prop} [decidable_pred p] : err_static (sat p) := ⟨λ _ _ _ _ h, (sat_eq_fail.mp h).left⟩ instance eps : err_static eps := err_static.pure instance ch (c : char) : err_static (ch c) := err_static.decorate_error instance char_buf {cb' : char_buffer} : err_static (char_buf cb') := err_static.decorate_error instance one_of {cs : list char} : err_static (one_of cs) := err_static.decorate_errors instance one_of' {cs : list char} : err_static (one_of' cs) := err_static.and_then_of_unfailing instance str {s : string} : err_static (str s) := err_static.decorate_error instance remaining : remaining.err_static := ⟨λ _ _ _ _, by simp [remaining_ne_fail]⟩ instance eof : eof.err_static := err_static.decorate_error -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : ∀ (max_depth : ℕ), err_static (fix_core F max_depth) | 0 := err_static.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.err_static := err_static.decorate_error instance nat : nat.err_static := err_static.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : err_static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact err_static.of_fail h }⟩ end err_static namespace step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_step_of_static_done [static p] (h : ∃ cb n n' a, p cb n = done n' a) : ¬ step p := begin introI, rcases h with ⟨cb, n, n', a, h⟩, have hs := static.of_done h, simpa [←hs] using of_done h end lemma pure (a : α) : ¬ step (pure a) := begin apply not_step_of_static_done, simp [pure_eq_done] end instance bind {f : α → parser β} [p.step] [∀ a, (f a).static] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact (static.of_done hf) ▸ (of_done hp) }⟩ instance bind' {f : α → parser β} [p.static] [∀ a, (f a).step] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, rw static.of_done hp, exact of_done hf }⟩ instance and_then {q : parser β} [p.step] [q.static] : (p >> q).step := step.bind instance and_then' {q : parser β} [p.static] [q.step] : (p >> q).step := step.bind' instance map [p.step] {f : α → β} : (f <$> p).step := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.step] [p.static] : (f <*> p).step := step.bind instance seq' {f : parser (α → β)} [f.static] [p.step] : (f <*> p).step := step.bind' instance mmap {f : α → parser β} [(f a).step] : ([a].mmap f).step := begin convert step.bind, { apply_instance }, { intro, convert static.bind, { exact static.pure }, { exact λ _, static.pure } } end instance mmap' {f : α → parser β} [(f a).step] : ([a].mmap' f).step := begin convert step.and_then, { apply_instance }, { exact static.pure } end instance failure : @parser.step α failure := ⟨λ _ _ _ _, by simp⟩ lemma guard_true : ¬ step (guard true) := pure _ instance guard : step (guard false) := step.failure instance orelse [p.step] [q.step] : (p <|> q).step := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).step ↔ p.step := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.step] : (@decorate_errors α msgs p).step := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).step ↔ p.step := decorate_errors_iff instance decorate_error [p.step] : (@decorate_error α msg p).step := step.decorate_errors instance any_char : step any_char := begin constructor, intros cb n, simp_rw [any_char_eq_done], rintro _ _ ⟨_, rfl, -⟩, simp end instance sat {p : char → Prop} [decidable_pred p] : step (sat p) := begin constructor, intros cb n, simp_rw [sat_eq_done], rintro _ _ ⟨_, _, rfl, -⟩, simp end lemma eps : ¬ step eps := step.pure () instance ch {c : char} : step (ch c) := step.decorate_error lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').step ↔ cb'.size = 1 := begin have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], split, { introI, simpa using of_done this }, { intro h, constructor, intros cb n n' _, rw [char_buf_eq_done, h], rintro ⟨rfl, -⟩, refl } end instance one_of {cs : list char} : (one_of cs).step := step.decorate_errors instance one_of' {cs : list char} : (one_of' cs).step := step.and_then lemma str_iff {s : string} : (str s).step ↔ s.length = 1 := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.step := begin apply not_step_of_static_done, simp [remaining_eq_done] end lemma eof : ¬ eof.step := begin apply not_step_of_static_done, simp only [eof_eq_done, exists_eq_left', exists_const], use [buffer.nil, 0], simp end -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : ∀ (max_depth : ℕ), step (fix_core F max_depth) | 0 := step.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.step := step.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : step (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end step section step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma many1_eq_done_iff_many_eq_done [p.step] [p.bounded] {x : α} {xs : list α} : many1 p cb n = done n' (x :: xs) ↔ many p cb n = done n' (x :: xs) := begin induction hx : (x :: xs) with hd tl IH generalizing x xs n n', { simpa using hx }, split, { simp only [many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (tsub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { rw ←@IH hd' tl' at hm, swap, refl, simp only [many1_eq_done, many, foldr] at hm, obtain ⟨np, hp', hf⟩ := hm, have : np = n + 1 + 1 := step.of_done hp', subst this, simpa [nat.sub_succ, many_eq_done, hp, hk, foldr_core_eq_done, hp'] using hf } }, { simp only [many_eq_done, many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (tsub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { simp [hp], rw ←@IH hd' tl' (n + 1) n', swap, refl, rw [hk, foldr_core_eq_done, or.comm] at hm, obtain (hm | ⟨np, hd', tl', hp', hf, hm⟩) := hm, { simpa using hm }, simp only at hm, obtain ⟨rfl, rfl⟩ := hm, have : np = n + 1 + 1 := step.of_done hp', subst this, simp [nat.sub_succ, many, many1_eq_done, hp, hk, foldr_core_eq_done, hp', ←hf, foldr] } } end end step namespace prog variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} @[priority 100] -- see Note [lower instance priority] instance of_step [step p] : prog p := ⟨λ _ _ _ _ h, by { rw step.of_done h, exact nat.lt_succ_self _ }⟩ lemma pure (a : α) : ¬ prog (pure a) := begin introI h, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end instance bind {f : α → parser β} [p.prog] [∀ a, (f a).mono] : (p >>= f).prog := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact lt_of_lt_of_le (of_done hp) (mono.of_done hf) }⟩ instance and_then {q : parser β} [p.prog] [q.mono] : (p >> q).prog := prog.bind instance map [p.prog] {f : α → β} : (f <$> p).prog := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.prog] [p.mono] : (f <*> p).prog := prog.bind instance mmap {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap f).prog := begin constructor, simp only [and_imp, bind_eq_done, return_eq_pure, mmap, exists_imp_distrib, pure_eq_done], rintro _ _ _ _ _ _ h _ _ hp rfl rfl, exact lt_of_lt_of_le (of_done h) (mono.of_done hp) end instance mmap' {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap' f).prog := begin constructor, simp only [and_imp, bind_eq_done, mmap', exists_imp_distrib, and_then_eq_bind], intros _ _ _ _ _ _ h hm, exact lt_of_lt_of_le (of_done h) (mono.of_done hm) end instance failure : @parser.prog α failure := prog.of_step lemma guard_true : ¬ prog (guard true) := pure _ instance guard : prog (guard false) := prog.failure instance orelse [p.prog] [q.prog] : (p <|> q).prog := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).prog ↔ p.prog := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.prog] : (@decorate_errors α msgs p).prog := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).prog ↔ p.prog := decorate_errors_iff instance decorate_error [p.prog] : (@decorate_error α msg p).prog := prog.decorate_errors instance any_char : prog any_char := prog.of_step instance sat {p : char → Prop} [decidable_pred p] : prog (sat p) := prog.of_step lemma eps : ¬ prog eps := prog.pure () instance ch {c : char} : prog (ch c) := prog.of_step lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').prog ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, this, decorate_error_iff], cases cb'.to_list, { simp [pure] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).prog := prog.decorate_errors instance one_of' {cs : list char} : (one_of' cs).prog := prog.and_then lemma str_iff {s : string} : (str s).prog ↔ s ≠ "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.prog := begin introI h, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end lemma eof : ¬ eof.prog := begin introI h, have : eof buffer.nil 0 = done 0 () := by simpa [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end -- TODO: add foldr and foldl, many, etc, fix_core instance many1 [p.mono] [p.prog] : p.many1.prog := begin constructor, rintro cb n n' (_ | ⟨hd, tl⟩), { simp }, { rw many1_eq_done, rintro ⟨np, hp, h⟩, exact (of_done hp).trans_le (mono.of_done h) } end lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : ∀ (max_depth : ℕ), prog (fix_core F max_depth) | 0 := prog.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.prog := prog.of_step instance nat : nat.prog := prog.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : prog (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end prog variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} section many -- TODO: generalize to p.prog instead of p.step lemma many_sublist_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : ∀ k < n' - n, p.many cb (n + k) = done n' (l.drop k) := begin induction l with hd tl hl generalizing n, { rw many_eq_done_nil at h, simp [h.left] }, intros m hm, cases m, { exact h }, rw [list.drop, nat.add_succ, ←nat.succ_add], apply hl, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, convert h, exact (step.of_done hp).symm }, { exact nat.lt_pred_iff.mpr hm }, end lemma many_eq_nil_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : p.many cb n' = done n' [] := begin induction l with hd tl hl generalizing n, { convert h, rw many_eq_done_nil at h, exact h.left.symm }, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, -, h⟩ := h, exact hl h } end lemma many_eq_nil_of_out_of_bound [p.bounded] {l : list α} (h : p.many cb n = done n' l) (hn : cb.size < n) : n' = n ∧ l = [] := begin cases l, { rw many_eq_done_nil at h, exact ⟨h.left.symm, rfl⟩ }, { rw many_eq_done at h, obtain ⟨np, hp, -⟩ := h, exact absurd (bounded.of_done hp) hn.not_lt } end lemma many1_length_of_done [p.mono] [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : l.length = n' - n := begin induction l with hd tl hl generalizing n n', { simpa using h }, { obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done h), subst hk, simp only [many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, have := step.of_done hp, subst this, cases tl, { simp only [many_eq_done_nil, add_left_inj, exists_and_distrib_right, self_eq_add_right] at h, rcases h with ⟨rfl, -⟩, simp }, rw ←many1_eq_done_iff_many_eq_done at h, specialize hl h, simp [hl, add_comm, add_assoc, nat.sub_succ] } end lemma many1_bounded_of_done [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : n' ≤ cb.size := begin induction l with hd tl hl generalizing n n', { simpa using h }, { simp only [many1_eq_done] at h, obtain ⟨np, hp, h⟩ := h, have := step.of_done hp, subst this, cases tl, { simp only [many_eq_done_nil, exists_and_distrib_right] at h, simpa [←h.left] using bounded.of_done hp }, { rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } } end end many section nat /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`. The number of characters parsed in is necessarily `n' - n`. This is one of the directions of `nat_eq_done`. -/ lemma nat_of_done {val : ℕ} (h : nat cb n = done n' val) : val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) := begin /- The parser `parser.nat` that generates a decimal number from a string of digit characters does several things. First it ingests in as many digits as it can with `many1 digit`. Then, it folds over the resulting `list ℕ` using a helper function that keeps track of both the running sum an and the magnitude so far, using a `(sum, magnitude) : (ℕ × ℕ)` pair. The final sum is extracted using a `prod.fst`. To prove that the value that `parser.nat` produces, after moving precisely `n' - n` steps, is precisely what `nat.of_digits` would give, if supplied the string that is in the ingested `char_buffer` (modulo conversion from `char` to `ℕ ), we need to induct over the length `n' - n` of `cb : char_buffer` ingested, and prove that the parser must have terminated due to hitting either the end of the `char_buffer` or a non-digit character. The statement of the lemma is phrased using a combination of `list.drop` and `list.map` because there is no currently better way to extract an "interval" from a `char_buffer`. Additionally, the statement uses a `list.reverse` because `nat.of_digits` is little-endian. We try to stop referring to the `cb : char_buffer` as soon as possible, so that we can instead regard a `list char` instead, which lends itself better to proofs via induction. -/ /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` with -- the function above. We use this lemma later when we finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We convert the hypothesis that `parser.nat` has succeeded into an existential that there is -- some list of digits that it has parsed in, and that those digits, when folded over by the -- function above, give the value at hand. simp only [nat, pure_eq_done, natm, decorate_error_eq_done, bind_eq_done] at h, obtain ⟨n', l, hp, rfl, rfl⟩ := h, -- We now want to stop working with the `cb : char_buffer` and parse positions `n` and `n'`, -- and just deal with the parsed digit list `l : list ℕ`. To do so, we have to show that -- this is precisely the list that could have been parsed in, no smaller and no greater. induction l with lhd ltl IH generalizing n n' cb, { -- Base case: we parsed in no digits whatsoever. But this is impossible because `parser.many1` -- must produce a list that is not `list.nil`, by `many1_ne_done_nil`. simpa using hp }, -- Inductive case: -- We must prove that the first digit parsed in `lhd : ℕ` is precisely the digit that is -- represented by the character at position `n` in `cb : char_buffer`. -- We will also prove the correspondence between the subsequent digits `ltl : list ℕ` and the -- remaining characters past position `n` up to position `n'`. cases hx : (list.drop n (buffer.to_list cb)) with chd ctl, { -- Are there even characters left to parse, at position `n` in the `cb : char_buffer`? In other -- words, are we already out of bounds, and thus could not have parsed in any value -- successfully. But this must be a contradiction because `parser.digit` is a `bounded` parser, -- (due to its being defined via `parser.decorate_error`), which means it only succeeds -- in-bounds, and the `many1` parser combinator retains that property. have : cb.size ≤ n := by simpa using list.drop_eq_nil_iff_le.mp hx, exact absurd (bounded.of_done hp) this.not_lt }, -- We prove that the first digit parsed in is precisely the digit that is represented by the -- character at position `n`, which we now call `chd : char`. have chdh : chd.to_nat - '0'.to_nat = lhd, { simp only [many1_eq_done] at hp, -- We know that `parser.digit` succeeded, so it has moved to a possibly different position. -- In fact, we know that this new position is `n + 1`, by the `step` property of -- `parser.digit`. obtain ⟨_, hp, -⟩ := hp, have := step.of_done hp, subst this, -- We now unfold what it means for `parser.digit` to succeed, which means that the character -- parsed in was "numeric" (for some definition of that property), and, more importantly, -- that the `n`th character of `cb`, let's say `c`, when converted to a `ℕ` via -- `char.to_nat c - '0'.to_nat`, must be equal to the resulting value, `lhd` in our case. simp only [digit_eq_done, buffer.read_eq_nth_le_to_list, hx, buffer.length_to_list, true_and, add_left_inj, list.length, list.nth_le, eq_self_iff_true, exists_and_distrib_left, fin.coe_mk] at hp, rcases hp with ⟨_, hn, rfl, _, _⟩, -- But we already know the list corresponding to `cb : char_buffer` from position `n` and on -- is equal to `(chd :: ctl) : list char`, so our `c` above must satisfy `c = chd`. have hn' : n < cb.to_list.length := by simpa using hn, rw ←list.cons_nth_le_drop_succ hn' at hx, -- We can ignore proving any correspondence of `ctl : list char` to the other portions of the -- `cb : char_buffer`. simp only at hx, simp [hx] }, -- We know that we parsed in more than one character because of the `prog` property of -- `parser.digit`, which the `many1` parser combinator retains. In other words, we know that -- `n < n'`, and so, the list of digits `ltl` must correspond to the list of digits that -- `digit.many1 cb (n + 1)` would produce. We know that the shift of `1` in `n ↦ n + 1` holds -- due to the `step` property of `parser.digit`. -- We also get here `k : ℕ` which will indicate how many characters we parsed in past position -- `n`. We will prove later that this must be the number of digits we produced as well in `ltl`. obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done hp), have hdm : ltl = [] ∨ digit.many1 cb (n + 1) = done n' ltl, { cases ltl, { simp }, { rw many1_eq_done at hp, obtain ⟨_, hp, hp'⟩ := hp, simpa [step.of_done hp, many1_eq_done_iff_many_eq_done] using hp' } }, -- Now we case on the two possibilities, that there was only a single digit parsed in, and -- `ltl = []`, or, had we started parsing at `n + 1` instead, we'd parse in the value associated -- with `ltl`. -- We prove that the LHS, which is a fold over a `list ℕ` is equal to the RHS, which is that -- the `val : ℕ` that `nat.of_digits` produces when supplied a `list ℕ that has been produced -- via mapping a `list char` using `char.to_nat`. Specifically, that `list char` are the -- characters in the `cb : char_buffer`, from position `n` to position `n'` (excluding `n'`), -- in reverse. rcases hdm with rfl|hdm, { -- Case that `ltl = []`. simp only [many1_eq_done, many_eq_done_nil, exists_and_distrib_right] at hp, -- This means we must have failed parsing with `parser.digit` at some other position, -- which we prove must be `n + 1` via the `step` property. obtain ⟨_, hp, rfl, hp'⟩ := hp, have := step.of_done hp, subst this, -- Now we rely on the simplifier, which simplfies the LHS, which is a fold over a singleton -- list. On the RHS, `list.take (n + 1 - n)` also produces a singleton list, which, when -- reversed, is the same list. `nat.of_digits` of a singleton list is precisely the value in -- the list. And we already have that `chd.to_nat - '0'.to_nat = lhd`. simp [chdh] }, -- We now have to deal with the case where we parsed in more than one digit, and thus -- `n + 1 < n'`, which means `ctl` has one or more elements. Similarly, `ltl` has one or more -- elements. -- We finish ridding ourselves of references to `cb : char_buffer`, by relying on the fact that -- our `ctl : list char` must be the appropriate portion of `cb` once enough elements have been -- dropped and taken. have rearr : list.take (n + (k + 1) - (n + 1)) (list.drop (n + 1) (buffer.to_list cb)) = ctl.take k, { simp [←list.tail_drop, hx, nat.sub_succ, hk] }, -- We have to prove that the number of digits produced (given by `ltl`) is equal to the number -- of characters parsed in, as given by `ctl.take k`, and that this is precisely `k`. We phrase it -- in the statement using `min`, because lemmas about `list.length (list.take ...)` simplify to -- a statement that uses `min`. The `list.length` term appears from the reduction of the folding -- function, as proven above. have ltll : min k ctl.length = ltl.length, { -- Here is an example of how statements about the `list.length` of `list.take` simplify. have : (ctl.take k).length = min k ctl.length := by simp, -- We bring back the underlying definition of `ctl` as the result of a sequence of `list.take` -- and `list.drop`, so that lemmas about `list.length` of those can fire. rw [←this, ←rearr, many1_length_of_done hdm], -- Likewise, we rid ourselves of the `k` we generated earlier. have : k = n' - n - 1, { simp [hk, add_assoc] }, subst this, simp only [nat.sub_succ, add_comm, ←nat.pred_sub, buffer.length_to_list, nat.pred_one_add, min_eq_left_iff, list.length_drop, add_tsub_cancel_left, list.length_take, tsub_zero], -- We now have a goal of proving an inequality dealing with `nat` subtraction and `nat.pred`, -- both of which require special care to provide positivity hypotheses. rw [tsub_le_tsub_iff_right, nat.pred_le_iff], { -- We know that `n' ≤ cb.size` because of the `bounded` property, that a parser will not -- produce a `done` result at a position farther than the size of the underlying -- `char_buffer`. convert many1_bounded_of_done hp, -- What is now left to prove is that `0 < cb.size`, which can be rephrased -- as proving that it is nonempty. cases hc : cb.size, { -- Proof by contradiction. Let's say that `cb.size = 0`. But we know that we succeeded -- parsing in at position `n` using a `bounded` parser, so we must have that -- `n < cb.size`. have := bounded.of_done hp, rw hc at this, -- But then `n < 0`, a contradiction. exact absurd n.zero_le this.not_le }, { simp } }, { -- Here, we use the same result as above, that `n < cb.size`, and relate it to -- `n ≤ cb.size.pred`. exact nat.le_pred_of_lt (bounded.of_done hp) } }, -- Finally, we simplify. On the LHS, we have a fold over `lhd :: ltl`, which simplifies to -- the operation of the summing folding function on `lhd` and the fold over `ltl`. To that we can -- apply the induction hypothesis, because we know that our parser would have succeeded had we -- started at position `n + 1`. We replace mentions of `cb : char_buffer` with the appropriate -- `chd :: ctl`, replace `lhd` with the appropriate statement of how it is calculated from `chd`, -- and use the lemmas describing the length of `ltl` and how it is associated with `k`. We also -- remove mentions of `n'` and replace with an expression using solely `n + k + 1`. -- We use the lemma we proved above about how the folding function produces the -- `prod.snd` value, which is `10` to the power of the length of the list provided to the fold. -- Finally, we rely on `nat.of_digits_append` for the related statement of how digits given -- are used in the `nat.of_digits` calculation, which also involves `10 ^ list.length ...`. -- The `list.append` operation appears due to the `list.reverse (chd :: ctl)`. -- We include some addition and multiplication lemmas to help the simplifier rearrange terms. simp [IH _ hdm, hx, hk, rearr, ←chdh, ←ltll, hpow, add_assoc, nat.of_digits_append, mul_comm] end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for all `k : ℕ`, `n ≤ k`, `k < n'`, the character at the `k`th position in `cb : char_buffer` is "numeric", that is, is between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_as_digit {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' ≤ cb.size) k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn⟩ ∧ cb.read ⟨k, hk.trans_le hn⟩ ≤ '9' := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: we prove that the `parser.digit.many1` produced a valid `(hd :: tl) : list ℕ`, -- by showing that is the case for the character at position `n`, which gave `hd`, and use the -- induction hypothesis on the remaining `tl`. -- We break apart a `many1` success into a success of the underlying `parser.digit` to give `hd` -- and a `parser.digit.many` which gives `tl`. We first deal with the `hd`. rw many1_eq_done at h, -- Right away, we can throw away the information about the "new" position that `parser.digit` -- ended on because we will soon prove that it must have been `n + 1`. obtain ⟨_, hp, h⟩ := h, -- The main lemma here is `digit_eq_done`, which already proves the necessary conditions about -- the character at hand. What is left to do is properly unpack the information. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left, exists_and_distrib_left] at hp, obtain ⟨rfl, -, hn, ge0, le9, rfl⟩ := hp, -- Let's now consider a position `k` between `n` and `n'`, excluding `n'`. intros hn k hk hk', -- What if we are at `n`? What if we are past `n`? We case on the `n ≤ k`. rcases hk'.eq_or_lt with rfl|hk', { -- The `n = k` case. But this is exactly what we know already, so we provide the -- relevant hypotheses. exact ⟨ge0, le9⟩ }, -- The `n < k` case. First, we check if there would have even been digits parsed in. So, we -- case on `tl : list ℕ` cases tl, { -- Case where `tl = []`. But that means `many` gave us a `[]` so either the character at -- position `k` was not "numeric" or we are out of bounds. More importantly, when `many` -- successfully produces a `[]`, it does not progress the parser head, so we have that -- `n + 1 = n'`. This will lead to a contradiction because now we have `n < k` and `k < n + 1`. simp only [many_eq_done_nil, exists_and_distrib_right] at h, -- Extract out just the `n + 1 = n'`. obtain ⟨rfl, -⟩ := h, -- Form the contradictory hypothesis, and discharge the goal. have : k < k := hk.trans_le (nat.succ_le_of_lt hk'), exact absurd this (lt_irrefl _) }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw ←many1_eq_done_iff_many_eq_done at h, apply hl h, -- All that is left to prove is that our `k` is at least our new "lower bound" `n + 1`, which -- we have from our original split of the `n ≤ k`, since we are now on the `n < k` case. exact nat.succ_le_of_lt hk' } end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for the ending position `n'`, either it is beyond the end of the `cb : char_buffer`, or the character at that position is not "numeric", that is, between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_bounded {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' < cb.size), '0' ≤ cb.read ⟨n', hn⟩ → '9' < cb.read ⟨n', hn⟩ := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. -- We deal with the case of `n'` is "out-of-bounds" right away by requiring that -- `∀ (hn : n' < cb.size)`. Thus we only have to prove the lemma for the cases where `n'` is still -- "in-bounds". simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: at least one character has been parsed in, starting at position `n`. -- We know that the size of `cb : char_buffer` must be at least `n + 1` because -- `parser.digit.many1` is `bounded` (`n < cb.size`). -- We show that either we parsed in just that one character, or we use the inductive hypothesis. obtain ⟨k, hk⟩ : ∃ k, cb.size = n + k + 1 := nat.exists_eq_add_of_lt (bounded.of_done h), cases tl, { -- Case where `tl = []`, so we parsed in only `hd`. That must mean that `parser.digit` failed -- at `n + 1`. simp only [many1_eq_done, many_eq_done_nil, and.left_comm, exists_and_distrib_right, exists_eq_left] at h, -- We throw away the success information of what happened at position `n`, and we do not need -- the "error" value that the failure produced. obtain ⟨-, _, h⟩ := h, -- If `parser.digit` failed at `n + 1`, then either we hit a non-numeric character, or -- we are out of bounds. `digit_eq_fail` provides us with those two cases. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left] at h, obtain (⟨rfl, h⟩ | ⟨h, -⟩) := h, { -- First case: we are still in bounds, but the character is not numeric. We must prove -- that we are still in bounds. But we know that from our initial requirement. intro hn, simpa using h hn }, { -- Second case: we are out of bounds, and somehow the fold that `many1` relied on failed. -- But we know that `parser.digit` is mono, that is, it never goes backward in position, -- in neither success nor in failure. We also have that `foldr_core` respects `mono`. -- But in this case, `foldr_core` is starting at position `n' + 1` but failing at -- position `n'`, which is a contradiction, because otherwise we would have `n' + 1 ≤ n'`. simpa using mono.of_fail h } }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw many1_eq_done at h, obtain ⟨_, -, h⟩ := h, rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } end /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`, where `n < n'`. The number of characters parsed in is necessarily `n' - n`. Additionally, all of the characters in the `cb` starting at position `n` (inclusive) up to position `n'` (exclusive) are "numeric", in that they are between `'0'` and `'9'` inclusive. Such a `char_buffer` would produce the `ℕ` value encoded by its decimal characters. -/ lemma nat_eq_done {val : ℕ} : nat cb n = done n' val ↔ ∃ (hn : n < n'), val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) ∧ (∀ (hn' : n' < cb.size), ('0' ≤ cb.read ⟨n', hn'⟩ → '9' < cb.read ⟨n', hn'⟩)) ∧ ∃ (hn'' : n' ≤ cb.size), (∀ k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn''⟩ ∧ cb.read ⟨k, hk.trans_le hn''⟩ ≤ '9') := begin -- To prove this iff, we have most of the way in the forward direction, using the lemmas proven -- above. First, we must use that `parser.nat` is `prog`, which means that on success, it must -- move forward. We also have to prove the statement that a success means the parsed in -- characters were properly "numeric". It involves first generating ane existential witness -- that the parse was completely "in-bounds". -- For the reverse direction, we first discharge the goals that deal with proving that our parser -- succeeded because it encountered characters with the proper "numeric" properties, was -- "in-bounds" and hit a nonnumeric character. The more difficult portion is proving that the -- list of characters from positions `n` to `n'`, when folded over by the function defined inside -- `parser.nat` gives exactly the same value as `nat.of_digits` when supplied with the same -- (modulo rearrangement) list. To reach this goal, we try to remove any reliance on the -- underlying `cb : char_buffer` or parsers as soon as possible, via a cased-induction. refine ⟨λ h, ⟨prog.of_done h, nat_of_done h, nat_of_done_bounded h, _⟩, _⟩, { -- To provide the existential witness that `n'` is within the bounds of the `cb : char_buffer`, -- we rely on the fact that `parser.nat` is primarily a `parser.digit.many1`, and that `many1`, -- must finish with the bounds of the `cb`, as long as the underlying parser is `step` and -- `bounded`, which `digit` is. We do not prove this as a separate lemma about `parser.nat` -- because it would almost always be only relevant in this larger theorem. -- We clone the success hypothesis `h` so that we can supply it back later. have H := h, -- We unwrap the `parser.nat` success down to the `many1` success, throwing away other info. rw [nat] at h, simp only [decorate_error_eq_done, bind_eq_done, pure_eq_done, and.left_comm, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨_, h, -⟩ := h, -- Now we get our existential witness that `n' ≤ cb.size`. replace h := many1_bounded_of_done h, -- With that, we can use the lemma proved above that our characters are "numeric" exact ⟨h, nat_of_done_as_digit H h⟩ }, -- We now prove that given the `cb : char_buffer` with characters within the `n ≤ k < n'` interval -- properly "numeric" and such that their `nat.of_digits` generates the `val : ℕ`, `parser.nat` -- of that `cb`, when starting at `n`, will finish at `n'` and produce the same `val`. -- We first introduce the relevant hypotheses, including the fact that we have a valid interval -- where `n < n'` and that characters at `n'` and beyond are no longer numeric. rintro ⟨hn, hv, hb, hn', ho⟩, -- We first unwrap the `parser.nat` definition to the underlying `parser.digit.many1` success -- and the fold function of the digits. rw nat, simp only [and.left_comm, pure_eq_done, hv, decorate_error_eq_done, list.map_reverse, bind_eq_done, exists_eq_left, exists_and_distrib_left], -- We won't actually need the `val : ℕ` itself, since it is entirely characterized by the -- underlying characters. Instead, we will induct over the `list char` of characters from -- position `n` onwards, showing that if we could have provided a list at `n`, we could have -- provided a valid list of characters at `n + 1` too. clear hv val, /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We induct over the characters available at position `n` and onwards. Because `cb` is used -- in other expressions, we utilize the `induction H : ...` tactic to induct separately from -- destructing `cb` itself. induction H : (cb.to_list.drop n) with hd tl IH generalizing n, { -- Base case: there are no characters at position `n` or onwards, which means that -- `cb.size ≤ n`. But this is a contradiction, since we have `n < n' ≤ cb.size`. rw list.drop_eq_nil_iff_le at H, refine absurd ((lt_of_le_of_lt H hn).trans_le hn') _, simp }, { -- Inductive case: we prove that if we could have parsed from `n + 1`, we could have also parsed -- from `n`, if there was a valid numerical character at `n`. Most of the body -- of this inductive case is generating the appropriate conditions for use of the inductive -- hypothesis. specialize @IH (n + 1), -- We have, by the inductive case, that there is at least one character `hd` at position `n`, -- with the rest at `tl`. We rearrange our inductive case to make `tl` be expressed as -- list.drop (n + 1), which fits out induction hypothesis conditions better. To use the -- rearranging lemma, we must prove that we are "dropping" in bounds, which we supply on-the-fly simp only [←list.cons_nth_le_drop_succ (show n < cb.to_list.length, by simpa using hn.trans_le hn')] at H, -- We prove that parsing our `n`th character, `hd`, would have resulted in a success from -- `parser.digit`, with the appropriate `ℕ` success value. We use this later to simplify the -- unwrapped fold, since `hd` is our head character. have hdigit : digit cb n = done (n + 1) (hd.to_nat - '0'.to_nat), { -- By our necessary condition, we know that `n` is in bounds, and that the `n`th character -- has the necessary "numeric" properties. specialize ho n hn le_rfl, -- We prove an additional result that the conversion of `hd : char` to a `ℕ` would give a -- value `x ≤ 9`, since that is part of the iff statement in the `digit_eq_done` lemma. have : (buffer.read cb ⟨n, hn.trans_le hn'⟩).to_nat - '0'.to_nat ≤ 9, { -- We rewrite the statement to be a statement about characters instead, and split the -- inequality into the case that our hypotheses prove, and that `'0' ≤ '9'`, which -- is true by computation, handled by `dec_trivial`. rw [show 9 = '9'.to_nat - '0'.to_nat, from dec_trivial, tsub_le_tsub_iff_right], { exact ho.right }, { dec_trivial } }, -- We rely on the simplifier, mostly powered by `digit_eq_done`, and supply all the -- necessary conditions of bounds and identities about `hd`. simp [digit_eq_done, this, ←H.left, buffer.nth_le_to_list, hn.trans_le hn', ho] }, -- We now case on whether we've moved to the end of our parse or not. We phrase this as -- casing on either `n + 1 < n` or `n ≤ n + 1`. The more difficult goal comes first. cases lt_or_ge (n + 1) n' with hn'' hn'', { -- Case `n + 1 < n'`. We can directly supply this to our induction hypothesis. -- We now have to prove, for the induction hypothesis, that the characters at positions `k`, -- `n + 1 ≤ k < n'` are "numeric". We already had this for `n ≤ k < n`, so we just rearrange -- the hypotheses we already have. specialize IH hn'' _ H.right, { intros k hk hk', apply ho, exact nat.le_of_succ_le hk' }, -- With the induction hypothesis conditions satisfier, we can extract out a list that -- `parser.digit.many1` would have generated from position `n + 1`, as well as the associated -- property of the list, that it folds into what `nat.of_digits` generates from the -- characters in `cb : char_buffer`, now known as `hd :: tl`. obtain ⟨l, hdl, hvl⟩ := IH, -- Of course, the parsed in list from position `n` would be `l` prepended with the result -- of parsing in `hd`, which is provided explicitly. use (hd.to_nat - '0'.to_nat) :: l, -- We case on `l : list ℕ` so that we can make statements about the fold on `l` cases l with lhd ltl, { -- As before, if `l = []` then `many1` produced a `[]` success, which is a contradiction. simpa using hdl }, -- Case `l = lhd :: ltl`. We can rewrite the fold of the function inside `parser.nat` on -- `lhd :: ltl`, which will be used to rewrite in the goal. simp only [natm, list.foldr] at hvl, -- We also expand the fold in the goal, using the expanded fold from our hypothesis, powered -- by `many1_eq_done` to proceed in the parsing. We know exactly what the next `many` will -- produce from `many1_eq_done_iff_many_eq_done.mp` of our `hdl` hypothesis. Finally, -- we also use `hdigit` to express what the single `parser.digit` result would be at `n`. simp only [natm, hvl, many1_eq_done, hdigit, many1_eq_done_iff_many_eq_done.mp hdl, true_and, and_true, eq_self_iff_true, list.foldr, exists_eq_left'], -- Now our goal is solely about the equality of two different folding functions, one from the -- function defined inside `parser.nat` and the other as `nat.of_digits`, when applied to -- similar list inputs. -- First, we rid ourselves of `n'` by replacing with `n + m + 1`, which allows us to -- simplify the term of how many elements we are keeping using a `list.take`. obtain ⟨m, rfl⟩ : ∃ m, n' = n + m + 1 := nat.exists_eq_add_of_lt hn, -- The following rearrangement lemma is to simplify the `list.take (n' - n)` expression we had have : n + m + 1 - n = m + 1, { rw [add_assoc, tsub_eq_iff_eq_add_of_le, add_comm], exact nat.le_add_right _ _ }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` -- with the function above. We use this lemma to finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We prove that the parsed list of digits `(lhd :: ltl) : list ℕ` must be of length `m` -- which is used later when the `parser.nat` fold places `ltl.length` in the exponent. have hml : ltl.length + 1 = m := by simpa using many1_length_of_done hdl, -- A simplified `list.length (list.take ...)` expression refers to the minimum of the -- underlying length and the amount of elements taken. We know that `m ≤ tl.length`, so -- we provide this auxiliary lemma so that the simplified "take-length" can simplify further have ltll : min m tl.length = m, { -- On the way to proving this, we have to actually show that `m ≤ tl.length`, by showing -- that since `tl` was a subsequence in `cb`, and was retrieved from `n + 1` to `n + m + 1`, -- then since `n + m + 1 ≤ cb.size`, we have that `tl` must be at least `m` in length. simpa [←H.right, le_tsub_iff_right (hn''.trans_le hn').le, add_comm, add_assoc, add_left_comm] using hn' }, -- Finally, we rely on the simplifier. We already expressions of `nat.of_digits` on both -- the LHS and RHS. All that is left to do is to prove that the summand on the LHS is produced -- by the fold of `nat.of_digits` on the RHS of `hd :: tl`. The `nat.of_digits_append` is used -- because of the append that forms from the included `list.reverse`. The lengths of the lists -- are placed in the exponents with `10` as a base, and are combined using `←pow_succ 10`. -- Any complicated expression about list lengths is further simplified by the auxiliary -- lemmas we just proved. Finally, we assist the simplifier by rearranging terms with our -- `n + m + 1 - n = m + 1` proof and `mul_comm`. simp [this, hpow, nat.of_digits_append, mul_comm, ←pow_succ 10, hml, ltll] }, { -- Consider the case that `n' ≤ n + 1`. But then since `n < n' ≤ n + 1`, `n' = n + 1`. have : n' = n + 1 := le_antisymm hn'' (nat.succ_le_of_lt hn), subst this, -- This means we have only parsed in a single character, so the resulting parsed in list -- is explicitly formed from an expression we can construct from `hd`. use [[hd.to_nat - '0'.to_nat]], -- Our list expression simplifies nicely because it is a fold over a singleton, so we -- do not have to supply any auxiliary lemmas for it, other than what we already know about -- `hd` and the function defined in `parser.nat`. However, we will have to prove that our -- parse ended because of a good reason: either we are out of bounds or we hit a nonnumeric -- character. simp only [many1_eq_done, many_eq_done_nil, digit_eq_fail, natm, and.comm, and.left_comm, hdigit, true_and, mul_one, nat.of_digits_singleton, list.take, exists_eq_left, exists_and_distrib_right, add_tsub_cancel_left, eq_self_iff_true, list.reverse_singleton, zero_add, list.foldr, list.map], -- We take the route of proving that we hit a nonnumeric character, since we already have -- a hypothesis that says that characters at `n'` and past it are nonnumeric. (Note, by now -- we have substituted `n + 1` for `n'. -- We are also asked to provide the error value that our failed parse would report. But -- `digit_eq_fail` already knows what it is, so we can discharge that with an inline `rfl`. refine ⟨_, or.inl ⟨rfl, _⟩⟩, -- The nonnumeric condition looks almost exactly like the hypothesis we already have, so -- we let the simplifier align them for us simpa using hb } } end end nat end parser
5bd7ec5ce695f1b2bc2b0483dddb4c631bcb762d
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/measure_theory/integral/interval_integral.lean
650d202b4d009e50ddbb35e7a6040f93fa99f880
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
125,108
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot, Sébastien Gouëzel -/ import analysis.calculus.extend_deriv import analysis.calculus.fderiv_measurable import analysis.normed_space.dual import measure_theory.integral.set_integral import measure_theory.integral.vitali_caratheodory import measure_theory.measure.lebesgue /-! # Integral over an interval In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and `-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. We prove a few simple properties and several versions of the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). Recall that its first version states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`, and its second version states that, if `f` has an integrable derivative on `[a, b]`, then `∫ x in a..b, f' x = f b - f a`. ## Main statements ### FTC-1 for Lebesgue measure We prove several versions of FTC-1, all in the `interval_integral` namespace. Many of them follow the naming scheme `integral_has(_strict?)_(f?)deriv(_within?)_at(_of_tendsto_ae?)(_right|_left?)`. They formulate FTC in terms of `has(_strict?)_(f?)deriv(_within?)_at`. Let us explain the meaning of each part of the name: * `_strict` means that the theorem is about strict differentiability; * `f` means that the theorem is about differentiability in both endpoints; incompatible with `_right|_left`; * `_within` means that the theorem is about one-sided derivatives, see below for details; * `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit almost surely as `x` tends to `a` and/or `b`; * `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left) endpoint. We also reformulate these theorems in terms of `(f?)deriv(_within?)`. These theorems are named `(f?)deriv(_within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the name. ### One-sided derivatives Theorem `integral_has_fderiv_within_at_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and corresponding filters `la`, `lb` are given in the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | We use a typeclass `FTC_filter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered by `integral_has_deriv_within_at_of_tendsto_ae_(left|right)` and `integral_has_fderiv_at_of_tendsto_ae`). Similarly, `integral_has_deriv_within_at_of_tendsto_ae_right` works for both one-sided derivatives using the same typeclass to find an appropriate filter. ### FTC for a locally finite measure Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for any measure. The most general of them, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae`, states the following. Let `(la, la')` be an `FTC_filter` pair of filters around `a` (i.e., `FTC_filter a la la'`) and let `(lb, lb')` be an `FTC_filter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. ### FTC-2 and corollaries We use FTC-1 to prove several versions of FTC-2 for the Lebesgue measure, using a similar naming scheme as for the versions of FTC-1. They include: * `interval_integral.integral_eq_sub_of_has_deriv_right_of_le` - most general version, for functions with a right derivative * `interval_integral.integral_eq_sub_of_has_deriv_at'` - version for functions with a derivative on an open set * `interval_integral.integral_deriv_eq_sub'` - version that is easiest to use when computing the integral of a specific function We then derive additional integration techniques from FTC-2: * `interval_integral.integral_mul_deriv_eq_deriv_mul` - integration by parts * `interval_integral.integral_comp_mul_deriv''` - integration by substitution Many applications of these theorems can be found in the file `analysis.special_functions.integrals`. Note that the assumptions of FTC-2 are formulated in the form that `f'` is integrable. To use it in a context with the stronger assumption that `f'` is continuous, one can use `continuous_on.interval_integrable` or `continuous_on.integrable_on_Icc` or `continuous_on.integrable_on_interval`. ## Implementation notes ### Avoiding `if`, `min`, and `max` In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as `integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these intervals is empty and the other coincides with `Ioc (min a b) (max a b)`. Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result. This way some properties can be translated from integrals over sets without dealing with the cases `a ≤ b` and `b ≤ a` separately. ### Choice of the interval We use integral over `Ioc (min a b) (max a b)` instead of one of the other three possible intervals with the same endpoints for two reasons: * this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever `f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom at `b`; this rules out `Ioo` and `Icc` intervals; * with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of `μ`. ### `FTC_filter` class As explained above, many theorems in this file rely on the typeclass `FTC_filter (a : α) (l l' : filter α)` to avoid code duplication. This typeclass combines four assumptions: - `pure a ≤ l`; - `l' ≤ 𝓝 a`; - `l'` has a basis of measurable sets; - if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included in `s`. This typeclass has the following “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`. Furthermore, we have the following instances that are equal to the previously mentioned instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure, it becomes important in the versions of FTC about any locally finite measure if this measure has an atom at one of the endpoints. ### Combining one-sided and two-sided derivatives There are some `FTC_filter` instances where the fact that it is one-sided or two-sided depends on the point, namely `(x, 𝓝[Icc a b] x, 𝓝[Icc a b] x)` (resp. `(x, 𝓝[[a, b]] x, 𝓝[[a, b]] x)`, where `[a, b] = set.interval a b`), with `x ∈ Icc a b` (resp. `x ∈ [a, b]`). This results in a two-sided derivatives for `x ∈ Ioo a b` and one-sided derivatives for `x ∈ {a, b}`. Other instances could be added when needed (in that case, one also needs to add instances for `filter.is_measurably_generated` and `filter.tendsto_Ixx_class`). ## Tags integral, fundamental theorem of calculus, FTC-1, FTC-2, change of variables in integrals -/ noncomputable theory open topological_space (second_countable_topology) open measure_theory set classical filter function open_locale classical topological_space filter ennreal big_operators interval variables {α β 𝕜 E F : Type*} [linear_order α] [measurable_space α] [measurable_space E] [normed_group E] /-! ### Almost everywhere on an interval -/ section variables {μ : measure α} {a b : α} {P : α → Prop} lemma ae_interval_oc_iff : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂μ, x ∈ Ioc a b → P x) ∧ (∀ᵐ x ∂μ, x ∈ Ioc b a → P x) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } lemma ae_measurable_interval_oc_iff {μ : measure α} {β : Type*} [measurable_space β] {f : α → β} : (ae_measurable f $ μ.restrict $ Ι a b) ↔ (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } variables [topological_space α] [opens_measurable_space α] [order_closed_topology α] lemma ae_interval_oc_iff' : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂ (μ.restrict $ Ioc a b), P x) ∧ (∀ᵐ x ∂ (μ.restrict $ Ioc b a), P x) := begin simp_rw ae_interval_oc_iff, rw [ae_restrict_eq, eventually_inf_principal, ae_restrict_eq, eventually_inf_principal] ; exact measurable_set_Ioc end end /-! ### Integrability at an interval -/ /-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these intervals is always empty, so this property is equivalent to `f` being integrable on `(min a b, max a b]`. -/ def interval_integrable (f : α → E) (μ : measure α) (a b : α) := integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ /-- A function is interval integrable with respect to a given measure `μ` on `interval a b` if and only if it is integrable on `Ioc (min a b) (max a b)` with respect to `μ`. This is an equivalent defintion of `interval_integrable`. -/ lemma interval_integrable_iff {f : α → E} {a b : α} {μ : measure α} : interval_integrable f μ a b ↔ integrable_on f (Ioc (min a b) (max a b)) μ := by cases le_total a b; simp [h, interval_integrable] /-- If a function is interval integrable with respect to a given measure `μ` on `interval a b` then it is integrable on `Ioc (min a b) (max a b)` with respect to `μ`. -/ lemma interval_integrable.def {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) : integrable_on f (Ioc (min a b) (max a b)) μ := interval_integrable_iff.mp h lemma interval_integrable_iff_integrable_Ioc_of_le {f : α → E} {a b : α} (hab : a ≤ b) {μ : measure α} : interval_integrable f μ a b ↔ integrable_on f (Ioc a b) μ := by simp [interval_integrable_iff, hab] /-- If a function is integrable with respect to a given measure `μ` then it is interval integrable with respect to `μ` on `interval a b`. -/ lemma measure_theory.integrable.interval_integrable {f : α → E} {a b : α} {μ : measure α} (hf : integrable f μ) : interval_integrable f μ a b := ⟨hf.integrable_on, hf.integrable_on⟩ lemma measure_theory.integrable_on.interval_integrable {f : α → E} {a b : α} {μ : measure α} (hf : integrable_on f (interval a b) μ) : interval_integrable f μ a b := ⟨measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_interval), measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_interval')⟩ namespace interval_integrable section variables {f : α → E} {a b c d : α} {μ ν : measure α} @[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a := h.symm @[refl] lemma refl : interval_integrable f μ a a := by split; simp @[trans] lemma trans (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : interval_integrable f μ a c := ⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc, (hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩ lemma trans_iterate {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : interval_integrable f μ (a 0) (a n) := begin induction n with n hn, { simp }, { exact (hn (λ k hk, hint k (hk.trans n.lt_succ_self))).trans (hint n n.lt_succ_self) } end lemma neg [borel_space E] (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ lemma norm [opens_measurable_space E] (h : interval_integrable f μ a b) : interval_integrable (λ x, ∥f x∥) μ a b := ⟨h.1.norm, h.2.norm⟩ lemma abs {f : α → ℝ} (h : interval_integrable f μ a b) : interval_integrable (λ x, |f x|) μ a b := h.norm lemma mono (hf : interval_integrable f ν a b) (h1 : interval c d ⊆ interval a b) (h2 : μ ≤ ν) : interval_integrable f μ c d := let ⟨h1₁, h1₂⟩ := interval_subset_interval_iff_le.mp h1 in interval_integrable_iff.mpr $ hf.def.mono (Ioc_subset_Ioc h1₁ h1₂) h2 lemma mono_set (hf : interval_integrable f μ a b) (h : interval c d ⊆ interval a b) : interval_integrable f μ c d := hf.mono h rfl.le lemma mono_measure (hf : interval_integrable f ν a b) (h : μ ≤ ν) : interval_integrable f μ a b := hf.mono rfl.subset h lemma mono_set_ae (hf : interval_integrable f μ a b) (h : Ioc (min c d) (max c d) ≤ᵐ[μ] Ioc (min a b) (max a b)) : interval_integrable f μ c d := interval_integrable_iff.mpr $ hf.def.mono_set_ae h protected lemma ae_measurable (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc a b)):= h.1.ae_measurable protected lemma ae_measurable' (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc b a)):= h.2.ae_measurable end variables [borel_space E] {f g : α → E} {a b : α} {μ : measure α} lemma smul [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) (r : 𝕜) : interval_integrable (r • f) μ a b := ⟨h.1.smul r, h.2.smul r⟩ @[simp] lemma add [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x + g x) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ @[simp] lemma sub [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x - g x) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ lemma mul_continuous_on {α : Type*} [conditionally_complete_linear_order α] [measurable_space α] [topological_space α] [order_topology α] [opens_measurable_space α] {μ : measure α} {a b : α} {f g : α → ℝ} (hf : interval_integrable f μ a b) (hg : continuous_on g (interval a b)) : interval_integrable (λ x, f x * g x) μ a b := begin rcases le_total a b with hab|hab, { rw interval_integrable_iff_integrable_Ioc_of_le hab at hf ⊢, apply hf.mul_continuous_on_of_subset hg measurable_set_Ioc is_compact_interval, rw interval_of_le hab, exact Ioc_subset_Icc_self }, { apply interval_integrable.symm, rw interval_integrable_iff_integrable_Ioc_of_le hab, have := (interval_integrable_iff_integrable_Ioc_of_le hab).1 hf.symm, apply this.mul_continuous_on_of_subset hg measurable_set_Ioc is_compact_interval, rw interval_of_ge hab, exact Ioc_subset_Icc_self }, end lemma continuous_on_mul {α : Type*} [conditionally_complete_linear_order α] [measurable_space α] [topological_space α] [order_topology α] [opens_measurable_space α] {μ : measure α} {a b : α} {f g : α → ℝ} (hf : interval_integrable f μ a b) (hg : continuous_on g (interval a b)) : interval_integrable (λ x, g x * f x) μ a b := by simpa [mul_comm] using hf.mul_continuous_on hg end interval_integrable section variables {μ : measure ℝ} [is_locally_finite_measure μ] lemma continuous_on.interval_integrable [borel_space E] {u : ℝ → E} {a b : ℝ} (hu : continuous_on u (interval a b)) : interval_integrable u μ a b := (continuous_on.integrable_on_Icc hu).interval_integrable lemma continuous_on.interval_integrable_of_Icc [borel_space E] {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : continuous_on u (Icc a b)) : interval_integrable u μ a b := continuous_on.interval_integrable ((interval_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure `ν` on ℝ. -/ lemma continuous.interval_integrable [borel_space E] {u : ℝ → E} (hu : continuous u) (a b : ℝ) : interval_integrable u μ a b := hu.continuous_on.interval_integrable end section variables {ι : Type*} [topological_space ι] [conditionally_complete_linear_order ι] [order_topology ι] [measurable_space ι] [borel_space ι] {μ : measure ι} [is_locally_finite_measure μ] [conditionally_complete_linear_order E] [order_topology E] [second_countable_topology E] [borel_space E] lemma monotone_on.interval_integrable {u : ι → E} {a b : ι} (hu : monotone_on u (interval a b)) : interval_integrable u μ a b := begin rw interval_integrable_iff, exact (monotone_on.integrable_on_compact is_compact_interval hu).mono_set Ioc_subset_Icc_self, end lemma antitone_on.interval_integrable {u : ι → E} {a b : ι} (hu : antitone_on u (interval a b)) : interval_integrable u μ a b := @monotone_on.interval_integrable (order_dual E) _ ‹_› ι _ _ _ _ _ _ _ _ _ ‹_› ‹_› u a b hu lemma monotone.interval_integrable {u : ι → E} {a b : ι} (hu : monotone u) : interval_integrable u μ a b := (hu.monotone_on _).interval_integrable lemma antitone.interval_integrable {u : ι → E} {a b : ι} (hu :antitone u) : interval_integrable u μ a b := (hu.antitone_on _).interval_integrable end /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable_ae {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := have _ := (hf.integrable_at_filter_ae hfm hμ).eventually, ((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := (hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv /-! ### Interval integral: definition and basic properties In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ` and prove some basic properties. -/ variables [second_countable_topology E] [complete_space E] [normed_space ℝ E] [borel_space E] /-- The interval integral `∫ x in a..b, f x ∂μ` is defined as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/ def interval_integral (f : α → E) (a b : α) (μ : measure α) := ∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r namespace interval_integral section basic variables {a b : α} {f g : α → E} {μ : measure α} @[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 := by simp [interval_integral] lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ := by simp [interval_integral, h] @[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 := sub_self _ lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [interval_integral, neg_sub] lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ := by simp only [integral_symm b, integral_of_le h] lemma integral_cases (f : α → E) (a b) : ∫ x in a..b, f x ∂μ ∈ ({∫ x in Ioc (min a b) (max a b), f x ∂μ, -∫ x in Ioc (min a b) (max a b), f x ∂μ} : set E) := (le_total a b).imp (λ h, by simp [h, integral_of_le]) (λ h, by simp [h, integral_of_ge]) lemma integral_undef (h : ¬ interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b with hab hab; simp only [integral_of_le, integral_of_ge, hab, neg_eq_zero]; refine integral_undef (not_imp_not.mpr integrable.integrable_on' _); simpa [hab] using not_and_distrib.mp h lemma integral_non_ae_measurable (hf : ¬ ae_measurable f (μ.restrict (Ioc (min a b) (max a b)))) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b; simpa [integral_of_le, integral_of_ge, h] using integral_non_ae_measurable hf lemma integral_non_ae_measurable_of_le (h : a ≤ b) (hf : ¬ ae_measurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := integral_non_ae_measurable $ by simpa [h] using hf lemma norm_integral_eq_norm_integral_Ioc : ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ := (integral_cases f a b).elim (congr_arg _) (λ h, (congr_arg _ h).trans (norm_neg _)) lemma norm_integral_le_integral_norm_Ioc : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ := calc ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ : norm_integral_eq_norm_integral_Ioc ... ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ : norm_integral_le_integral_norm f lemma norm_integral_le_abs_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ |∫ x in a..b, ∥f x∥ ∂μ| := begin simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc], exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _) end lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ioc (min a b) (max a b) → ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * |b - a| := begin rw [norm_integral_eq_norm_integral_Ioc], convert norm_set_integral_le_of_norm_le_const_ae'' _ measurable_set_Ioc h, { rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] }, { simp only [real.volume_Ioc, ennreal.of_real_lt_top] }, end lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E} (h : ∀ x ∈ Ioc (min a b) (max a b), ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * |b - a| := norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h @[simp] lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ := by { simp only [interval_integral, integral_add hf.1 hg.1, integral_add hf.2 hg.2], abel } @[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by { simp only [interval_integral, integral_neg], abel } @[simp] lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ := by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg) @[simp] lemma integral_smul {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] (r : 𝕜) (f : α → E) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, integral_smul, smul_sub] lemma integral_const' (c : E) : ∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c := by simp only [interval_integral, set_integral_const, sub_smul] @[simp] lemma integral_const {a b : ℝ} (c : E) : ∫ x in a..b, c = (b - a) • c := by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b, max_zero_sub_eq_self] lemma integral_smul_measure (c : ℝ≥0∞) : ∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub] variables [normed_group F] [second_countable_topology F] [complete_space F] [normed_space ℝ F] [measurable_space F] [borel_space F] lemma _root_.continuous_linear_map.interval_integral_comp_comm (L : E →L[ℝ] F) (hf : interval_integrable f μ a b) : ∫ x in a..b, L (f x) ∂μ = L (∫ x in a..b, f x ∂μ) := begin rw [interval_integral, interval_integral, L.integral_comp_comm, L.integral_comp_comm, L.map_sub], exacts [hf.2, hf.1] end end basic section comp variables {a b c d : ℝ} (f : ℝ → E) @[simp] lemma integral_comp_mul_right (hc : c ≠ 0) : ∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x := begin have A : closed_embedding (λ x, x * c) := (homeomorph.mul_right₀ c hc).closed_embedding, conv_rhs { rw [← real.smul_map_volume_mul_right hc] }, simp_rw [integral_smul_measure, interval_integral, set_integral_map_of_closed_embedding measurable_set_Ioc A, ennreal.to_real_of_real (abs_nonneg c)], cases lt_or_gt_of_ne hc, { simp [h, mul_div_cancel, hc, abs_of_neg, restrict_congr_set Ico_ae_eq_Ioc] }, { simp [(show 0 < c, from h), mul_div_cancel, hc, abs_of_pos] } end @[simp] lemma smul_integral_comp_mul_right (c) : c • ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_left (hc : c ≠ 0) : ∫ x in a..b, f (c * x) = c⁻¹ • ∫ x in c*a..c*b, f x := by simpa only [mul_comm c] using integral_comp_mul_right f hc @[simp] lemma smul_integral_comp_mul_left (c) : c • ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div (hc : c ≠ 0) : ∫ x in a..b, f (x / c) = c • ∫ x in a/c..b/c, f x := by simpa only [inv_inv₀] using integral_comp_mul_right f (inv_ne_zero hc) @[simp] lemma inv_smul_integral_comp_div (c) : c⁻¹ • ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_right (d) : ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x := have A : closed_embedding (λ x, x + d) := (homeomorph.add_right d).closed_embedding, calc ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x ∂(measure.map (λ x, x + d) volume) : by simp [interval_integral, set_integral_map_of_closed_embedding _ A] ... = ∫ x in a+d..b+d, f x : by rw [real.map_volume_add_right] @[simp] lemma integral_comp_add_left (d) : ∫ x in a..b, f (d + x) = ∫ x in d+a..d+b, f x := by simpa only [add_comm] using integral_comp_add_right f d @[simp] lemma integral_comp_mul_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x + d) = c⁻¹ • ∫ x in c*a+d..c*b+d, f x := by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_mul_add (c d) : c • ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + c * x) = c⁻¹ • ∫ x in d+c*a..d+c*b, f x := by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_add_mul (c d) : c • ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c + d) = c • ∫ x in a/c+d..b/c+d, f x := by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_mul_add f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_add (c d) : c⁻¹ • ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + x / c) = c • ∫ x in d+a/c..d+b/c, f x := by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_add_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_add_div (c d) : c⁻¹ • ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x - d) = c⁻¹ • ∫ x in c*a-d..c*b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d) @[simp] lemma smul_integral_comp_mul_sub (c d) : c • ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - c * x) = c⁻¹ • ∫ x in d-c*b..d-c*a, f x := begin simp only [sub_eq_add_neg, neg_mul_eq_neg_mul], rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm], simp only [inv_neg, smul_neg, neg_neg, neg_smul], end @[simp] lemma smul_integral_comp_sub_mul (c d) : c • ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c - d) = c • ∫ x in a/c-d..b/c-d, f x := by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_mul_sub f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_sub (c d) : c⁻¹ • ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - x / c) = c • ∫ x in d-b/c..d-a/c, f x := by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_sub_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_sub_div (c d) : c⁻¹ • ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_right (d) : ∫ x in a..b, f (x - d) = ∫ x in a-d..b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d) @[simp] lemma integral_comp_sub_left (d) : ∫ x in a..b, f (d - x) = ∫ x in d-b..d-a, f x := by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d @[simp] lemma integral_comp_neg : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x := by simpa only [zero_sub] using integral_comp_sub_left f 0 end comp /-! ### Integral is an additive function of the interval In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` as well as a few other identities trivially equivalent to this one. We also prove that `∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`. -/ section order_closed_topology variables [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b c d : α} {f g : α → E} {μ : measure α} lemma integrable_on_Icc_iff_integrable_on_Ioc' {E : Type*} [measurable_space E] [normed_group E] {f : α → E} {a b : α} (ha : μ {a} ≠ ⊤) : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ := begin cases le_or_lt a b with hab hab, { have : Icc a b = Icc a a ∪ Ioc a b := (Icc_union_Ioc_eq_Icc le_rfl hab).symm, rw [this, integrable_on_union], simp [lt_top_iff_ne_top.2 ha] }, { simp [hab, hab.le] }, end lemma integrable_on_Icc_iff_integrable_on_Ioc {E : Type*} [measurable_space E] [normed_group E] [has_no_atoms μ] {f : α → E} {a b : α} : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ := integrable_on_Icc_iff_integrable_on_Ioc' (by simp) lemma interval_integrable_iff_integrable_Icc_of_le {E : Type*} [measurable_space E] [normed_group E] {f : α → E} {a b : α} (hab : a ≤ b) {μ : measure α} [has_no_atoms μ] : interval_integrable f μ a b ↔ integrable_on f (Icc a b) μ := by rw [interval_integrable_iff_integrable_Ioc_of_le hab, integrable_on_Icc_iff_integrable_on_Ioc] lemma integral_Icc_eq_integral_Ioc' {f : α → E} {a b : α} (ha : μ {a} = 0) : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := begin cases le_or_lt a b with hab hab, { have : μ.restrict (Icc a b) = μ.restrict (Ioc a b), { rw [← Ioc_union_left hab, measure_theory.measure.restrict_union _ measurable_set_Ioc (measurable_set_singleton a)], { simp [measure_theory.measure.restrict_zero_set ha] }, { simp } }, rw this }, { simp [hab, hab.le] } end lemma integral_Icc_eq_integral_Ioc {f : α → E} {a b : α} [has_no_atoms μ] : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := integral_Icc_eq_integral_Ioc' $ measure_singleton a /-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/ lemma integral_congr {a b : α} (h : eq_on f g (interval a b)) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by cases le_total a b with hab hab; simpa [hab, integral_of_le, integral_of_ge] using set_integral_congr measurable_set_Ioc (h.mono Ioc_subset_Icc_self) lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 := begin have hac := hab.trans hbc, simp only [interval_integral, ← add_sub_comm, sub_eq_zero], iterate 4 { rw ← integral_union }, { suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this, rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle, min_left_comm, max_left_comm] }, all_goals { simp [*, measurable_set.union, measurable_set_Ioc, Ioc_disjoint_Ioc_same, Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] } end lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ := by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc] lemma sum_integral_adjacent_intervals {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : ∑ (k : ℕ) in finset.range n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ := begin induction n with n hn, { simp }, { rw [finset.sum_range_succ, hn (λ k hk, hint k (hk.trans n.lt_succ_self))], exact integral_add_adjacent_intervals (interval_integrable.trans_iterate $ λ k hk, hint k (hk.trans n.lt_succ_self)) (hint n n.lt_succ_self) } end lemma integral_interval_sub_left (hab : interval_integrable f μ a b) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ := sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab) lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ := by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm, integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm] lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ := by simp only [sub_eq_add_neg, ← integral_symm, integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)] lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ := by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c, sub_neg_eq_add, sub_eq_neg_add], } lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) : ∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ := begin wlog hab : a ≤ b using [a b] tactic.skip, { rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc (le_refl _)), Iic_union_Ioc_eq_Iic hab], exacts [measurable_set_Iic, measurable_set_Ioc, ha, hb.mono_set (λ _, and.right)] }, { intros ha hb, rw [integral_symm, ← this hb ha, neg_sub] } end /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ lemma integral_const_of_cdf [is_finite_measure μ] (c : E) : ∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c := begin simp only [sub_smul, ← set_integral_const], refine (integral_Iic_sub_Iic _ _).symm; simp only [integrable_on_const, measure_lt_top, or_true] end lemma integral_eq_integral_of_support_subset {f : α → E} {a b} (h : support f ⊆ Ioc a b) : ∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ := begin cases le_total a b with hab hab, { rw [integral_of_le hab, ← integral_indicator measurable_set_Ioc, indicator_eq_self.2 h]; apply_instance }, { rw [Ioc_eq_empty hab.not_lt, subset_empty_iff, support_eq_empty_iff] at h, simp [h] } end lemma integral_congr_ae' {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x) (h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) : ∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ := by simp only [interval_integral, set_integral_congr_ae (measurable_set_Ioc) h, set_integral_congr_ae (measurable_set_Ioc) h'] lemma integral_congr_ae {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) : ∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ := integral_congr_ae' (ae_interval_oc_iff.mp h).1 (ae_interval_oc_iff.mp h).2 lemma integral_zero_ae {f : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) : ∫ (x : α) in a..b, f x ∂μ = 0 := calc ∫ x in a..b, f x ∂μ = ∫ x in a..b, 0 ∂μ : integral_congr_ae h ... = 0 : integral_zero lemma integral_indicator {a₁ a₂ a₃ : α} (h : a₂ ∈ Icc a₁ a₃) {f : α → E} : ∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂ μ = ∫ x in a₁..a₂, f x ∂ μ := begin have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂, from Iic_inter_Ioc_of_le h.2, rw [integral_of_le h.1, integral_of_le (h.1.trans h.2), integral_indicator, measure.restrict_restrict, this], exact measurable_set_Iic, all_goals { apply measurable_set_Iic }, end end order_closed_topology section continuity_wrt_parameter open topological_space variables {X : Type*} [topological_space X] [first_countable_topology X] variables {μ : measure α} /-- Continuity of interval integral with respect to a parameter, at a point within a set. Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀` within `s` and at `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀` within `s`. If `(λ x, F x t)` is continuous at `x₀` within `s` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_within_at_of_dominated_interval {F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} {s : set X} (hF_meas : ∀ᶠ x in 𝓝[s] x₀, ae_measurable (F x) (μ.restrict $ Ι a b)) (hF_meas₀ : ae_measurable (F x₀) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_within_at (λ x, F x t) s x₀) : continuous_within_at (λ x, ∫ t in a..b, F x t ∂μ) s x₀ := begin cases bound_integrable, cases le_or_lt a b with hab hab; [{ rw interval_oc_of_le hab at *, simp_rw interval_integral.integral_of_le hab }, { rw interval_oc_of_lt hab at *, simp_rw interval_integral.integral_of_ge hab.le, refine tendsto.neg _ }]; apply tendsto_integral_filter_of_dominated_convergence bound hF_meas hF_meas₀ h_bound, exacts [bound_integrable_left, h_cont, bound_integrable_right, h_cont] end /-- Continuity of interval integral with respect to a parameter at a point. Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀`. If `(λ x, F x t)` is continuous at `x₀` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_at_of_dominated_interval {F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_at (λ x, F x t) x₀) : continuous_at (λ x, ∫ t in a..b, F x t ∂μ) x₀ := begin rw ← continuous_within_at_univ, apply continuous_within_at_of_dominated_interval ; try { rw nhds_within_univ}, exacts [hF_meas, (mem_of_mem_nhds hF_meas : _), h_bound, bound_integrable, h_cont.mono (λ a, (continuous_within_at_univ (λ x, F x a) x₀).mpr)] end /-- Continuity of interval integral with respect to a parameter. Given `F : X → α → E`, assume each `F x` is ae-measurable on `[a, b]`, and assume it is bounded by a function integrable on `[a, b]` independent of `x`. If `(λ x, F x t)` is continuous for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_of_dominated_interval {F : X → α → E} {bound : α → ℝ} {a b : α} (hF_meas : ∀ x, ae_measurable (F x) $ μ.restrict $ Ι a b) (h_bound : ∀ x, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous (λ x, F x t)) : continuous (λ x, ∫ t in a..b, F x t ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated_interval (eventually_of_forall hF_meas) (eventually_of_forall h_bound) bound_integrable $ h_cont.mono $ λ _, continuous.continuous_at) end continuity_wrt_parameter section continuous_primitive open topological_space variables [topological_space α] [order_topology α] [opens_measurable_space α] [first_countable_topology α] {a b : α} {μ : measure α} lemma continuous_within_at_primitive {f : α → E} {a b₀ b₁ b₂ : α} (hb₀ : μ {b₀} = 0) (h_int : interval_integrable f μ (min a b₁) (max a b₂)) : continuous_within_at (λ b, ∫ x in a .. b, f x ∂ μ) (Icc b₁ b₂) b₀ := begin by_cases h₀ : b₀ ∈ Icc b₁ b₂, { have h₁₂ : b₁ ≤ b₂ := h₀.1.trans h₀.2, have min₁₂ : min b₁ b₂ = b₁ := min_eq_left h₁₂, have h_int' : ∀ {x}, x ∈ Icc b₁ b₂ → interval_integrable f μ b₁ x, { rintros x ⟨h₁, h₂⟩, apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_right a b₁), h₁.trans (h₂.trans $ le_max_of_le_right $ le_max_right _ _)⟩ }, { exact ⟨min_le_of_left_le $ (min_le_right _ _).trans h₁, le_max_of_le_right $ h₂.trans $ le_max_right _ _⟩ } }, have : ∀ b ∈ Icc b₁ b₂, ∫ x in a..b, f x ∂μ = ∫ x in a..b₁, f x ∂μ + ∫ x in b₁..b, f x ∂μ, { rintros b ⟨h₁, h₂⟩, rw ← integral_add_adjacent_intervals _ (h_int' ⟨h₁, h₂⟩), apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_left a b₁), le_max_of_le_right (le_max_left _ _)⟩ }, { exact ⟨min_le_of_left_le (min_le_right _ _), le_max_of_le_right (h₁.trans $ h₂.trans (le_max_right a b₂))⟩ } }, apply continuous_within_at.congr _ this (this _ h₀), clear this, refine continuous_within_at_const.add _, have : (λ b, ∫ x in b₁..b, f x ∂μ) =ᶠ[𝓝[Icc b₁ b₂] b₀] λ b, ∫ x in b₁..b₂, indicator {x | x ≤ b} f x ∂ μ, { apply eventually_eq_of_mem self_mem_nhds_within, exact λ b b_in, (integral_indicator b_in).symm }, apply continuous_within_at.congr_of_eventually_eq _ this (integral_indicator h₀).symm, have : interval_integrable (λ x, ∥f x∥) μ b₁ b₂, from interval_integrable.norm (h_int' $ right_mem_Icc.mpr h₁₂), refine continuous_within_at_of_dominated_interval _ _ _ this _ ; clear this, { apply eventually.mono (self_mem_nhds_within), intros x hx, erw [ae_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' hx).1.ae_measurable }, { exact le_max_of_le_right hx.2 }, exacts [measurable_set_Iic, measurable_set_Iic] }, { erw [ae_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' h₀).1.ae_measurable }, { exact le_max_of_le_right h₀.2 }, exact measurable_set_Iic, exact measurable_set_Iic }, { refine eventually_of_forall (λ (x : α), eventually_of_forall (λ (t : α), _)), dsimp [indicator], split_ifs ; simp }, { have : ∀ᵐ t ∂μ.restrict (Ι b₁ b₂), t < b₀ ∨ b₀ < t, { apply ae_restrict_of_ae, apply eventually.mono (compl_mem_ae_iff.mpr hb₀), intros x hx, exact ne.lt_or_lt hx }, apply this.mono, rintros x₀ (hx₀ | hx₀), { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = f x₀, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Ioi_mem_nhds hx₀), intros x hx, simp [hx.le] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀.le] }, { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = 0, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Iio_mem_nhds hx₀), intros x hx, simp [hx] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀] } } }, { apply continuous_within_at_of_not_mem_closure, rwa [closure_Icc] } end lemma continuous_on_primitive {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Ioc a x, f t ∂ μ) (Icc a b) := begin by_cases h : a ≤ b, { have : ∀ x ∈ Icc a b, ∫ (t : α) in Ioc a x, f t ∂μ = ∫ (t : α) in a..x, f t ∂μ, { intros x x_in, simp_rw [← interval_oc_of_le h, integral_of_le x_in.1] }, rw continuous_on_congr this, intros x₀ hx₀, refine continuous_within_at_primitive (measure_singleton x₀) _, rw interval_integrable_iff, simp only [h, max_eq_right, min_eq_left], exact h_int.mono Ioc_subset_Icc_self le_rfl }, { rw Icc_eq_empty h, exact continuous_on_empty _ }, end lemma continuous_on_primitive_Icc {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Icc a x, f t ∂ μ) (Icc a b) := begin rw show (λ x, ∫ t in Icc a x, f t ∂μ) = λ x, ∫ t in Ioc a x, f t ∂μ, by { ext x, exact integral_Icc_eq_integral_Ioc }, exact continuous_on_primitive h_int end /-- Note: this assumes that `f` is `interval_integrable`, in contrast to some other lemmas here. -/ lemma continuous_on_primitive_interval' {f : α → E} {a b₁ b₂ : α} [has_no_atoms μ] (h_int : interval_integrable f μ b₁ b₂) (ha : a ∈ [b₁, b₂]) : continuous_on (λ b, ∫ x in a..b, f x ∂ μ) [b₁, b₂] := begin intros b₀ hb₀, refine continuous_within_at_primitive (measure_singleton _) _, rw [min_eq_right ha.1, max_eq_right ha.2], simpa [interval_integrable_iff] using h_int, end lemma continuous_on_primitive_interval {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (interval a b) μ) : continuous_on (λ x, ∫ t in a..x, f t ∂ μ) (interval a b) := continuous_on_primitive_interval' h_int.interval_integrable left_mem_interval lemma continuous_on_primitive_interval_left {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (interval a b) μ) : continuous_on (λ x, ∫ t in x..b, f t ∂ μ) (interval a b) := begin rw interval_swap a b at h_int ⊢, simp only [integral_symm b], exact (continuous_on_primitive_interval h_int).neg, end variables [no_bot_order α] [no_top_order α] [has_no_atoms μ] lemma continuous_primitive {f : α → E} (h_int : ∀ a b : α, interval_integrable f μ a b) (a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := begin rw continuous_iff_continuous_at, intro b₀, cases no_bot b₀ with b₁ hb₁, cases no_top b₀ with b₂ hb₂, apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₁ hb₂), exact continuous_within_at_primitive (measure_singleton b₀) (h_int _ _) end lemma _root_.measure_theory.integrable.continuous_primitive {f : α → E} (h_int : integrable f μ) (a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := continuous_primitive (λ _ _, h_int.interval_integrable) a end continuous_primitive section variables {f g : α → ℝ} {a b : α} {μ : measure α} lemma integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b)] 0 := by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1] lemma integral_eq_zero_iff_of_nonneg_ae (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 := begin cases le_total a b with hab hab; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi }, { rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] } end lemma integral_pos_iff_support_of_nonneg_ae' (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := begin obtain hab | hab := le_total b a; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { rw [←not_iff_not, not_and_distrib, not_lt, not_lt, integral_of_ge hab, neg_nonpos], exact iff_of_true (integral_nonneg_of_ae hf) (or.intro_left _ hab) }, rw [integral_of_le hab, set_integral_pos_iff_support_of_nonneg_ae hf hfi.1, iff.comm, and_iff_right_iff_imp], contrapose!, intro h, rw [Ioc_eq_empty h.not_lt, inter_empty, measure_empty], exact le_refl 0, end lemma integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi variable (hab : a ≤ b) include hab lemma integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf in by simpa only [integral_of_le hab] using set_integral_nonneg_of_ae_restrict H lemma integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ ae_restrict_of_ae hf lemma integral_nonneg_of_forall (hf : ∀ u, 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae hab $ eventually_of_forall hf lemma integral_nonneg [topological_space α] [opens_measurable_space α] [order_closed_topology α] (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ (ae_restrict_iff' measurable_set_Icc).mpr $ ae_of_all μ hf lemma norm_integral_le_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in a..b, ∥f x∥ ∂μ := norm_integral_le_abs_integral_norm.trans_eq $ abs_of_nonneg $ integral_nonneg_of_forall hab $ λ x, norm_nonneg _ lemma abs_integral_le_integral_abs : |∫ x in a..b, f x ∂μ| ≤ ∫ x in a..b, |f x| ∂μ := norm_integral_le_integral_norm hab section mono variables (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) include hf hg lemma integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := h.filter_mono $ ae_mono $ measure.restrict_mono Ioc_subset_Icc_self $ le_refl μ in by simpa only [integral_of_le hab] using set_integral_mono_ae_restrict hf.1 hg.1 H lemma integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := by simpa only [integral_of_le hab] using set_integral_mono_ae hf.1 hg.1 h lemma integral_mono_on [topological_space α] [opens_measurable_space α] [order_closed_topology α] (h : ∀ x ∈ Icc a b, f x ≤ g x) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := λ x hx, h x $ Ioc_subset_Icc_self hx in by simpa only [integral_of_le hab] using set_integral_mono_on hf.1 hg.1 measurable_set_Ioc H lemma integral_mono (h : f ≤ g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := integral_mono_ae hab hf hg $ ae_of_all _ h end mono end /-! ### Fundamental theorem of calculus, part 1, for any measure In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by `FTC_filter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar cases. Lean can automatically find both `a` and `l'` based on `l`. The most general theorem `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` can be seen as a generalization of lemma `integral_has_strict_fderiv_at` below which states strict differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three directions: first, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` deals with any locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes only that `f` has finite limits almost surely at `a` and `b`. Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This theorem is formulated with integral of constants instead of measures in the right hand sides for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is possible to write better `simp` lemmas for these integrals, see `integral_const` and `integral_const_of_cdf`. In the next subsection we apply this theorem to prove various theorems about differentiability of the integral w.r.t. Lebesgue measure. -/ /-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. -/ class FTC_filter {β : Type*} [linear_order β] [measurable_space β] [topological_space β] (a : out_param β) (outer : filter β) (inner : out_param $ filter β) extends tendsto_Ixx_class Ioc outer inner : Prop := (pure_le : pure a ≤ outer) (le_nhds : inner ≤ 𝓝 a) [meas_gen : is_measurably_generated inner] /- The `dangerous_instance` linter doesn't take `out_param`s into account, so it thinks that `FTC_filter.to_tendsto_Ixx_class` is dangerous. Disable this linter using `nolint`. -/ attribute [nolint dangerous_instance] FTC_filter.to_tendsto_Ixx_class namespace FTC_filter variables [linear_order β] [measurable_space β] [topological_space β] instance pure (a : β) : FTC_filter a (pure a) ⊥ := { pure_le := le_refl _, le_nhds := bot_le } instance nhds_within_singleton (a : β) : FTC_filter a (𝓝[{a}] a) ⊥ := by { rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)], apply_instance } lemma finite_at_inner {a : β} (l : filter β) {l'} [h : FTC_filter a l l'] {μ : measure β} [is_locally_finite_measure μ] : μ.finite_at_filter l' := (μ.finite_at_nhds a).filter_mono h.le_nhds variables [opens_measurable_space β] [order_topology β] instance nhds (a : β) : FTC_filter a (𝓝 a) (𝓝 a) := { pure_le := pure_le_nhds a, le_nhds := le_refl _ } instance nhds_univ (a : β) : FTC_filter a (𝓝[univ] a) (𝓝 a) := by { rw nhds_within_univ, apply_instance } instance nhds_left (a : β) : FTC_filter a (𝓝[Iic a] a) (𝓝[Iic a] a) := { pure_le := pure_le_nhds_within right_mem_Iic, le_nhds := inf_le_left } instance nhds_right (a : β) : FTC_filter a (𝓝[Ici a] a) (𝓝[Ioi a] a) := { pure_le := pure_le_nhds_within left_mem_Ici, le_nhds := inf_le_left } instance nhds_Icc {x a b : β} [h : fact (x ∈ Icc a b)] : FTC_filter x (𝓝[Icc a b] x) (𝓝[Icc a b] x) := { pure_le := pure_le_nhds_within h.out, le_nhds := inf_le_left } instance nhds_interval {x a b : β} [h : fact (x ∈ [a, b])] : FTC_filter x (𝓝[[a, b]] x) (𝓝[[a, b]] x) := by { haveI : fact (x ∈ set.Icc (min a b) (max a b)) := h, exact FTC_filter.nhds_Icc } end FTC_filter open asymptotics section variables {f : α → E} {a b : α} {c ca cb : E} {l l' la la' lb lb' : filter α} {lt : filter β} {μ : measure α} {u v ua va ub vb : β → α} /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, where `μ` is a measure finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := begin have A := hf.integral_sub_linear_is_o_ae hfm hl (hu.Ioc hv), have B := hf.integral_sub_linear_is_o_ae hfm hl (hv.Ioc hu), simp only [integral_const'], convert (A.trans_le _).sub (B.trans_le _), { ext t, simp_rw [interval_integral, sub_smul], abel }, all_goals { intro t, cases le_total (u t) (v t) with huv huv; simp [huv] } end /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l` so that `u ≤ v`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf hl hu hv).congr' (huv.mono $ λ x hx, by simp [integral_const', hx]) (huv.mono $ λ x hx, by simp [integral_const', hx]) /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l` so that `v ≤ u`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left $ λ t, by simp [integral_symm (u t), add_comm] variables [topological_space α] section variables [is_locally_finite_measure μ] [FTC_filter a l l'] include a local attribute [instance] FTC_filter.meas_gen /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae'` for a version that also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf (FTC_filter.finite_at_inner l) hu hv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf (FTC_filter.finite_at_inner l) hu hv huv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' hfm hf (FTC_filter.finite_at_inner l) hu hv huv end variables [order_topology α] [borel_space α] local attribute [instance] FTC_filter.meas_gen variables [FTC_filter a la la'] [FTC_filter b lb lb'] [is_locally_finite_measure μ] /-- Fundamental theorem of calculus-1, strict derivative in both limits for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f μ a b) (hmeas_a : measurable_at_filter f la' μ) (hmeas_b : measurable_at_filter f lb' μ) (ha_lim : tendsto f (la' ⊓ μ.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ μ.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x ∂μ) - (∫ x in ua t..ub t, f x ∂μ) - (∫ x in ub t..vb t, cb ∂μ - ∫ x in ua t..va t, ca ∂μ)) (λ t, ∥∫ x in ua t..va t, (1:ℝ) ∂μ∥ + ∥∫ x in ub t..vb t, (1:ℝ) ∂μ∥) lt := begin refine ((measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add (measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr' _ eventually_eq.rfl, have A : ∀ᶠ t in lt, interval_integrable f μ (ua t) (va t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) hua hva, have A' : ∀ᶠ t in lt, interval_integrable f μ a (ua t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) (tendsto_const_pure.mono_right FTC_filter.pure_le) hua, have B : ∀ᶠ t in lt, interval_integrable f μ (ub t) (vb t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) hub hvb, have B' : ∀ᶠ t in lt, interval_integrable f μ b (ub t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) (tendsto_const_pure.mono_right FTC_filter.pure_le) hub, filter_upwards [A, A', B, B'], intros t ua_va a_ua ub_vb b_ub, rw [← integral_interval_sub_interval_comm'], { dsimp only [], abel }, exacts [ub_vb, ua_va, b_ub.symm.trans $ hab.symm.trans a_ua] end /-- Fundamental theorem of calculus-1, strict derivative in right endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ μ.ae`. Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f lb' μ) (hf : tendsto f (lb' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, ∫ x in a..v t, f x ∂μ - ∫ x in a..u t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab measurable_at_bot hmeas ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hf (tendsto_const_pure : tendsto _ _ (pure a)) tendsto_const_pure hu hv /-- Fundamental theorem of calculus-1, strict derivative in left endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ μ.ae`. Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `la`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f la' μ) (hf : tendsto f (la' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, ∫ x in v t..b, f x ∂μ - ∫ x in u t..b, f x ∂μ + ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas measurable_at_bot hf ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hu hv (tendsto_const_pure : tendsto _ _ (pure b)) tendsto_const_pure end /-! ### Fundamental theorem of calculus-1 for Lebesgue measure In this section we restate theorems from the previous section for Lebesgue measure. In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)` at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`. -/ variables {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter β} {a b z : ℝ} {u v ua ub va vb : β → ℝ} [FTC_filter a la la'] [FTC_filter b lb lb'] /-! #### Auxiliary `is_o` statements In this section we prove several lemmas that can be interpreted as strict differentiability of `(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `is_o` because we have no definition of `has_strict_(f)deriv_at_filter` in the library. -/ /-- Fundamental theorem of calculus-1, local version. If `f` has a finite limit `c` almost surely at `l'`, where `(l, l')` is an `FTC_filter` pair around `a`, then `∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/ lemma integral_sub_linear_is_o_of_tendsto_ae [FTC_filter a l l'] (hfm : measurable_at_filter f l') (hf : tendsto f (l' ⊓ volume.ae) (𝓝 c)) {u v : β → ℝ} (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, (∫ x in u t..v t, f x) - (v t - u t) • c) (v - u) lt := by simpa [integral_const] using measure_integral_sub_linear_is_o_of_tendsto_ae hfm hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca + o(∥va - ua∥ + ∥vb - ub∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This lemma could've been formulated using `has_strict_fderiv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la') (hmeas_b : measurable_at_filter f lb') (ha_lim : tendsto f (la' ⊓ volume.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ volume.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x) - (∫ x in ua t..ub t, f x) - ((vb t - ub t) • cb - (va t - ua t) • ca)) (λ t, ∥va t - ua t∥ + ∥vb t - ub t∥) lt := by simpa [integral_const] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas_a hmeas_b ha_lim hb_lim hua hva hub hvb /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then `(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `lb`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f lb') (hf : tendsto f (lb' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, (∫ x in a..v t, f x) - (∫ x in a..u t, f x) - (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hab hmeas hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `f` has a finite limit `c` almost surely at `la'`, then `(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `la`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f la') (hf : tendsto f (la' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, (∫ x in v t..b, f x) - (∫ x in u t..b, f x) + (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left hab hmeas hf hu hv open continuous_linear_map (fst snd smul_right sub_apply smul_right_apply coe_fst' coe_snd' map_sub) /-! #### Strict differentiability In this section we prove that for a measurable function `f` integrable on `a..b`, * `integral_has_strict_fderiv_at_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`, respectively; * `integral_has_strict_fderiv_at`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability provided that `f` is continuous at `a` and `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `b`; * `integral_has_strict_deriv_at_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability provided that `f` is continuous at `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `a`; * `integral_has_strict_deriv_at_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability provided that `f` is continuous at `a`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := begin have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb ((continuous_fst.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_fst.comp continuous_fst).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_fst).tendsto ((a, b), (a, b))), refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- **First Fundamental Theorem of Calculus**: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) c b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb continuous_at_snd continuous_at_fst /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_of_tendsto_ae_right hf.symm hmeas ha).neg /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_right hf.symm hmeas ha).neg /-! #### Fréchet differentiability In this subsection we restate results from the previous subsection in terms of `has_fderiv_at`, `has_deriv_at`, `fderiv`, and `deriv`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := (integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := (integral_has_strict_fderiv_at hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca := (integral_has_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a) := (integral_has_fderiv_at hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/ lemma integral_has_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in a..u, f x) c b := (integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/ lemma integral_has_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := (integral_has_strict_deriv_at_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in a..u, f x) b = c := (integral_has_deriv_at_of_tendsto_ae_right hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_integral_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : deriv (λ u, ∫ x in a..u, f x) b = f b := (integral_has_deriv_at_right hf hmeas hb).deriv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/ lemma integral_has_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := (integral_has_strict_deriv_at_of_tendsto_ae_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/ lemma integral_has_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := (integral_has_strict_deriv_at_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in u..b, f x) a = -c := (integral_has_deriv_at_of_tendsto_ae_left hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_integral_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : continuous_at f a) : deriv (λ u, ∫ x in u..b, f x) a = -f a := (integral_has_deriv_at_left hf hmeas hb).deriv /-! #### One-sided derivatives -/ /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at_of_tendsto_ae (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (s.prod t) (a, b) := begin rw [has_fderiv_within_at, nhds_within_prod_eq], have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[s] a)) tendsto_fst (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[t] b)) tendsto_snd, refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption is definitionally equal `continuous_at f _` or `continuous_within_at f _ _`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f la (𝓝 $ f a)) (hb : tendsto f lb (𝓝 $ f b)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (s.prod t) (a, b) := integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- An auxiliary tactic closing goals `unique_diff_within_at ℝ s a` where `s ∈ {Iic a, Ici a, univ}`. -/ meta def unique_diff_within_at_Ici_Iic_univ : tactic unit := `[apply_rules [unique_diff_on.unique_diff_within_at, unique_diff_on_Ici, unique_diff_on_Iic, left_mem_Ici, right_mem_Iic, unique_diff_within_at_univ]] /-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}` and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the table below. Then `fderiv_within ℝ (λ p, ∫ x in p.1..p.2, f x) (s.prod t)` is equal to `(u, v) ↦ u • cb - v • ca`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma fderiv_within_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) (ht : unique_diff_within_at ℝ t b . unique_diff_within_at_Ici_Iic_univ) : fderiv_within ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (s.prod t) (a, b) = ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) := (integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv_within $ hs.prod ht /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in a..u, f x) c s b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb (tendsto_const_pure.mono_right FTC_filter.pure_le) tendsto_id /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right) derivative `f b` at `b`. -/ lemma integral_has_deriv_within_at_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) : has_deriv_within_at (λ u, ∫ x in a..u, f x) (f b) s b := integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_within_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas: measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = c := (integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `b`, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_within_integral_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = f b := (integral_has_deriv_within_at_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-c) s a := by { simp only [integral_symm b], exact (integral_has_deriv_within_at_of_tendsto_ae_right hf.symm hmeas ha).neg } /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right) derivative `-f a` at `a`. -/ lemma integral_has_deriv_within_at_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-f a) s a := integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_within_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -c := (integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas ha).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `a`, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_within_integral_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -f a := (integral_has_deriv_within_at_left hf hmeas ha).deriv_within hs /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiable_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : differentiable_on ℝ (λ u, ∫ x in a..u, f x) s := λ y hy, (integral_has_deriv_at_right (hintg y hy) hcont.measurable.ae_measurable.measurable_at_filter hcont.continuous_at) .differentiable_at.differentiable_within_at /-! ### Fundamental theorem of calculus, part 2 This section contains theorems pertaining to FTC-2 for interval integrals, i.e., the assertion that `∫ x in a..b, f' x = f b - f a` under suitable assumptions. The most classical version of this theorem assumes that `f'` is continuous. However, this is unnecessarily strong: the result holds if `f'` is just integrable. We prove the strong version, following [Rudin, *Real and Complex Analysis* (Theorem 7.21)][rudin2006real]. The proof is first given for real-valued functions, and then deduced for functions with a general target space. For a real-valued function `g`, it suffices to show that `g b - g a ≤ (∫ x in a..b, g' x) + ε` for all positive `ε`. To prove this, choose a lower-semicontinuous function `G'` with `g' < G'` and with integral close to that of `g'` (its existence is guaranteed by the Vitali-Carathéodory theorem). It satisfies `g t - g a ≤ ∫ x in a..t, G' x` for all `t ∈ [a, b]`: this inequality holds at `a`, and if it holds at `t` then it holds for `u` close to `t` on its right, as the left hand side increases by `g u - g t ∼ (u -t) g' t`, while the right hand side increases by `∫ x in t..u, G' x` which is roughly at least `∫ x in t..u, G' t = (u - t) G' t`, by lower semicontinuity. As `g' t < G' t`, this gives the conclusion. One can therefore push progressively this inequality to the right until the point `b`, where it gives the desired conclusion. -/ variables {g' g : ℝ → ℝ} /-- Hard part of FTC-2 for integrable derivatives, real-valued functions: one has `g b - g a ≤ ∫ y in a..b, g' y`. Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`. -/ lemma sub_le_integral_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : g b - g a ≤ ∫ y in a..b, g' y := begin refine le_of_forall_pos_le_add (λ ε εpos, _), -- Bound from above `g'` by a lower-semicontinuous function `G'`. rcases exists_lt_lower_semicontinuous_integral_lt g' g'int εpos with ⟨G', g'_lt_G', G'cont, G'int, G'lt_top, hG'⟩, -- we will show by "induction" that `g t - g a ≤ ∫ u in a..t, G' u` for all `t ∈ [a, b]`. set s := {t | g t - g a ≤ ∫ u in a..t, (G' u).to_real} ∩ Icc a b, -- the set `s` of points where this property holds is closed. have s_closed : is_closed s, { have : continuous_on (λ t, (g t - g a, ∫ u in a..t, (G' u).to_real)) (Icc a b), { rw ← interval_of_le hab at G'int ⊢ hcont, exact (hcont.sub continuous_on_const).prod (continuous_on_primitive_interval G'int) }, simp only [s, inter_comm], exact this.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, have main : Icc a b ⊆ {t | g t - g a ≤ ∫ u in a..t, (G' u).to_real }, { -- to show that the set `s` is all `[a, b]`, it suffices to show that any point `t` in `s` -- with `t < b` admits another point in `s` slightly to its right -- (this is a sort of real induction). apply s_closed.Icc_subset_of_forall_exists_gt (by simp only [integral_same, mem_set_of_eq, sub_self]) (λ t ht v t_lt_v, _), obtain ⟨y, g'_lt_y', y_lt_G'⟩ : ∃ (y : ℝ), (g' t : ereal) < y ∧ (y : ereal) < G' t := ereal.lt_iff_exists_real_btwn.1 (g'_lt_G' t), -- bound from below the increase of `∫ x in a..u, G' x` on the right of `t`, using the lower -- semicontinuity of `G'`. have I1 : ∀ᶠ u in 𝓝[Ioi t] t, (u - t) * y ≤ ∫ w in t..u, (G' w).to_real, { have B : ∀ᶠ u in 𝓝 t, (y : ereal) < G' u := G'cont.lower_semicontinuous_at _ _ y_lt_G', rcases mem_nhds_iff_exists_Ioo_subset.1 B with ⟨m, M, ⟨hm, hM⟩, H⟩, have : Ioo t (min M b) ∈ 𝓝[Ioi t] t := mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨min M b, by simp only [hM, ht.right.right, lt_min_iff, mem_Ioi, and_self], subset.refl _⟩, filter_upwards [this], assume u hu, have I : Icc t u ⊆ Icc a b := Icc_subset_Icc ht.2.1 (hu.2.le.trans (min_le_right _ _)), calc (u - t) * y = ∫ v in Icc t u, y : by simp only [hu.left.le, measure_theory.integral_const, algebra.id.smul_eq_mul, sub_nonneg, measurable_set.univ, real.volume_Icc, measure.restrict_apply, univ_inter, ennreal.to_real_of_real] ... ≤ ∫ w in t..u, (G' w).to_real : begin rw [interval_integral.integral_of_le hu.1.le, ← integral_Icc_eq_integral_Ioc], apply set_integral_mono_ae_restrict, { simp only [integrable_on_const, real.volume_Icc, ennreal.of_real_lt_top, or_true] }, { exact integrable_on.mono_set G'int I }, { have C1 : ∀ᵐ (x : ℝ) ∂volume.restrict (Icc t u), G' x < ⊤ := ae_mono (measure.restrict_mono I (le_refl _)) G'lt_top, have C2 : ∀ᵐ (x : ℝ) ∂volume.restrict (Icc t u), x ∈ Icc t u := ae_restrict_mem measurable_set_Icc, filter_upwards [C1, C2], assume x G'x hx, apply ereal.coe_le_coe_iff.1, have : x ∈ Ioo m M, by simp only [hm.trans_le hx.left, (hx.right.trans_lt hu.right).trans_le (min_le_left M b), mem_Ioo, and_self], convert le_of_lt (H this), exact ereal.coe_to_real G'x.ne (ne_bot_of_gt (g'_lt_G' x)) } end }, -- bound from above the increase of `g u - g a` on the right of `t`, using the derivative at `t` have I2 : ∀ᶠ u in 𝓝[Ioi t] t, g u - g t ≤ (u - t) * y, { have g'_lt_y : g' t < y := ereal.coe_lt_coe_iff.1 g'_lt_y', filter_upwards [(hderiv t ⟨ht.2.1, ht.2.2⟩).limsup_slope_le' (not_mem_Ioi.2 le_rfl) g'_lt_y, self_mem_nhds_within], assume u hu t_lt_u, have := hu.le, rwa [← div_eq_inv_mul, div_le_iff'] at this, exact sub_pos.2 t_lt_u }, -- combine the previous two bounds to show that `g u - g a` increases less quickly than -- `∫ x in a..u, G' x`. have I3 : ∀ᶠ u in 𝓝[Ioi t] t, g u - g t ≤ ∫ w in t..u, (G' w).to_real, { filter_upwards [I1, I2], assume u hu1 hu2, exact hu2.trans hu1 }, have I4 : ∀ᶠ u in 𝓝[Ioi t] t, u ∈ Ioc t (min v b), { refine mem_nhds_within_Ioi_iff_exists_Ioc_subset.2 ⟨min v b, _, subset.refl _⟩, simp only [lt_min_iff, mem_Ioi], exact ⟨t_lt_v, ht.2.2⟩ }, -- choose a point `x` slightly to the right of `t` which satisfies the above bound rcases (I3.and I4).exists with ⟨x, hx, h'x⟩, -- we check that it belongs to `s`, essentially by construction refine ⟨x, _, Ioc_subset_Ioc (le_refl _) (min_le_left _ _) h'x⟩, calc g x - g a = (g t - g a) + (g x - g t) : by abel ... ≤ (∫ w in a..t, (G' w).to_real) + ∫ w in t..x, (G' w).to_real : add_le_add ht.1 hx ... = ∫ w in a..x, (G' w).to_real : begin apply integral_add_adjacent_intervals, { rw interval_integrable_iff_integrable_Ioc_of_le ht.2.1, exact integrable_on.mono_set G'int (Ioc_subset_Icc_self.trans (Icc_subset_Icc le_rfl ht.2.2.le)) }, { rw interval_integrable_iff_integrable_Ioc_of_le h'x.1.le, apply integrable_on.mono_set G'int, refine Ioc_subset_Icc_self.trans (Icc_subset_Icc ht.2.1 (h'x.2.trans (min_le_right _ _))) } end }, -- now that we know that `s` contains `[a, b]`, we get the desired result by applying this to `b`. calc g b - g a ≤ ∫ y in a..b, (G' y).to_real : main (right_mem_Icc.2 hab) ... ≤ (∫ y in a..b, g' y) + ε : begin convert hG'.le; { rw interval_integral.integral_of_le hab, simp only [integral_Icc_eq_integral_Ioc', real.volume_singleton] }, end end /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`. -/ lemma integral_le_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y ≤ g b - g a := begin rw ← neg_le_neg_iff, convert sub_le_integral_of_has_deriv_right_of_le hab hcont.neg (λ x hx, (hderiv x hx).neg) g'int.neg, { abel }, { simp only [integral_neg] } end /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`: real version -/ lemma integral_eq_sub_of_has_deriv_right_of_le_real (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y = g b - g a := le_antisymm (integral_le_sub_of_has_deriv_right_of_le hab hcont hderiv g'int) (sub_le_integral_of_has_deriv_right_of_le hab hcont hderiv g'int) /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`: real version, not requiring differentiability as the left endpoint of the interval. Follows from `integral_eq_sub_of_has_deriv_right_of_le_real` together with a continuity argument. -/ lemma integral_eq_sub_of_has_deriv_right_of_le_real' (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y = g b - g a := begin obtain rfl|a_lt_b := hab.eq_or_lt, { simp }, set s := {t | ∫ u in t..b, g' u = g b - g t} ∩ Icc a b, have s_closed : is_closed s, { have : continuous_on (λ t, (∫ u in t..b, g' u, g b - g t)) (Icc a b), { rw ← interval_of_le hab at ⊢ hcont g'int, exact (continuous_on_primitive_interval_left g'int).prod (continuous_on_const.sub hcont) }, simp only [s, inter_comm], exact this.preimage_closed_of_closed is_closed_Icc is_closed_diagonal, }, have A : closure (Ioc a b) ⊆ s, { apply s_closed.closure_subset_iff.2, assume t ht, refine ⟨_, ⟨ht.1.le, ht.2⟩⟩, exact integral_eq_sub_of_has_deriv_right_of_le_real ht.2 (hcont.mono (Icc_subset_Icc ht.1.le (le_refl _))) (λ x hx, hderiv x ⟨ht.1.trans_le hx.1, hx.2⟩) (g'int.mono_set (Icc_subset_Icc ht.1.le (le_refl _))) }, rw closure_Ioc a_lt_b at A, exact (A (left_mem_Icc.2 hab)).1, end variable {f' : ℝ → E} /-- **Fundamental theorem of calculus-2**: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a right derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_within_at f (f' x) (Ioi x) x) (f'int : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := begin refine (normed_space.eq_iff_forall_dual_eq ℝ).2 (λ g, _), rw [← g.interval_integral_comp_comm f'int, g.map_sub], exact integral_eq_sub_of_has_deriv_right_of_le_real' hab (g.continuous.comp_continuous_on hcont) (λ x hx, g.has_fderiv_at.comp_has_deriv_within_at x (hderiv x hx)) (g.integrable_comp ((interval_integrable_iff_integrable_Icc_of_le hab).1 f'int)) end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is integrable on `[a, b]` then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := begin cases le_total a b with hab hab, { simp only [interval_of_le, min_eq_left, max_eq_right, hab] at hcont hderiv hint, apply integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hint }, { simp only [interval_of_ge, min_eq_right, max_eq_left, hab] at hcont hderiv, rw [integral_symm, integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hint.symm, neg_sub] } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_right_of_le hab hcont (λ x hx, (hderiv x hx).has_deriv_within_at) hint /-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in `[a, b]` and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at (hderiv : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_right (has_deriv_at.continuous_on hderiv) (λ x hx, (hderiv _ (mem_Icc_of_Ioo hx)).has_deriv_within_at) hint theorem integral_eq_sub_of_has_deriv_at_of_tendsto (hab : a < b) {fa fb} (hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) (ha : tendsto f (𝓝[Ioi a] a) (𝓝 fa)) (hb : tendsto f (𝓝[Iio b] b) (𝓝 fb)) : ∫ y in a..b, f' y = fb - fa := begin set F : ℝ → E := update (update f a fa) b fb, have Fderiv : ∀ x ∈ Ioo a b, has_deriv_at F (f' x) x, { refine λ x hx, (hderiv x hx).congr_of_eventually_eq _, filter_upwards [Ioo_mem_nhds hx.1 hx.2], intros y hy, simp only [F], rw [update_noteq hy.2.ne, update_noteq hy.1.ne'] }, have hcont : continuous_on F (Icc a b), { rw [continuous_on_update_iff, continuous_on_update_iff, Icc_diff_right, Ico_diff_left], refine ⟨⟨λ z hz, (hderiv z hz).continuous_at.continuous_within_at, _⟩, _⟩, { exact λ _, ha.mono_left (nhds_within_mono _ Ioo_subset_Ioi_self) }, { rintro -, refine (hb.congr' _).mono_left (nhds_within_mono _ Ico_subset_Iio_self), filter_upwards [Ioo_mem_nhds_within_Iio (right_mem_Ioc.2 hab)], exact λ z hz, (update_noteq hz.1.ne' _ _).symm } }, simpa [F, hab.ne, hab.ne'] using integral_eq_sub_of_has_deriv_at_of_le hab.le hcont Fderiv hint end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and its derivative is integrable on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hint : interval_integrable (deriv f) volume a b) : ∫ y in a..b, deriv f y = f b - f a := integral_eq_sub_of_has_deriv_at (λ x hx, (hderiv x hx).has_deriv_at) hint theorem integral_deriv_eq_sub' (f) (hderiv : deriv f = f') (hdiff : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin rw [← hderiv, integral_deriv_eq_sub hdiff], rw hderiv, exact hcont.interval_integrable end /-! ### Integration by parts -/ theorem integral_deriv_mul_eq_sub {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hu' : interval_integrable u' volume a b) (hv' : interval_integrable v' volume a b) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := integral_eq_sub_of_has_deriv_at (λ x hx, (hu x hx).mul (hv x hx)) $ (hu'.mul_continuous_on (has_deriv_at.continuous_on hv)).add (hv'.continuous_on_mul ((has_deriv_at.continuous_on hu))) theorem integral_mul_deriv_eq_deriv_mul {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hu' : interval_integrable u' volume a b) (hv' : interval_integrable v' volume a b) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, v x * u' x := begin rw [← integral_deriv_mul_eq_sub hu hv hu' hv', ← integral_sub], { exact integral_congr (λ x hx, by simp only [mul_comm, add_sub_cancel']) }, { exact ((hu'.mul_continuous_on (has_deriv_at.continuous_on hv)).add (hv'.continuous_on_mul (has_deriv_at.continuous_on hu))) }, { exact hu'.continuous_on_mul (has_deriv_at.continuous_on hv) }, end /-! ### Integration by substitution / Change of variables -/ section smul /-- Change of variables, general form. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. We could potentially slightly weaken the conditions, by not requiring that `f'` and `g` are continuous on the endpoints of these intervals, but in that case we need to additionally assume that the functions are integrable on that interval. -/ theorem integral_comp_smul_deriv'' {f f' : ℝ → ℝ} {g : ℝ → E} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, f' x • (g ∘ f) x= ∫ u in f a..f b, g u := begin have h_cont : continuous_on (λ u, ∫ t in f a..f u, g t) [a, b], { rw [hf.image_interval] at hg, refine (continuous_on_primitive_interval' hg.interval_integrable _).comp hf _, { rw [← hf.image_interval], exact mem_image_of_mem f left_mem_interval }, { rw [← image_subset_iff], exact hf.image_interval.subset } }, have h_der : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at (λ u, ∫ t in f a..f u, g t) (f' x • ((g ∘ f) x)) (Ioi x) x, { intros x hx, let I := [Inf (f '' [a, b]), Sup (f '' [a, b])], have hI : f '' [a, b] = I := hf.image_interval, have h2x : f x ∈ I, { rw [← hI], exact mem_image_of_mem f (Ioo_subset_Icc_self hx) }, have h2g : interval_integrable g volume (f a) (f x), { refine (hg.mono $ _).interval_integrable, exact hf.surj_on_interval left_mem_interval (Ioo_subset_Icc_self hx) }, rw [hI] at hg, have h3g : measurable_at_filter g (𝓝[I] f x) volume := hg.measurable_at_filter_nhds_within measurable_set_Icc (f x), haveI : fact (f x ∈ I) := ⟨h2x⟩, have : has_deriv_within_at (λ u, ∫ x in f a..u, g x) (g (f x)) I (f x) := integral_has_deriv_within_at_right h2g h3g (hg (f x) h2x), refine (this.scomp x ((hff' x hx).Ioo_of_Ioi hx.2) _).Ioi_of_Ioo hx.2, dsimp only [I], rw [← image_subset_iff, ← hf.image_interval], refine image_subset f (Ioo_subset_Icc_self.trans $ Icc_subset_Icc_left hx.1.le) }, have h_int : interval_integrable (λ (x : ℝ), f' x • (g ∘ f) x) volume a b := (hf'.smul (hg.comp hf $ subset_preimage_image f _)).interval_integrable, simp_rw [integral_eq_sub_of_has_deriv_right h_cont h_der h_int, integral_same, sub_zero], end /-- Change of variables. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. Compared to `interval_integral.integral_comp_smul_deriv` we only require that `g` is continuous on `f '' [a, b]`. -/ theorem integral_comp_smul_deriv' {f f' : ℝ → ℝ} {g : ℝ → E} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, f' x • (g ∘ f) x = ∫ x in f a..f b, g x := integral_comp_smul_deriv'' (λ x hx, (h x hx).continuous_at.continuous_within_at) (λ x hx, (h x $ Ioo_subset_Icc_self hx).has_deriv_within_at) h' hg /-- Change of variables, most common version. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_smul_deriv {f f' : ℝ → ℝ} {g : ℝ → E} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous g) : ∫ x in a..b, f' x • (g ∘ f) x = ∫ x in f a..f b, g x := integral_comp_smul_deriv' h h' hg.continuous_on theorem integral_deriv_comp_smul_deriv' {f f' : ℝ → ℝ} {g g' : ℝ → E} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g [f a, f b]) (hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), has_deriv_within_at g (g' x) (Ioi x) x) (hg' : continuous_on g' (f '' [a, b])) : ∫ x in a..b, f' x • (g' ∘ f) x = (g ∘ f) b - (g ∘ f) a := begin rw [integral_comp_smul_deriv'' hf hff' hf' hg', integral_eq_sub_of_has_deriv_right hg hgg' (hg'.mono _).interval_integrable], exact intermediate_value_interval hf end theorem integral_deriv_comp_smul_deriv {f f' : ℝ → ℝ} {g g' : ℝ → E} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x)) (hf' : continuous_on f' (interval a b)) (hg' : continuous g') : ∫ x in a..b, f' x • (g' ∘ f) x = (g ∘ f) b - (g ∘ f) a := integral_eq_sub_of_has_deriv_at (λ x hx, (hg x hx).scomp x $ hf x hx) (hf'.smul (hg'.comp_continuous_on $ has_deriv_at.continuous_on hf)).interval_integrable end smul section mul /-- Change of variables, general form for scalar functions. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv'' {f f' g : ℝ → ℝ} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u := by simpa [mul_comm] using integral_comp_smul_deriv'' hf hff' hf' hg /-- Change of variables. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. Compared to `interval_integral.integral_comp_mul_deriv` we only require that `g` is continuous on `f '' [a, b]`. -/ theorem integral_comp_mul_deriv' {f f' g : ℝ → ℝ} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := by simpa [mul_comm] using integral_comp_smul_deriv' h h' hg /-- Change of variables, most common version. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv {f f' g : ℝ → ℝ} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous g) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := integral_comp_mul_deriv' h h' hg.continuous_on theorem integral_deriv_comp_mul_deriv' {f f' g g' : ℝ → ℝ} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g [f a, f b]) (hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), has_deriv_within_at g (g' x) (Ioi x) x) (hg' : continuous_on g' (f '' [a, b])) : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := by simpa [mul_comm] using integral_deriv_comp_smul_deriv' hf hff' hf' hg hgg' hg' theorem integral_deriv_comp_mul_deriv {f f' g g' : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x)) (hf' : continuous_on f' (interval a b)) (hg' : continuous g') : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := by simpa [mul_comm] using integral_deriv_comp_smul_deriv hf hg hf' hg' end mul end interval_integral
77fc5345fc8a45c10e3919c2ef9020da1b2371fc
137c667471a40116a7afd7261f030b30180468c2
/src/linear_algebra/basic.lean
294ca6bbc5ea5e4d9c567dbdf4439393b7b4bb0c
[ "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
113,451
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import algebra.big_operators.pi import algebra.module.hom import algebra.module.pi import algebra.module.prod import algebra.module.submodule import algebra.module.submodule_lattice import algebra.group.prod import data.finsupp.basic import data.dfinsupp import algebra.pointwise import order.compactly_generated import order.omega_complete_partial_order /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module`. ## Main definitions * Many constructors for linear maps * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first, second and third isomorphism laws for modules are proved as `linear_map.quot_ker_equiv_range`, `linear_map.quotient_inf_equiv_sup_quotient` and `submodule.quotient_quotient_equiv_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. * We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is `\.`, not the same as the scalar multiplication `•`/`\bub`. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [monoid R] [add_comm_monoid M] [distrib_mul_action R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum @[simp] lemma sum_smul_index_linear_map' {α : Type u} {R : Type v} {M : Type w} {M₂ : Type x} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] {v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} : (c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) := begin rw [finsupp.sum_smul_index', finsupp.smul_sum], { simp only [linear_map.map_smul], }, { intro i, exact (h i).map_zero }, end variable (R) /-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between `α →₀ β` and `α → β`. -/ @[simps apply] noncomputable def linear_equiv_fun_on_fintype {α} [fintype α] [add_comm_monoid M] [semiring R] [module R M] : (α →₀ M) ≃ₗ[R] (α → M) := { to_fun := coe_fn, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl }, .. equiv_fun_on_fintype } @[simp] lemma linear_equiv_fun_on_fintype_single {α} [decidable_eq α] [fintype α] [add_comm_monoid M] [semiring R] [module R M] (x : α) (m : M) : (@linear_equiv_fun_on_fintype R M α _ _ _ _) (single x m) = pi.single x m := begin ext a, change (equiv_fun_on_fintype (single x m)) a = _, convert _root_.congr_fun (equiv_fun_on_fintype_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_single {α} [decidable_eq α] [fintype α] [add_comm_monoid M] [semiring R] [module R M] (x : α) (m : M) : (@linear_equiv_fun_on_fintype R M α _ _ _ _).symm (pi.single x m) = single x m := begin ext a, change (equiv_fun_on_fintype.symm (pi.single x m)) a = _, convert congr_fun (equiv_fun_on_fintype_symm_single x m) a, end end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f g : M →ₗ[R] M₂) include R theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := (f.dom_restrict p).cod_restrict p $ set_like.forall.2 hf lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨{ to_fun := 0, map_add' := by simp, map_smul' := by simp }⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl @[simp] lemma default_def : default (M →ₗ[R] M₂) = 0 := rfl instance unique_of_left [subsingleton M] : unique (M →ₗ[R] M₂) := { uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero], .. linear_map.inhabited } instance unique_of_right [subsingleton M₂] : unique (M →ₗ[R] M₂) := coe_injective.unique /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, { to_fun := f + g, map_add' := by simp [add_comm, add_left_comm], map_smul' := by simp [smul_add] }⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := { zero := 0, add := (+), add_assoc := by intros; ext; simp [add_comm, add_left_comm], zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, nsmul_zero' := λ f, by { ext x, simp }, nsmul_succ' := λ n f, by { ext x, simp [nat.succ_eq_one_add, add_nsmul] } } instance linear_map_apply_is_add_monoid_hom (a : M) : is_add_monoid_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a, map_zero := rfl } lemma add_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (h + g).comp f = h.comp f + g.comp f := rfl lemma comp_add (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (f + g) = h.comp f + h.comp g := by { ext, simp } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm section smul_right variables {S : Type*} [semiring S] [module R S] [module S M] [is_scalar_tower R S M] /-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/ def smul_right (f : M₂ →ₗ[R] S) (x : M) : M₂ →ₗ[R] M := { to_fun := λb, f b • x, map_add' := λ x y, by rw [f.map_add, add_smul], map_smul' := λ b y, by rw [f.map_smul, smul_assoc] } @[simp] theorem coe_smul_right (f : M₂ →ₗ[R] S) (x : M) : (smul_right f x : M₂ → M) = λ c, f c • x := rfl theorem smul_right_apply (f : M₂ →ₗ[R] S) (x : M) (c : M₂) : smul_right f x c = f c • x := rfl end smul_right instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ lemma one_eq_id : (1 : M →ₗ[R] M) = id := rfl lemma mul_eq_comp (f g : M →ₗ[R] M) : f * g = f.comp g := rfl @[simp] lemma one_apply (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_apply (f g : M →ₗ[R] M) (x : M) : (f * g) x = f (g x) := rfl lemma coe_one : ⇑(1 : M →ₗ[R] M) = _root_.id := rfl lemma coe_mul (f g : M →ₗ[R] M) : ⇑(f * g) = f ∘ g := rfl instance [nontrivial M] : nontrivial (module.End R M) := begin obtain ⟨m, ne⟩ := (nontrivial_iff_exists_ne (0 : M)).mp infer_instance, exact nontrivial_of_ne 1 0 (λ p, ne (linear_map.congr_fun p m)), end @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩ }; intros; try { refl }; apply linear_map.ext; simp {proj := ff} @[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) : (f^n) m = (f^[n] m) := begin induction n with n ih, { refl, }, { simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih], exact (function.commute.iterate_self _ _ m).symm, }, end lemma pow_map_zero_of_le {f : module.End R M} {m : M} {k l : ℕ} (hk : k ≤ l) (hm : (f^k) m = 0) : (f^l) m = 0 := by rw [← nat.sub_add_cancel hk, pow_add, mul_apply, hm, map_zero] lemma commute_pow_left_of_commute {f : M →ₗ[R] M₂} {g : module.End R M} {g₂ : module.End R M₂} (h : g₂.comp f = f.comp g) (k : ℕ) : (g₂^k).comp f = f.comp (g^k) := begin induction k with k ih, { simpa only [pow_zero], }, { rw [pow_succ, pow_succ, linear_map.mul_eq_comp, linear_map.comp_assoc, ih, ← linear_map.comp_assoc, h, linear_map.comp_assoc, linear_map.mul_eq_comp], }, end lemma submodule_pow_eq_zero_of_pow_eq_zero {N : submodule R M} {g : module.End R N} {G : module.End R M} (h : G.comp N.subtype = N.subtype.comp g) {k : ℕ} (hG : G^k = 0) : g^k = 0 := begin ext m, have hg : N.subtype.comp (g^k) m = 0, { rw [← commute_pow_left_of_commute h, hG, zero_comp, zero_apply], }, simp only [submodule.subtype_apply, comp_app, submodule.coe_eq_zero, coe_comp] at hg, rw [hg, linear_map.zero_apply], end lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) := by { ext m, apply pow_apply, } @[simp] lemma id_pow (n : ℕ) : (id : M →ₗ[R] M)^n = id := one_pow n section variables {f' : M →ₗ[R] M} lemma iterate_succ (n : ℕ) : (f' ^ (n + 1)) = comp (f' ^ n) f' := by rw [pow_succ', mul_eq_comp] lemma iterate_surjective (h : surjective f') : ∀ n : ℕ, surjective ⇑(f' ^ n) | 0 := surjective_id | (n + 1) := by { rw [iterate_succ], exact surjective.comp (iterate_surjective n) h, } lemma iterate_injective (h : injective f') : ∀ n : ℕ, injective ⇑(f' ^ n) | 0 := injective_id | (n + 1) := by { rw [iterate_succ], exact injective.comp (iterate_injective n) h, } lemma iterate_bijective (h : bijective f') : ∀ n : ℕ, bijective ⇑(f' ^ n) | 0 := bijective_id | (n + 1) := by { rw [iterate_succ], exact bijective.comp (iterate_bijective n) h, } lemma injective_of_iterate_injective {n : ℕ} (hn : n ≠ 0) (h : injective ⇑(f' ^ n)) : injective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), iterate_succ, coe_comp] at h, exact injective.of_comp h, end end section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] (f g : M →ₗ[R] M₂) /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, { to_fun := -f, map_add' := by simp [add_comm], map_smul' := by simp }⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl @[simp] lemma comp_neg (g : M₂ →ₗ[R] M₃) : g.comp (- f) = - g.comp f := by { ext, simp } /-- The negation of a linear map is linear. -/ instance : has_sub (M →ₗ[R] M₂) := ⟨λ f g, { to_fun := f - g, map_add' := λ x y, by simp only [pi.sub_apply, map_add, add_sub_comm], map_smul' := λ r x, by simp only [pi.sub_apply, map_smul, smul_sub] }⟩ @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl lemma sub_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (g - f) = h.comp g - h.comp f := by { ext, simp } /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, add_left_neg := _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, gsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. linear_map.add_comm_monoid }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } end add_comm_group section has_scalar variables {S : Type*} [semiring R] [monoid S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [distrib_mul_action S M₂] [smul_comm_class R S M₂] (f : M →ₗ[R] M₂) instance : has_scalar S (M →ₗ[R] M₂) := ⟨λ a f, { to_fun := a • f, map_add' := λ x y, by simp only [pi.smul_apply, f.map_add, smul_add], map_smul' := λ c x, by simp only [pi.smul_apply, f.map_smul, smul_comm c] }⟩ @[simp] lemma smul_apply (a : S) (x : M) : (a • f) x = a • f x := rfl instance {T : Type*} [monoid T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [smul_comm_class S T M₂] : smul_comm_class S T (M →ₗ[R] M₂) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ -- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and -- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible. instance {T : Type*} [monoid T] [has_scalar S T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [is_scalar_tower S T M₂] : is_scalar_tower S T (M →ₗ[R] M₂) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance : distrib_mul_action S (M →ₗ[R] M₂) := { one_smul := λ f, ext $ λ _, one_smul _ _, mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _, smul_add := λ c f g, ext $ λ x, smul_add _ _ _, smul_zero := λ c, ext $ λ x, smul_zero _ } theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) := rfl end has_scalar section module variables {S : Type*} [semiring R] [semiring S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] (f : M →ₗ[R] M₂) instance : module S (M →ₗ[R] M₂) := { add_smul := λ a b f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variable (S) /-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`. See `linear_map.applyₗ` for a version where `S = R`. -/ @[simps] def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ := { to_fun := λ v, { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v }, map_zero' := linear_map.ext $ λ f, f.map_zero, map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ } section variables (R M) /-- The equivalence between R-linear maps from `R` to `M`, and points of `M` itself. This says that the forgetful functor from `R`-modules to types is representable, by `R`. This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`. When `R` is commutative, we can take this to be the usual action with `S = R`. Otherwise, `S = ℕ` shows that the equivalence is additive. See note [bundled maps over different rings]. -/ @[simps] def ring_lmap_equiv_self [module S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M := { to_fun := λ f, f 1, inv_fun := smul_right (1 : R →ₗ[R] R), left_inv := λ f, by { ext, simp }, right_inv := λ x, by simp, .. applyₗ' S (1 : R) } end end module section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (f g : M →ₗ[R] M₂) include R theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := { to_fun := f.comp, map_add' := λ _ _, linear_map.ext $ λ _, f.map_add _ _, map_smul' := λ _ _, linear_map.ext $ λ _, f.map_smul _ _ } /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. See also `linear_map.applyₗ'` for a version that works with two different semirings. This is the `linear_map` version of `add_monoid_hom.eval`. -/ @[simps] def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ := { to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v }, map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _, ..applyₗ' R } /-- Alternative version of `dom_restrict` as a linear map. -/ def dom_restrict' (p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) := { to_fun := λ φ, φ.dom_restrict p, map_add' := by simp [linear_map.ext_iff], map_smul' := by simp [linear_map.ext_iff] } @[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : dom_restrict' p f x = f x := rfl end comm_semiring section semiring variables [semiring R] [add_comm_monoid M] [module R M] instance endomorphism_semiring : semiring (M →ₗ[R] M) := by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), zero := 0, add := (+), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, .. linear_map.add_comm_monoid, .. }; intros; try { refl }; apply linear_map.ext; simp {proj := ff} end semiring section ring variables [ring R] [add_comm_group M] [module R M] instance endomorphism_ring : ring (M →ₗ[R] M) := { ..linear_map.endomorphism_semiring, ..linear_map.add_comm_group } end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map /-- The `ℕ`-linear equivalence between additive morphisms `A →+ B` and `ℕ`-linear morphisms `A →ₗ[ℕ] B`. -/ @[simps] def add_monoid_hom_lequiv_nat {A B : Type*} [add_comm_monoid A] [add_comm_monoid B] : (A →+ B) ≃ₗ[ℕ] (A →ₗ[ℕ] B) := { to_fun := add_monoid_hom.to_nat_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-- The `ℤ`-linear equivalence between additive morphisms `A →+ B` and `ℤ`-linear morphisms `A →ₗ[ℤ] B`. -/ @[simps] def add_monoid_hom_lequiv_int {A B : Type*} [add_comm_group A] [add_comm_group B] : (A →+ B) ≃ₗ[ℤ] (A →ₗ[ℤ] B) := { to_fun := add_monoid_hom.to_int_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set variables {p p'} /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } instance add_comm_monoid_submodule : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl variables (R) lemma subsingleton_iff : subsingleton M ↔ subsingleton (submodule R M) := add_submonoid.subsingleton_iff.trans $ begin rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top], convert to_add_submonoid_eq; refl end lemma nontrivial_iff : nontrivial M ↔ nontrivial (submodule R M) := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans not_nontrivial_iff_subsingleton.symm) variables {R} instance [subsingleton M] : unique (submodule R M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mp ‹_›) a _⟩ instance unique' [subsingleton R] : unique (submodule R M) := by haveI := module.subsingleton R M; apply_instance instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mp ‹_› theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma apply_coe_mem_map (f : M →ₗ[R] M₂) {p : submodule R M} (r : p) : f r ∈ map f p := mem_map_of_mem r.prop @[simp] lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := set_like.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] lemma range_map_nonempty (N : submodule R M) : (set.range (λ ϕ, submodule.map ϕ N : (M →ₗ[R] M₂) → submodule R M₂)).nonempty := ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩ /-- The pushforward of a submodule by an injective linear map is linearly equivalent to the original submodule. -/ @[simps] noncomputable def equiv_map_of_injective (f : M →ₗ[R] M₂) (i : injective f) (p : submodule R M) : p ≃ₗ[R] p.map f := { map_add' := by { intros, simp, refl, }, map_smul' := by { intros, simp, refl, }, ..(equiv.set.image f p i) } /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := set_like.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ section galois_coinsertion variables {f : M →ₗ[R] M₂} (hf : injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) lemma comap_map_eq_of_injective (p : submodule R M) : (p.map f).comap f = p := (gci_map_comap hf).u_l_eq _ lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective lemma comap_inf_map_of_injective (p q : submodule R M) : (p.map f ⊓ q.map f).comap f = p ⊓ q := (gci_map_comap hf).u_inf_l _ _ lemma comap_infi_map_of_injective (S : ι → submodule R M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ lemma comap_sup_map_of_injective (p q : submodule R M) : (p.map f ⊔ q.map f).comap f = p ⊔ q := (gci_map_comap hf).u_sup_l _ _ lemma comap_supr_map_of_injective (S : ι → submodule R M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ lemma map_le_map_iff_of_injective (p q : submodule R M) : p.map f ≤ q.map f ↔ p ≤ q := (gci_map_comap hf).l_le_l_iff lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span lemma map_span (f : M →ₗ[R] M₂) (s : set M) : (span R s).map f = span R (f '' s) := eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩ alias submodule.map_span ← linear_map.map_span lemma map_span_le {R M M₂ : Type*} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) (s : set M) (N : submodule R M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N := begin rw [f.map_span, span_le, set.image_subset_iff], exact iff.rfl end alias submodule.map_span_le ← linear_map.map_span_le /- See also `span_preimage_eq` below. -/ lemma span_preimage_le (f : M →ₗ[R] M₂) (s : set M₂) : span R (f ⁻¹' s) ≤ (span R s).comap f := by { rw [span_le, comap_coe], exact preimage_mono (subset_span), } alias submodule.span_preimage_le ← linear_map.span_preimage_le /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h lemma span_nat_eq_add_submonoid_closure (s : set M) : (span ℕ s).to_add_submonoid = add_submonoid.closure s := begin refine eq.symm (add_submonoid.closure_eq_of_le subset_span _), apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _, rw span_le, exact add_submonoid.subset_closure, end @[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s := by rw [span_nat_eq_add_submonoid_closure, s.closure_eq] lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) : (span ℤ s).to_add_subgroup = add_subgroup.closure s := eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx (λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _) (λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _) @[simp] lemma span_int_eq {M : Type*} [add_comm_group M] (s : add_subgroup M) : (span ℤ (s : set M)).to_add_subgroup = s := by rw [span_int_eq_add_subgroup_closure, s.closure_eq] section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} := by simp only [←span_Union, set.bUnion_of_singleton s] @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M} (h : ∀ i ∈ s, f i ∈ p i) : ∑ i in s, f i ∈ ⨆ i ∈ s, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi) lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M} (h : ∀ i, f i ∈ p i) : ∑ i, f i ∈ ⨆ i, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i (h i) @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] end @[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →ₘ submodule R M) : (↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) := coe_supr_of_directed a a.monotone.directed_le /-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/ lemma coe_scott_continuous : omega_complete_partial_order.continuous' (coe : submodule R M → set M) := ⟨set_like.coe_mono, coe_supr_of_chain⟩ @[simp] lemma mem_supr_of_chain (a : ℕ →ₘ submodule R M) (m : M) : m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k := mem_supr_of_directed a a.monotone.directed_le section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] lemma coe_sup : ↑(p ⊔ p') = (p + p' : set M) := by { ext, rw [set_like.mem_coe, mem_sup, set.mem_add], simp, } end /- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar multiplication character `•`, with escape sequence `\bub`. -/ notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x) lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} : s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v := by simp_rw [set_like.le_def, mem_span_singleton] lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v := begin rw [eq_top_iff, le_span_singleton_iff], finish, end @[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ := by { ext, simp [mem_span_singleton, eq_comm] } lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x := begin rw [span_le, set.singleton_subset_iff, set_like.mem_coe], exact smul_mem _ _ (mem_span_singleton_self _) end lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x := begin refine le_antisymm (span_singleton_smul_le r x) _, convert span_singleton_smul_le r⁻¹ (r • x), exact (inv_smul_smul' hr _).symm end lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {p : submodule K E} {x : E} (x0 : x ≠ 0) : disjoint p (K ∙ x) ↔ x ∉ p := disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩ lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma apply_mem_span_image_of_mem_span (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) : f x ∈ submodule.span R (f '' s) := begin rw submodule.span_image, exact submodule.mem_map_of_mem h end /-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/ lemma not_mem_span_of_apply_not_mem_span_image (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : f x ∉ submodule.span R (f '' s)) : x ∉ submodule.span R s := not.imp h (apply_mem_span_image_of_mem_span f) lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, set_like.mem_coe] lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end instance : is_compactly_generated (submodule R M) := ⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩, apply singleton_span_is_compact_element, end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩ lemma lt_add_iff_not_mem {I : submodule R M} {a : M} : I < I + (R ∙ a) ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I + (R ∙ a) ≤ I, { simp only [add_eq_sup, sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply set_like.lt_iff_le_and_exists.mpr, split, simp only [add_eq_sup, le_sup_left], use a, split, swap, { assumption, }, { have : (R ∙ a) ≤ I + (R ∙ a) := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end section open_locale classical /-- For every element in the span of a set, there exists a finite subset of the set such that the element is contained in the span of the subset. -/ lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) : ∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) := begin refine span_induction hx (λ x hx, _) _ _ _, { refine ⟨{x}, _, _⟩, { rwa [finset.coe_singleton, set.singleton_subset_iff] }, { rw finset.coe_singleton, exact submodule.mem_span_singleton_self x } }, { use ∅, simp }, { rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩, refine ⟨X ∪ Y, _, _⟩, { rw finset.coe_union, exact set.union_subset hX hY }, rw [finset.coe_union, span_union, mem_sup], exact ⟨x, hxX, y, hyY, rfl⟩, }, { rintros a x ⟨T, hT, h2⟩, exact ⟨T, hT, smul_mem _ _ h2⟩ } end end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := set_like.coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [set_like.le_def], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set @[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff @[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p := ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩, λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩ @[simp] lemma span_neg (s : set M) : span R (-s) = span R s := calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp ... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm ... = span R s : by simp lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : has_sub (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a - b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ (neg_mem p h₂)⟩ @[simp] theorem mk_sub : (mk (x - y) : quotient p) = mk x - mk y := rfl instance : add_comm_group (quotient p) := { zero := (0 : quotient p), add := (+), neg := has_neg.neg, sub := has_sub.sub, add_assoc := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, simp only [←mk_add p, quot_mk_eq_mk, add_assoc] }, zero_add := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, quot_mk_eq_mk, zero_add] }, add_zero := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, add_zero, quot_mk_eq_mk] }, add_comm := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, quot_mk_eq_mk, add_comm] }, add_left_neg := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, ←mk_neg p, quot_mk_eq_mk, add_left_neg] }, sub_eq_add_neg := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, ←mk_neg p, ←mk_sub p, sub_eq_add_neg, quot_mk_eq_mk] }, nsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, nsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, nsmul_succ' := by { rintros n ⟨⟩, simp only [nat.succ_eq_one_add, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul], refl }, gsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, gsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, gsmul_succ' := by { rintros n ⟨⟩, simp [nat.succ_eq_add_one, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul, add_smul, add_comm], refl }, gsmul_neg' := by { rintros n ⟨x⟩, simp_rw [gsmul_neg_succ_of_nat, gsmul_coe_nat], refl }, } instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl @[simp] theorem mk_nsmul (n : ℕ) : (mk (n • x) : quotient p) = n • mk x := rfl instance : module R (quotient p) := module.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) := by { rintros ⟨x⟩, exact ⟨x, rfl⟩ } lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) := begin obtain ⟨x, _, not_mem_s⟩ := set_like.exists_of_lt h, refine ⟨⟨mk x, 0, _⟩⟩, simpa using not_mem_s end end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/ lemma eq_on_span {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`. See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/ lemma eq_on_span' {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) : set.eq_on f g (span R s : set M) := eq_on_span H /-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are equal. -/ lemma ext_on {s : set M} {f g : M →ₗ[R] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) : f = g := linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _)) /-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at each `v i`, then they are equal. -/ lemma ext_on_range {v : ι → M} {f g : M →ₗ[R] M₂} (hv : span R (set.range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := ext_on hv (set.forall_range_iff.2 h) section finsupp variables {γ : Type*} [has_zero γ] @[simp] lemma map_finsupp_sum (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end finsupp section dfinsupp variables {γ : ι → Type*} [decidable_eq ι] [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] @[simp] lemma map_dfinsupp_sum (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end dfinsupp theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. See Note [range copy pattern]. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := (map f ⊤).copy (set.range f) set.image_univ.symm theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := rfl @[simp] theorem mem_range {f : M →ₗ[R] M₂} {x} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl lemma range_eq_map (f : M →ₗ[R] M₂) : f.range = map f ⊤ := by { ext, simp } theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := set_like.coe_injective set.range_id theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := set_like.coe_injective (set.range_comp g f) theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := set_like.coe_mono (set.range_comp_subset_range f g) theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [set_like.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := set_like.coe_mono (set.image_subset_range f p) /-- The decreasing sequence of submodules consisting of the ranges of the iterates of a linear map. -/ @[simps] def iterate_range {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (f ^ n).range, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_range at h, obtain ⟨m, rfl⟩ := h, rw linear_map.mem_range, use (f ^ c) m, rw [pow_add, linear_map.mul_apply], end⟩ /-- Restrict the codomain of a linear map `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₗ[R] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot_of_inverse {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M} (h : g.comp f = id) : ker f = ⊥ := ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero] lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := by simpa only [range_eq_map] using map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf map_le_range (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := by simpa only [range_eq_map] using submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem range_eq_bot {f : M →ₗ[R] M₂} : range f = ⊥ ↔ f = 0 := by rw [← range_le_bot_iff, le_bot_iff] lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ ⟨_, rfl⟩, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y hy, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end /-- The increasing sequence of submodules consisting of the kernels of the iterates of a linear map. -/ @[simps] def iterate_ker {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ submodule R M := ⟨λ n, (f ^ n).ker, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_ker at h, rw [linear_map.mem_ker, add_comm, pow_add, linear_map.mul_apply, h, linear_map.map_zero], end⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range_eq_map, map_le_map_iff] end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables {f : M →ₗ[R] M₂} include R open submodule theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ lemma ker_le_iff {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p := begin split, { intros h, use 0, rw [← set_like.mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, }, { rintros ⟨y, h₁, h₂⟩, rw set_like.le_def, intros z hz, simp only [mem_ker, set_like.mem_coe] at hz, rw [← set_like.mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁, have hx' : x ∈ p, { exact h₂ hx, }, have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], }, suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], }, exact p.sub_mem hxz hx', }, end end ring section field variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := by simpa only [range_eq_map] using submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := by simpa only [range_eq_map] using submodule.map_smul' f _ a lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) : (K ∙ x) ⊔ f.ker = ⊤ := eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x, submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩, ⟨y - (f y * (f x)⁻¹) • x, by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc, inv_mul_cancel hx, mul_one, sub_self], by simp only [add_sub_cancel'_right]⟩⟩) end field end linear_map namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [module R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := f.range_eq_map.symm @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_le_range : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, map_le_map_iff' (ker_subtype p) } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := { to_fun := quotient.mk, map_add' := by simp, map_smul' := by simp } @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := { to_fun := λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, map_add' := by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, map_smul' := by rintro a ⟨x⟩; exact f.map_smul a x } @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := by simpa only [range_eq_map] using map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.rel_iso : submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p], map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.order_embedding : submodule R p.quotient ↪o submodule R M := (rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.order_embedding p p' = comap p.mkq p' := rfl lemma span_preimage_eq {f : M →ₗ[R] M₂} {s : set M₂} (h₀ : s.nonempty) (h₁ : s ⊆ range f) : span R (f ⁻¹' s) = (span R s).comap f := begin suffices : (span R s).comap f ≤ span R (f ⁻¹' s), { exact le_antisymm (span_preimage_le f s) this, }, have hk : ker f ≤ span R (f ⁻¹' s), { let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, }, rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy, exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), }, rw ← left_eq_sup at hk, rw f.range_coe at h₁, rw [hk, ← map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁], exact inf_le_right, end end ring end submodule namespace linear_map section semiring variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end lemma range_comp_of_range_eq_top {f : M →ₗ[R] M₂} (g : M₂ →ₗ[R] M₃) (hf : range f = ⊤) : range (g.comp f) = range g := by rw [range_comp, hf, submodule.map_top] lemma ker_comp_of_ker_eq_bot (f : M →ₗ[R] M₂) {g : M₂ →ₗ[R] M₃} (hg : ker g = ⊥) : ker (g.comp f) = ker f := by rw [ker_comp, hg, submodule.comap_bot] end semiring section ring variables [ring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] lemma range_mkq_comp (f : M →ₗ[R] M₂) : f.range.mkq.comp f = 0 := linear_map.ext $ λ x, by simp lemma ker_le_range_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 := by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype] /-- An epimorphism is surjective. -/ lemma range_eq_top_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : M₂ →ₗ[R] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R] f.range.quotient).comp f = 0 := zero_comp _, rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)], exact ker_zero end end ring end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section subsingleton variables [module R M] [module R M₂] [subsingleton M] [subsingleton M₂] /-- Between two zero modules, the zero map is an equivalence. -/ instance : has_zero (M ≃ₗ[R] M₂) := ⟨{ to_fun := 0, inv_fun := 0, right_inv := λ x, subsingleton.elim _ _, left_inv := λ x, subsingleton.elim _ _, ..(0 : M →ₗ[R] M₂)}⟩ -- Even though these are implied by `subsingleton.elim` via the `unique` instance below, they're -- nice to have as `rfl`-lemmas for `dsimp`. @[simp] lemma zero_symm : (0 : M ≃ₗ[R] M₂).symm = 0 := rfl @[simp] lemma coe_zero : ⇑(0 : M ≃ₗ[R] M₂) = 0 := rfl lemma zero_apply (x : M) : (0 : M ≃ₗ[R] M₂) x = 0 := rfl /-- Between two zero modules, the zero map is the only equivalence. -/ instance : unique (M ≃ₗ[R] M₂) := { uniq := λ f, to_linear_map_injective (subsingleton.elim _ _), default := 0 } end subsingleton section variables {module_M : module R M} {module_M₂ : module R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := set_like.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule `p` of the domain onto the image of that submodule. This is `linear_equiv.of_submodule'` but with `map` on the right instead of `comap` on the left. -/ def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) := { inv_fun := λ y, ⟨e.symm y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) } @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl end section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def curry : (V × V₂ → R) ≃ₗ[R] (V → V₂ → R) := { map_add' := λ _ _, by { ext, refl }, map_smul' := λ _ _, by { ext, refl }, .. equiv.curry _ _ _ } @[simp] lemma coe_curry : ⇑(linear_equiv.curry R V V₂) = curry := rfl @[simp] lemma coe_curry_symm : ⇑(linear_equiv.curry R V V₂).symm = uncurry := rfl end uncurry section variables {module_M : module R M} {module_M₂ : module R M₂} {module_M₃ : module R M₃} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) (l : M₃ →ₗ[R] M) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl /-- A linear equivalence of two modules restricts to a linear equivalence from the preimage of any submodule to that submodule. This is `linear_equiv.of_submodule` but with `comap` on the left instead of `map` on the right. -/ def of_submodule' [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) : U.comap (f : M →ₗ[R] M₂) ≃ₗ[R] U := (f.symm.of_submodules _ _ f.symm.map_eq_comap).symm lemma of_submodule'_to_linear_map [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) : (f.of_submodule' U).to_linear_map = (f.to_linear_map.dom_restrict _).cod_restrict _ subtype.prop := by { ext, refl } @[simp] lemma of_submodule'_apply [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U.comap (f : M →ₗ[R] M₂)) : (f.of_submodule' U x : M₂) = f (x : M) := rfl @[simp] lemma of_submodule'_symm_apply [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U) : ((f.of_submodule' U).symm x : M) = f.symm (x : M₂) := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [module R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (set_like.le_def.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective @[simp] theorem range_comp : (h.comp (e : M →ₗ[R] M₂)).range = h.range := linear_map.range_comp_of_range_eq_top _ e.range @[simp] theorem ker_comp : ((e : M →ₗ[R] M₂).comp l).ker = l.ker := linear_map.ker_comp_of_ker_eq_bot _ e.ker variables {f g} /-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear equivalence between `M` and `f.range`. This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of `linear_map.range_restrict`. -/ def of_left_inverse {g : M₂ → M} (h : function.left_inverse g f) : M ≃ₗ[R] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.range_restrict } @[simp] lemma of_left_inverse_apply (h : function.left_inverse g f) (x : M) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl end end add_comm_monoid section add_comm_group variables [semiring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b end add_comm_group section neg variables (R) [semiring R] [add_comm_group M] [module R M] /-- `x ↦ -x` as a `linear_equiv` -/ def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) } variable {R} @[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl lemma neg_apply (x : M) : neg R x = -x := by simp @[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl end neg section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] variables {module_M : module R M} {module_M₂ : module R M₂} variables (f : M →ₗ[R] M₂) (e : M ≃ₗ[R] M₂) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/ noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range := of_left_inverse $ classical.some_spec (linear_map.ker_eq_bot.1 h).has_left_inverse @[simp] theorem of_injective_apply {h : f.ker = ⊥} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp }, right_inv := λ f, by { ext x, simp }, map_add' := λ f g, by { ext x, simp }, map_smul' := λ c f, by { ext x, simp } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl @[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) : (arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_group N] [add_comm_group N₂] [add_comm_group N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁] [add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ := begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) := linear_equiv.trans (linear_equiv.of_injective (to_span_singleton K M x) (ker_to_span_singleton K M h)) (of_eq (to_span_singleton K M x).range (K ∙ x) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) := begin apply set_like.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section module variables [semiring R] [add_comm_monoid M] [module R M] /-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q` is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/ def equiv_subtype_map (p : submodule R M) (q : submodule R p) : q ≃ₗ[R] q.map p.subtype := { inv_fun := begin rintro ⟨x, hx⟩, refine ⟨⟨x, _⟩, _⟩; rcases hx with ⟨⟨_, h⟩, _, rfl⟩; assumption end, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl, .. (p.subtype.dom_restrict q).cod_restrict _ begin rintro ⟨x, hx⟩, refine ⟨x, hx, rfl⟩, end } @[simp] lemma equiv_subtype_map_apply {p : submodule R M} {q : submodule R p} (x : q) : (p.equiv_subtype_map q x : M) = p.subtype.dom_restrict q x := rfl @[simp] lemma equiv_subtype_map_symm_apply {p : submodule R M} {q : submodule R p} (x : q.map p.subtype) : ((p.equiv_subtype_map q).symm x : M) = x := by { cases x, refl } /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, set_like.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, set_like.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end module variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl variables (q : submodule R M) /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = q) : p.quotient ≃ₗ[R] q.quotient := { map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl }, ..@quotient.congr _ _ (quotient_rel p) (quotient_rel q) (equiv.refl _) $ λ a b, by { subst h, refl } } end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) @[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw set_like.le_def, intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw set_like.le_def, intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, map_smul' := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace add_equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl end add_equiv namespace linear_map open submodule section isomorphism_laws variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) /-- The first isomorphism theorem for surjective linear maps. -/ noncomputable def quot_ker_equiv_of_surjective (f : M →ₗ[R] M₂) (hf : function.surjective f) : f.ker.quotient ≃ₗ[R] M₂ := f.quot_ker_equiv_range.trans (linear_equiv.of_top f.range (linear_map.range_eq_top.2 hf)) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws section fun_left variables (R M) [semiring R] [add_comm_monoid M] [module R M] variables {m n p : Type*} /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := { to_fun := (∘ f), map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl } @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl theorem fun_left_surjective_of_injective (f : m → n) (hf : injective f) : surjective (fun_left R M f) := begin classical, intro g, refine ⟨λ x, if h : ∃ y, f y = x then g h.some else 0, _⟩, { ext, dsimp only [fun_left_apply], split_ifs with w, { congr, exact hf w.some_spec, }, { simpa only [not_true, exists_apply_eq_apply] using w } }, end theorem fun_left_injective_of_surjective (f : m → n) (hf : surjective f) : injective (fun_left R M f) := begin obtain ⟨g, hg⟩ := hf.has_right_inverse, suffices : left_inverse (fun_left R M g) (fun_left R M f), { exact this.injective }, intro x, simp only [← linear_map.comp_apply, ← fun_left_comp, hg.id, fun_left_id] end /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end fun_left universe i variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map namespace submodule variables [ring R] [add_comm_group M] [module R M] instance : is_modular_lattice (submodule R M) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw [← add_sub_cancel c b, add_comm], apply z.sub_mem haz (xz hb), end⟩ section third_iso_thm variables (S T : submodule R M) (h : S ≤ T) /-- The map from the third isomorphism theorem for modules: `(M / S) / (T / S) → M / T`. -/ def quotient_quotient_equiv_quotient_aux : quotient (T.map S.mkq) →ₗ[R] quotient T := liftq _ (mapq S T linear_map.id h) (by { rintro _ ⟨x, hx, rfl⟩, rw [linear_map.mem_ker, mkq_apply, mapq_apply], exact (quotient.mk_eq_zero _).mpr hx }) @[simp] lemma quotient_quotient_equiv_quotient_aux_mk (x : S.quotient) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk x) = mapq S T linear_map.id h x := liftq_apply _ _ _ @[simp] lemma quotient_quotient_equiv_quotient_aux_mk_mk (x : M) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk (quotient.mk x)) = quotient.mk x := by rw [quotient_quotient_equiv_quotient_aux_mk, mapq_apply, linear_map.id_apply] /-- **Noether's third isomorphism theorem** for modules: `(M / S) / (T / S) ≃ M / T`. -/ def quotient_quotient_equiv_quotient : quotient (T.map S.mkq) ≃ₗ[R] quotient T := { to_fun := quotient_quotient_equiv_quotient_aux S T h, inv_fun := mapq _ _ (mkq S) (le_comap_map _ _), left_inv := λ x, quotient.induction_on' x $ λ x, quotient.induction_on' x $ λ x, by simp, right_inv := λ x, quotient.induction_on' x $ λ x, by simp, .. quotient_quotient_equiv_quotient_aux S T h } end third_iso_thm end submodule
2e9e47e5e7bafdc42ea4b7368741b5db01d8c3a7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/hidingInaccessibleNames.lean
c4028786fe89256f0b9d7c2e7700e18918add1b2
[ "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
689
lean
def f : (xs : List Nat) → Nat → xs ≠ [] → Nat | [], _, _ => _ | [a,b], _, _ => _ | _, _, _ => _ set_option pp.inaccessibleNames true in def f' : (xs : List Nat) → Nat → xs ≠ [] → Nat | [], _, _ => _ -- TODO: figure out why hyp `Ne (α := List Nat) x✝² []` needs α | [a,b], _, _ => _ | _, _, _ => _ theorem ex1 : p ∨ q → q ∨ p := by intro h cases h trace_state apply Or.inr assumption apply Or.inl assumption done theorem ex2 : {p : Prop} → [Decidable p] → p → decide p = true | _, isTrue _, _ => _ | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem ex3 : ∀ {c d : Char}, c = d → c.val = d.val | _, _, rfl => _
0e301c91824ec9efa2b94fb0cbadba0a100bf4ed
4ec0e92c725fad3fd2871a0ab050a7da1c719444
/src/mywork/lecture_4.lean
f3ab0c88dd75d028a405bdf795e50e5acffd3c82
[]
no_license
mitchelltaylor06/cs2120f21
cc2c2b61a7e45c07faa849fcb8a66eb948753a25
efb71a748d7c76e24834d03b8f01c3ae084c1756
refs/heads/main
1,693,841,444,092
1,633,713,850,000
1,633,713,850,000
399,946,415
0
0
null
null
null
null
UTF-8
Lean
false
false
3,189
lean
/- In this file, we give formal statements (our version) of the two axioms of equality. We also present Lean's versions of these rules, and show how you can use them without giving all of the arguments explicitly. -/ /- AXIOMS Everything is equal to itself. A bit more formally, if one is given a type, T, and a value, t, of this type, then you may have a proof of t = t "for free." -/ axiom eq_refl : ∀ (T : Type) -- if T is any type (of thing) (t : T), -- and t is thing of that type, T t = t -- the result type: proof of t = t /- INFERENCE RULE #2/2: SUBSTITUTION OF EQUALS FOR EQUALS Given any type, T, of objects, and any *property*, P, of objects of this type, if you know x has property P (written as P x) and you know that x = y, then you can deduce that y has property P. -/ axiom eq_subst : ∀ (T : Type) -- if T is a type (P : T → Prop) -- and P is a property of T objects (x y : T) -- and x and y are T objects (e : x = y) -- and you have a proof that x = y (px : P x), -- and you have a proof that x has property P P y -- then you can deduce (and get a proof) of P y /- The Lean versions of these axioms are called eq.refl and eq.subst. They're defined in ways that allow (and require) one not to give the T, P, x, or y parameters explicitly when applying eq_subst. More details come later. -/ /- We will now present formal proofs of our two theorems in this style. -/ /- CONJECTURES -/ -- We define eq_symm to be the proposition at issue -- Note: Prop is the type of all propositions in Lean -- And each proposition is itself a type: of it proofs def eq_symm : Prop := ∀ (T : Type) (x y : T), x = y → y = x -- We define eq_trans formally in the same basic way def eq_trans : Prop := ∀ (T : Type) (x y z : T), x = y → y = z → x = z /- PROOFS: From conjectures to theorems -/ /- Proofs: equality is symmetric. -/ example : eq_symm := begin unfold eq_symm, -- replace name with definition assume T x y e, -- assume arbitrary values rw e, -- rw uses eq.subst to replace x with y -- and then applies eq.refl automatically -- QED. end /- A fundamental idea is that any proof is as good as any other for establishing the truth of a proposition. Here is an equally good alternative proof (or to be correct, proof-generating scripts in the "proof tactic" language" of the Lean Prover. -/ example : eq_symm := begin unfold eq_symm, -- replace name with definition assume T x y e, -- assume arbitrary values apply eq.subst e, -- apply axiom 2, substitutability exact eq.refl x, -- apply axiom 1, reflexivity -- QED. end /- Proof: equality is transitive. -/ example : eq_trans := begin unfold eq_trans, assume T, assume x y z, assume e1, assume e2, rw e1, exact e2, end /- Note: Lean defines these rules as - eq.refl - eq.subst - eq.symm - eq.trans -/ /- Practice -/ example : ∀ (T : Type) (x y z : T), x = y → y = z → z = x := begin assume T x y z, assume h1 h2, apply eq.symm _, apply eq.trans h1 h2, end /- INTRODUCTION and ELIMINATION RULES -/
ea8f5ace6975fb5e6cb6655d83dde80c82cf6064
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/group_power/lemmas.lean
dccd0bf686b6e2581458352858bd8a87f5dc6969
[ "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
35,778
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import data.int.cast /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `zsmul` which require additional imports besides those available in `algebra.group_power.basic`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n • (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n • (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) @[simp, norm_cast, to_additive] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n instance invertible_pow (m : M) [invertible m] (n : ℕ) : invertible (m ^ n) := { inv_of := ⅟ m ^ n, inv_of_mul_self := by rw [← (commute_inv_of m).symm.mul_pow, inv_of_mul_self, one_pow], mul_inv_of_self := by rw [← (commute_inv_of m).mul_pow, mul_inv_of_self, one_pow] } lemma inv_of_pow (m : M) [invertible m] (n : ℕ) [invertible (m ^ n)] : ⅟(m ^ n) = ⅟m ^ n := @invertible_unique M _ (m ^ n) (m ^ n) rfl ‹_› (invertible_pow m n) lemma is_unit.pow {m : M} (n : ℕ) : is_unit m → is_unit (m ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ @[simp] lemma is_unit_pow_succ_iff {m : M} {n : ℕ} : is_unit (m ^ (n + 1)) ↔ is_unit m := begin refine ⟨_, λ h, h.pow _⟩, rw [pow_succ, ((commute.refl _).pow_right _).is_unit_mul_iff], exact and.left end lemma is_unit_pos_pow_iff {m : M} : ∀ {n : ℕ} (h : 0 < n), is_unit (m ^ n) ↔ is_unit m | (n + 1) _ := is_unit_pow_succ_iff /-- If `x ^ n.succ = 1` then `x` has an inverse, `x^n`. -/ def invertible_of_pow_succ_eq_one (x : M) (n : ℕ) (hx : x ^ n.succ = 1) : invertible x := ⟨x ^ n, (pow_succ' x n).symm.trans hx, (pow_succ x n).symm.trans hx⟩ /-- If `x ^ n = 1` then `x` has an inverse, `x^(n - 1)`. -/ def invertible_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : invertible x := begin apply invertible_of_pow_succ_eq_one x (n - 1), convert hx, exact tsub_add_cancel_of_le (nat.succ_le_of_lt hn), end lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin haveI := invertible_of_pow_eq_one x n hx hn, exact is_unit_of_invertible x end lemma smul_pow [mul_action M N] [is_scalar_tower M N N] [smul_comm_class M N N] (k : M) (x : N) (p : ℕ) : (k • x) ^ p = k ^ p • x ^ p := begin induction p with p IH, { simp }, { rw [pow_succ', IH, smul_mul_smul, ←pow_succ', ←pow_succ'] } end @[simp] lemma smul_pow' [mul_distrib_mul_action M N] (x : M) (m : N) (n : ℕ) : x • m ^ n = (x • m) ^ n := begin induction n with n ih, { rw [pow_zero, pow_zero], exact smul_one x }, { rw [pow_succ, pow_succ], exact (smul_mul' x m (m ^ n)).trans (congr_arg _ ih) } end end monoid section group variables [group G] [group H] [add_group A] [add_group B] open int local attribute [ematch] le_of_lt open nat theorem zsmul_one [has_one A] (n : ℤ) : n • (1 : A) = n := by cases n; simp @[to_additive add_one_zsmul] lemma zpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, zpow_neg, neg_add, neg_add_cancel_right, zpow_neg, ← int.coe_nat_succ, zpow_coe_nat, zpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] @[to_additive zsmul_sub_one] lemma zpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← zpow_add_one, sub_add_cancel] @[to_additive add_zsmul] lemma zpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, zpow_add_one, ihn, mul_assoc] }, { rw [zpow_sub_one, ← mul_assoc, ← ihn, ← zpow_sub_one, add_sub_assoc] } end @[to_additive add_zsmul_self] lemma mul_self_zpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← zpow_one b }, rw [← zpow_add, add_comm] } @[to_additive add_self_zsmul] lemma mul_zpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← zpow_one b }, rw [← zpow_add, add_comm] } @[to_additive sub_zsmul] lemma zpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, zpow_add, zpow_neg] @[to_additive one_add_zsmul] theorem zpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [zpow_add, zpow_one] @[to_additive] theorem zpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← zpow_add, ← zpow_add, add_comm] -- note that `mul_zsmul` and `zpow_mul` have the primes swapped since their argument order -- and therefore the more "natural" choice of lemma is reversed. @[to_additive mul_zsmul'] theorem zpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, zpow_add, ihn]) (λ n ihn, by simp only [mul_sub, zpow_sub, ihn, mul_one, zpow_one]) @[to_additive mul_zsmul] theorem zpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, zpow_mul] @[to_additive bit0_zsmul] theorem zpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := zpow_add _ _ _ @[to_additive bit1_zsmul] theorem zpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, zpow_add, zpow_bit0, zpow_one] @[simp, norm_cast, to_additive] lemma units.coe_zpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_zpow u n end group section ordered_add_comm_group variables [ordered_add_comm_group A] /-! Lemmas about `zsmul` under ordering, placed here (rather than in `algebra.group_power.order` with their friends) because they require facts from `data.int.basic`-/ open int lemma zsmul_pos {a : A} (ha : 0 < a) {k : ℤ} (hk : (0:ℤ) < k) : 0 < k • a := begin lift k to ℕ using int.le_of_lt hk, rw coe_nat_zsmul, apply nsmul_pos ha, exact (coe_nat_pos.mp hk).ne', end theorem zsmul_strict_mono_left {a : A} (ha : 0 < a) : strict_mono (λ n : ℤ, n • a) := λ n m h, calc n • a = n • a + 0 : (add_zero _).symm ... < n • a + (m - n) • a : add_lt_add_left (zsmul_pos ha (sub_pos.mpr h)) _ ... = m • a : by { rw [← add_zsmul], simp } theorem zsmul_mono_left {a : A} (ha : 0 ≤ a) : monotone (λ n : ℤ, n • a) := λ n m h, calc n • a = n • a + 0 : (add_zero _).symm ... ≤ n • a + (m - n) • a : add_le_add_left (zsmul_nonneg ha (sub_nonneg.mpr h)) _ ... = m • a : by { rw [← add_zsmul], simp } theorem zsmul_le_zsmul {a : A} {n m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a := zsmul_mono_left ha h theorem zsmul_lt_zsmul {a : A} {n m : ℤ} (ha : 0 < a) (h : n < m) : n • a < m • a := zsmul_strict_mono_left ha h theorem zsmul_le_zsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n • a ≤ m • a ↔ n ≤ m := (zsmul_strict_mono_left ha).le_iff_le theorem zsmul_lt_zsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n • a < m • a ↔ n < m := (zsmul_strict_mono_left ha).lt_iff_lt variables (A) lemma zsmul_strict_mono_right {n : ℤ} (hn : 0 < n) : strict_mono ((•) n : A → A) := λ a b hab, begin rw ← sub_pos at hab, rw [← sub_pos, ← zsmul_sub], exact zsmul_pos hab hn, end lemma zsmul_mono_right {n : ℤ} (hn : 0 ≤ n) : monotone ((•) n : A → A) := λ a b hab, begin rw ← sub_nonneg at hab, rw [← sub_nonneg, ← zsmul_sub], exact zsmul_nonneg hab hn, end variables {A} theorem zsmul_le_zsmul' {n : ℤ} (hn : 0 ≤ n) {a₁ a₂ : A} (h : a₁ ≤ a₂) : n • a₁ ≤ n • a₂ := zsmul_mono_right A hn h theorem zsmul_lt_zsmul' {n : ℤ} (hn : 0 < n) {a₁ a₂ : A} (h : a₁ < a₂) : n • a₁ < n • a₂ := zsmul_strict_mono_right A hn h lemma abs_nsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℕ) (a : α) : |n • a| = n • |a| := begin cases le_total a 0 with hneg hpos, { rw [abs_of_nonpos hneg, ← abs_neg, ← neg_nsmul, abs_of_nonneg], exact nsmul_nonneg (neg_nonneg.mpr hneg) n }, { rw [abs_of_nonneg hpos, abs_of_nonneg], exact nsmul_nonneg hpos n } end lemma abs_zsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℤ) (a : α) : |n • a| = |n| • |a| := begin by_cases n0 : 0 ≤ n, { lift n to ℕ using n0, simp only [abs_nsmul, coe_nat_abs, coe_nat_zsmul] }, { lift (- n) to ℕ using int.le_of_lt (neg_pos.mpr (not_le.mp n0)) with m h, rw [← abs_neg (n • a), ← neg_zsmul, ← abs_neg n, ← h, coe_nat_zsmul, coe_nat_abs, coe_nat_zsmul], exact abs_nsmul m _ }, end lemma abs_add_eq_add_abs_le {α : Type*} [linear_ordered_add_comm_group α] {a b : α} (hle : a ≤ b) : |a + b| = |a| + |b| ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases a0 : 0 ≤ a; by_cases b0 : 0 ≤ b, { simp [a0, b0, abs_of_nonneg, add_nonneg a0 b0] }, { exact (lt_irrefl (0 : α) (a0.trans_lt (hle.trans_lt (not_le.mp b0)))).elim }, any_goals { simp [(not_le.mp a0).le, (not_le.mp b0).le, abs_of_nonpos, add_nonpos, add_comm] }, obtain F := (not_le.mp a0), have : (|a + b| = -a + b ↔ b ≤ 0) ↔ (|a + b| = |a| + |b| ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0), { simp [a0, b0, abs_of_neg, abs_of_nonneg, F, F.le] }, refine this.mp ⟨λ h, _, λ h, by simp only [le_antisymm h b0, abs_of_neg F, add_zero]⟩, by_cases ba : a + b ≤ 0, { refine le_of_eq (eq_zero_of_neg_eq _), rwa [abs_of_nonpos ba, neg_add_rev, add_comm, add_right_inj] at h }, { refine (lt_irrefl (0 : α) _).elim, rw [abs_of_pos (not_le.mp ba), add_left_inj] at h, rwa eq_zero_of_neg_eq h.symm at F } end lemma abs_add_eq_add_abs_iff {α : Type*} [linear_ordered_add_comm_group α] (a b : α) : |a + b| = |a| + |b| ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases ab : a ≤ b, { exact abs_add_eq_add_abs_le ab }, { rw [add_comm a, add_comm (abs _), abs_add_eq_add_abs_le ((not_le.mp ab).le), and.comm, @and.comm (b ≤ 0 ) _] } end end ordered_add_comm_group section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group A] theorem zsmul_le_zsmul_iff' {n : ℤ} (hn : 0 < n) {a₁ a₂ : A} : n • a₁ ≤ n • a₂ ↔ a₁ ≤ a₂ := (zsmul_strict_mono_right A hn).le_iff_le theorem zsmul_lt_zsmul_iff' {n : ℤ} (hn : 0 < n) {a₁ a₂ : A} : n • a₁ < n • a₂ ↔ a₁ < a₂ := (zsmul_strict_mono_right A hn).lt_iff_lt theorem nsmul_le_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n • a ≤ m • a ↔ n ≤ m := begin refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h) end theorem nsmul_lt_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n • a < m • a ↔ n < m := begin refine ⟨λ h, _, nsmul_lt_nsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h) end /-- See also `smul_right_injective`. TODO: provide a `no_zero_smul_divisors` instance. We can't do that here because importing that definition would create import cycles. -/ lemma zsmul_right_injective {m : ℤ} (hm : m ≠ 0) : function.injective ((•) m : A → A) := begin cases hm.symm.lt_or_lt, { exact (zsmul_strict_mono_right A h).injective, }, { intros a b hab, refine (zsmul_strict_mono_right A (neg_pos.mpr h)).injective _, rw [neg_zsmul, neg_zsmul, hab], }, end lemma zsmul_right_inj {a b : A} {m : ℤ} (hm : m ≠ 0) : m • a = m • b ↔ a = b := (zsmul_right_injective hm).eq_iff /-- Alias of `zsmul_right_inj`, for ease of discovery alongside `zsmul_le_zsmul_iff'` and `zsmul_lt_zsmul_iff'`. -/ lemma zsmul_eq_zsmul_iff' {a b : A} {m : ℤ} (hm : m ≠ 0) : m • a = m • b ↔ a = b := zsmul_right_inj hm end linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((n • a : A) : with_bot A) = n • a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n • a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n • (a * b) = n • a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := begin induction m with m ih, { rw [pow_zero, pow_zero], exact nat.cast_one }, { rw [pow_succ', pow_succ', nat.cast_mul, ih] } end @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `zsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = (2 : ℤ) • (n * r) := by { dsimp [bit0], rw [add_mul, add_zsmul, one_zsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = (2 : ℤ) • (r * n) := by { dsimp [bit0], rw [mul_add, add_zsmul, one_zsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = (2 : ℤ) • (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = (2 : ℤ) • (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem zsmul_eq_mul [ring R] (a : R) : ∀ (n : ℤ), n • a = n * a | (n : ℕ) := by { rw [coe_nat_zsmul, nsmul_eq_mul], refl } | -[1+ n] := by simp [nat.cast_succ, neg_add_rev, int.cast_neg_succ_of_nat, add_mul] theorem zsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n • a = a * n := by rw [zsmul_eq_mul, (n.cast_commute a).eq] theorem mul_zsmul_left [ring R] (a b : R) (n : ℤ) : n • (a * b) = a * (n • b) := by rw [zsmul_eq_mul', zsmul_eq_mul', mul_assoc] theorem mul_zsmul_assoc [ring R] (a b : R) (n : ℤ) : n • (a * b) = n • a * b := by rw [zsmul_eq_mul, zsmul_eq_mul, mul_assoc] lemma zsmul_int_int (a b : ℤ) : a • b = a * b := by simp lemma zsmul_int_one (n : ℤ) : n • 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := begin induction m with m ih, { rw [pow_zero, pow_zero, int.cast_one] }, { rw [pow_succ, pow_succ, int.cast_mul, ih] } end lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [sq] section ordered_semiring variables [ordered_semiring R] {a : R} /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≤ a * a` and `0 ≤ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' (Hsq : 0 ≤ a * a) (Hsq' : 0 ≤ (1 + a) * (1 + a)) (H : 0 ≤ 2 + a) : ∀ (n : ℕ), 1 + (n : R) * a ≤ (1 + a) ^ n | 0 := by simp | 1 := by simp | (n+2) := have 0 ≤ (n : R) * (a * a * (2 + a)) + a * a, from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsq H)) Hsq, calc 1 + (↑(n + 2) : R) * a ≤ 1 + ↑(n + 2) * a + (n * (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n * a) : by { simp [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsq' ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] private lemma pow_lt_pow_of_lt_one_aux (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin rw [←one_mul (a^i), add_zero, pow_succ], exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw [←one_mul (a^i), pow_succ], apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by { rw [←add_assoc, ←one_mul (a^i), pow_succ], exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one } lemma pow_lt_pow_of_lt_one (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_lt_pow_iff_of_lt_one {n m : ℕ} (hpos : 0 < a) (h : a < 1) : a ^ m < a ^ n ↔ n < m := begin have : strict_mono (λ (n : order_dual ℕ), a ^ (id n : ℕ)) := λ m n, pow_lt_pow_of_lt_one hpos h, exact this.lt_iff_lt end lemma pow_le_pow_of_le_one (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_of_le_one (h₀ : 0 ≤ a) (h₁ : a ≤ 1) {n : ℕ} (hn : n ≠ 0) : a ^ n ≤ a := (pow_one a).subst (pow_le_pow_of_le_one h₀ h₁ (nat.pos_of_ne_zero hn)) lemma sq_le (h₀ : 0 ≤ a) (h₁ : a ≤ 1) : a ^ 2 ≤ a := pow_le_of_le_one h₀ h₁ two_ne_zero end ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring R] lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : ∀ n : ℕ, 0 ≤ C * r ^ n) : C = 0 ∨ (0 < C ∧ 0 ≤ r) := begin have : 0 ≤ C, by simpa only [pow_zero, mul_one] using h 0, refine this.eq_or_lt.elim (λ h, or.inl h.symm) (λ hC, or.inr ⟨hC, _⟩), refine nonneg_of_mul_nonneg_left _ hC, simpa only [pow_one] using h 1 end end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring R] {a : R} {n : ℕ} @[simp] lemma abs_pow (a : R) (n : ℕ) : |a ^ n| = |a| ^ n := (pow_abs a n).symm @[simp] theorem pow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ pow_nonneg h' _, λ ha, pow_bit1_neg ha n⟩ @[simp] theorem pow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))] @[simp] theorem pow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff lemma even.pow_nonneg (hn : even n) (a : R) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_nonneg a k lemma even.pow_pos (hn : even n) (ha : a ≠ 0) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_pos ha k lemma odd.pow_nonpos (hn : odd n) (ha : a ≤ 0) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonpos_iff.mpr ha lemma odd.pow_neg (hn : odd n) (ha : a < 0) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_neg_iff.mpr ha lemma odd.pow_nonneg_iff (hn : odd n) : 0 ≤ a ^ n ↔ 0 ≤ a := ⟨λ h, le_of_not_lt (λ ha, h.not_lt $ hn.pow_neg ha), λ ha, pow_nonneg ha n⟩ lemma odd.pow_nonpos_iff (hn : odd n) : a ^ n ≤ 0 ↔ a ≤ 0 := ⟨λ h, le_of_not_lt (λ ha, h.not_lt $ pow_pos ha _), hn.pow_nonpos⟩ lemma odd.pow_pos_iff (hn : odd n) : 0 < a ^ n ↔ 0 < a := ⟨λ h, lt_of_not_ge' (λ ha, h.not_le $ hn.pow_nonpos ha), λ ha, pow_pos ha n⟩ lemma odd.pow_neg_iff (hn : odd n) : a ^ n < 0 ↔ a < 0 := ⟨λ h, lt_of_not_ge' (λ ha, h.not_le $ pow_nonneg ha _), hn.pow_neg⟩ lemma even.pow_pos_iff (hn : even n) (h₀ : 0 < n) : 0 < a ^ n ↔ a ≠ 0 := ⟨λ h ha, by { rw [ha, zero_pow h₀] at h, exact lt_irrefl 0 h }, hn.pow_pos⟩ lemma even.pow_abs {p : ℕ} (hp : even p) (a : R) : |a| ^ p = a ^ p := begin rw [←abs_pow, abs_eq_self], exact hp.pow_nonneg _ end @[simp] lemma pow_bit0_abs (a : R) (p : ℕ) : |a| ^ bit0 p = a ^ bit0 p := (even_bit0 _).pow_abs _ lemma strict_mono_pow_bit1 (n : ℕ) : strict_mono (λ a : R, a ^ bit1 n) := begin intros a b hab, cases le_total a 0 with ha ha, { cases le_or_lt b 0 with hb hb, { rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1], exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) }, { exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } }, { exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) } end lemma odd.strict_mono_pow (hn : odd n) : strict_mono (λ a : R, a ^ n) := by cases hn with k hk; simpa only [hk, two_mul] using strict_mono_pow_bit1 _ /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow (H : -2 ≤ a) (n : ℕ) : 1 + (n : R) * a ≤ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _ /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow (H : -1 ≤ a) (n : ℕ) : 1 + (n : R) * (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right], by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n end linear_ordered_ring /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) namespace int lemma units_sq (u : units ℤ) : u ^ 2 = 1 := (sq u).symm ▸ units_mul_self u alias int.units_sq ← int.units_pow_two lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_sq, one_pow, mul_one] @[simp] lemma nat_abs_sq (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [sq, int.nat_abs_mul_self', sq] alias int.nat_abs_sq ← int.nat_abs_pow_two lemma abs_le_self_sq (a : ℤ) : (int.nat_abs a : ℤ) ≤ a ^ 2 := by { rw [← int.nat_abs_sq a, sq], norm_cast, apply nat.le_mul_self } alias int.abs_le_self_sq ← int.abs_le_self_pow_two lemma le_self_sq (b : ℤ) : b ≤ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_sq _) alias int.le_self_sq ← int.le_self_pow_two lemma pow_right_injective {x : ℤ} (h : 1 < x.nat_abs) : function.injective ((^) x : ℕ → ℤ) := begin suffices : function.injective (nat_abs ∘ ((^) x : ℕ → ℤ)), { exact function.injective.of_comp this }, convert nat.pow_right_injective h, ext n, rw [function.comp_app, nat_abs_pow] end end int variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, by { convert pow_zero x, exact to_add_one }, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def zpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, zpow_zero x, λ m n, zpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := zpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_zpow, ← of_add_zsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n • x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def zmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n • x, zero_zsmul x, λ m n, add_zsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_zsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_zsmul (f 1) } attribute [to_additive multiples_hom] powers_hom attribute [to_additive zmultiples_hom] zpowers_hom variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma zpowers_hom_apply [group G] (x : G) (n : multiplicative ℤ) : zpowers_hom G x n = x ^ n.to_add := rfl @[simp] lemma zpowers_hom_symm_apply [group G] (f : multiplicative ℤ →* G) : (zpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : ℕ) : multiples_hom A x n = n • x := rfl attribute [to_additive multiples_hom_apply] powers_hom_apply @[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : ℕ →+ A) : (multiples_hom A).symm f = f 1 := rfl attribute [to_additive multiples_hom_symm_apply] powers_hom_symm_apply @[simp] lemma zmultiples_hom_apply [add_group A] (x : A) (n : ℤ) : zmultiples_hom A x n = n • x := rfl attribute [to_additive zmultiples_hom_apply] zpowers_hom_apply @[simp] lemma zmultiples_hom_symm_apply [add_group A] (f : ℤ →+ A) : (zmultiples_hom A).symm f = f 1 := rfl attribute [to_additive zmultiples_hom_symm_apply] zpowers_hom_symm_apply -- TODO use to_additive in the rest of this file lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mnat [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mnat, g.apply_mnat, h] lemma monoid_hom.apply_mint [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← zpowers_hom_symm_apply, ← zpowers_hom_apply, equiv.apply_symm_apply] /-! `monoid_hom.ext_mint` is defined in `data.int.cast` -/ lemma add_monoid_hom.apply_nat [add_monoid M] (f : ℕ →+ M) (n : ℕ) : f n = n • (f 1) := by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ lemma add_monoid_hom.apply_int [add_group M] (f : ℤ →+ M) (n : ℤ) : f n = n • (f 1) := by rw [← zmultiples_hom_symm_apply, ← zmultiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ variables (M G A) /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative ℕ →* M) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_pow], ..powers_hom M} /-- If `M` is commutative, `zpowers_hom` is a multiplicative equivalence. -/ def zpowers_mul_hom [comm_group G] : G ≃* (multiplicative ℤ →* G) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_zpow], ..zpowers_hom G} /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom [add_comm_monoid A] : A ≃+ (ℕ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [nsmul_add], ..multiples_hom A} /-- If `M` is commutative, `zmultiples_hom` is an additive equivalence. -/ def zmultiples_add_hom [add_comm_group A] : A ≃+ (ℤ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [zsmul_add], ..zmultiples_hom A} variables {M G A} @[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative ℕ) : powers_mul_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative ℕ →* M) : (powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma zpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative ℤ) : zpowers_mul_hom G x n = x ^ n.to_add := rfl @[simp] lemma zpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative ℤ →* G) : (zpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : ℕ) : multiples_add_hom A x n = n • x := rfl @[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : ℕ →+ A) : (multiples_add_hom A).symm f = f 1 := rfl @[simp] lemma zmultiples_add_hom_apply [add_comm_group A] (x : A) (n : ℤ) : zmultiples_add_hom A x n = n • x := rfl @[simp] lemma zmultiples_add_hom_symm_apply [add_comm_group A] (f : ℤ →+ A) : (zmultiples_add_hom A).symm f = f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `zpow` or `zsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp, to_additive] lemma units_zpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [zpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [zpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp, to_additive] lemma units_zpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_zpow_right m @[simp, to_additive] lemma units_zpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_zpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] lemma cast_int_left : commute (m : R) a := by { rw [← mul_one (m : R)], exact (one_left a).cast_int_mul_left m } @[simp] lemma cast_int_right : commute a m := by { rw [← mul_one (m : R)], exact (one_right a).cast_int_mul_right m } @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_zpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [zpow_add, mul_add] {contextual := tt}) (by simp [zpow_add, mul_add, sub_eq_add_neg, -int.add_neg_one] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_zpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n end units namespace opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow [monoid M] (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := rfl @[simp] lemma unop_pow [monoid M] (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := rfl /-- Moving to the opposite group or group_with_zero commutes with taking powers. -/ @[simp] lemma op_zpow [div_inv_monoid M] (x : M) (z : ℤ) : op (x ^ z) = (op x) ^ z := rfl @[simp] lemma unop_zpow [div_inv_monoid M] (x : Mᵒᵖ) (z : ℤ) : unop (x ^ z) = (unop x) ^ z := rfl end opposite
564e57fe96ccc9b573121d3e35f96350c866fb48
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/geometry/manifold/basic_smooth_bundle.lean
29e80ade9963019bbbc0bc56cef7a5cd2b48402d
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
31,947
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.topological_fiber_bundle import geometry.manifold.smooth_manifold_with_corners /-! # Basic smooth bundles In general, a smooth bundle is a bundle over a smooth manifold, whose fiber is a manifold, and for which the coordinate changes are smooth. In this definition, there are charts involved at several places: in the manifold structure of the base, in the manifold structure of the fibers, and in the local trivializations. This makes it a complicated object in general. There is however a specific situation where things are much simpler: when the fiber is a vector space (no need for charts for the fibers), and when the local trivializations of the bundle and the charts of the base coincide. Then everything is expressed in terms of the charts of the base, making for a much simpler overall structure, which is easier to manipulate formally. Most vector bundles that naturally occur in differential geometry are of this form: the tangent bundle, the cotangent bundle, differential forms (used to define de Rham cohomology) and the bundle of Riemannian metrics. Therefore, it is worth defining a specific constructor for this kind of bundle, that we call basic smooth bundles. A basic smooth bundle is thus a smooth bundle over a smooth manifold whose fiber is a vector space, and which is trivial in the coordinate charts of the base. (We recall that in our notion of manifold there is a distinguished atlas, which does not need to be maximal: we require the triviality above this specific atlas). It can be constructed from a basic smooth bundled core, defined below, specifying the changes in the fiber when one goes from one coordinate chart to another one. We do not require that this changes in fiber are linear, but only diffeomorphisms. ## Main definitions * `basic_smooth_bundle_core I M F`: assuming that `M` is a smooth manifold over the model with corners `I` on `(𝕜, E, H)`, and `F` is a normed vector space over `𝕜`, this structure registers, for each pair of charts of `M`, a smooth change of coordinates on `F`. This is the core structure from which one will build a smooth bundle with fiber `F` over `M`. Let `Z` be a basic smooth bundle core over `M` with fiber `F`. We define `Z.to_topological_fiber_bundle_core`, the (topological) fiber bundle core associated to `Z`. From it, we get a space `Z.to_topological_fiber_bundle_core.total_space` (which as a Type is just `Σ (x : M), F`), with the fiber bundle topology. It inherits a manifold structure (where the charts are in bijection with the charts of the basis). We show that this manifold is smooth. Then we use this machinery to construct the tangent bundle of a smooth manifold. * `tangent_bundle_core I M`: the basic smooth bundle core associated to a smooth manifold `M` over a model with corners `I`. * `tangent_bundle I M` : the total space of `tangent_bundle_core I M`. It is itself a smooth manifold over the model with corners `I.tangent`, the product of `I` and the trivial model with corners on `E`. * `tangent_space I x` : the tangent space to `M` at `x` * `tangent_bundle.proj I M`: the projection from the tangent bundle to the base manifold ## Implementation notes In the definition of a basic smooth bundle core, we do not require that the coordinate changes of the fibers are linear map, only that they are diffeomorphisms. Therefore, the fibers of the resulting fiber bundle do not inherit a vector space structure (as an algebraic object) in general. As the fiber, as a type, is just `F`, one can still always register the vector space structure, but it does not make sense to do so (i.e., it will not lead to any useful theorem) unless this structure is canonical, i.e., the coordinate changes are linear maps. For instance, we register the vector space structure on the fibers of the tangent bundle. However, we do not register the normed space structure coming from that of `F` (as it is not canonical, and we also want to keep the possibility to add a Riemannian structure on the manifold later on without having two competing normed space instances on the tangent spaces). We require `F` to be a normed space, and not just a topological vector space, as we want to talk about smooth functions on `F`. The notion of derivative requires a norm to be defined. ## TODO construct the cotangent bundle, and the bundles of differential forms. They should follow functorially from the description of the tangent bundle as a basic smooth bundle. ## Tags Smooth fiber bundle, vector bundle, tangent space, tangent bundle -/ noncomputable theory universe u open topological_space set open_locale manifold topological_space /-- Core structure used to create a smooth bundle above `M` (a manifold over the model with corner `I`) with fiber the normed vector space `F` over `𝕜`, which is trivial in the chart domains of `M`. This structure registers the changes in the fibers when one changes coordinate charts in the base. We do not require the change of coordinates of the fibers to be linear, only smooth. Therefore, the fibers of the resulting bundle will not inherit a canonical vector space structure in general. -/ structure basic_smooth_bundle_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] (F : Type*) [normed_group F] [normed_space 𝕜 F] := (coord_change : atlas H M → atlas H M → H → F → F) (coord_change_self : ∀ i : atlas H M, ∀ x ∈ i.1.target, ∀ v, coord_change i i x v = v) (coord_change_comp : ∀ i j k : atlas H M, ∀ x ∈ ((i.1.symm.trans j.1).trans (j.1.symm.trans k.1)).source, ∀ v, (coord_change j k ((i.1.symm.trans j.1) x)) (coord_change i j x v) = coord_change i k x v) (coord_change_smooth : ∀ i j : atlas H M, times_cont_diff_on 𝕜 ∞ (λp : E × F, coord_change i j (I.symm p.1) p.2) ((I '' (i.1.symm.trans j.1).source).prod (univ : set F))) /-- The trivial basic smooth bundle core, in which all the changes of coordinates are the identity. -/ def trivial_basic_smooth_bundle_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] (F : Type*) [normed_group F] [normed_space 𝕜 F] : basic_smooth_bundle_core I M F := { coord_change := λ i j x v, v, coord_change_self := λ i x hx v, rfl, coord_change_comp := λ i j k x hx v, rfl, coord_change_smooth := λ i j, times_cont_diff_snd.times_cont_diff_on } namespace basic_smooth_bundle_core variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {F : Type*} [normed_group F] [normed_space 𝕜 F] (Z : basic_smooth_bundle_core I M F) instance : inhabited (basic_smooth_bundle_core I M F) := ⟨trivial_basic_smooth_bundle_core I M F⟩ /-- Fiber bundle core associated to a basic smooth bundle core -/ def to_topological_fiber_bundle_core : topological_fiber_bundle_core (atlas H M) M F := { base_set := λi, i.1.source, is_open_base_set := λi, i.1.open_source, index_at := λx, ⟨chart_at H x, chart_mem_atlas H x⟩, mem_base_set_at := λx, mem_chart_source H x, coord_change := λi j x v, Z.coord_change i j (i.1 x) v, coord_change_self := λi x hx v, Z.coord_change_self i (i.1 x) (i.1.map_source hx) v, coord_change_comp := λi j k x ⟨⟨hx1, hx2⟩, hx3⟩ v, begin have := Z.coord_change_comp i j k (i.1 x) _ v, convert this using 2, { simp only [hx1] with mfld_simps }, { simp only [hx1, hx2, hx3] with mfld_simps } end, coord_change_continuous := λi j, begin have A : continuous_on (λp : E × F, Z.coord_change i j (I.symm p.1) p.2) ((I '' (i.1.symm.trans j.1).source).prod (univ : set F)) := (Z.coord_change_smooth i j).continuous_on, have B : continuous_on (λx : M, I (i.1 x)) i.1.source := I.continuous.comp_continuous_on i.1.continuous_on, have C : continuous_on (λp : M × F, (⟨I (i.1 p.1), p.2⟩ : E × F)) (i.1.source.prod univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact B.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, have C' : continuous_on (λp : M × F, (⟨I (i.1 p.1), p.2⟩ : E × F)) ((i.1.source ∩ j.1.source).prod univ) := continuous_on.mono C (prod_mono (inter_subset_left _ _) (subset.refl _)), have D : (i.1.source ∩ j.1.source).prod univ ⊆ (λ (p : M × F), (I (i.1 p.1), p.2)) ⁻¹' ((I '' (i.1.symm.trans j.1).source).prod univ), { rintros ⟨x, v⟩ hx, simp only with mfld_simps at hx, simp only [hx] with mfld_simps }, convert continuous_on.comp A C' D, ext p, simp only with mfld_simps end } @[simp, mfld_simps] lemma base_set (i : atlas H M) : Z.to_topological_fiber_bundle_core.base_set i = i.1.source := rfl /-- Local chart for the total space of a basic smooth bundle -/ def chart {e : local_homeomorph M H} (he : e ∈ atlas H M) : local_homeomorph (Z.to_topological_fiber_bundle_core.total_space) (model_prod H F) := (Z.to_topological_fiber_bundle_core.local_triv ⟨e, he⟩).trans (local_homeomorph.prod e (local_homeomorph.refl F)) @[simp, mfld_simps] lemma chart_source (e : local_homeomorph M H) (he : e ∈ atlas H M) : (Z.chart he).source = Z.to_topological_fiber_bundle_core.proj ⁻¹' e.source := by { simp only [chart, mem_prod], mfld_set_tac } @[simp, mfld_simps] lemma chart_target (e : local_homeomorph M H) (he : e ∈ atlas H M) : (Z.chart he).target = e.target.prod univ := by { simp only [chart], mfld_set_tac } /-- The total space of a basic smooth bundle is endowed with a charted space structure, where the charts are in bijection with the charts of the basis. -/ instance to_charted_space : charted_space (model_prod H F) Z.to_topological_fiber_bundle_core.total_space := { atlas := ⋃(e : local_homeomorph M H) (he : e ∈ atlas H M), {Z.chart he}, chart_at := λp, Z.chart (chart_mem_atlas H p.1), mem_chart_source := λp, by simp [mem_chart_source], chart_mem_atlas := λp, begin simp only [mem_Union, mem_singleton_iff, chart_mem_atlas], exact ⟨chart_at H p.1, chart_mem_atlas H p.1, rfl⟩ end } lemma mem_atlas_iff (f : local_homeomorph Z.to_topological_fiber_bundle_core.total_space (model_prod H F)) : f ∈ atlas (model_prod H F) Z.to_topological_fiber_bundle_core.total_space ↔ ∃(e : local_homeomorph M H) (he : e ∈ atlas H M), f = Z.chart he := by simp only [atlas, mem_Union, mem_singleton_iff] @[simp, mfld_simps] lemma mem_chart_source_iff (p q : Z.to_topological_fiber_bundle_core.total_space) : p ∈ (chart_at (model_prod H F) q).source ↔ p.1 ∈ (chart_at H q.1).source := by simp only [chart_at] with mfld_simps @[simp, mfld_simps] lemma mem_chart_target_iff (p : H × F) (q : Z.to_topological_fiber_bundle_core.total_space) : p ∈ (chart_at (model_prod H F) q).target ↔ p.1 ∈ (chart_at H q.1).target := by simp only [chart_at] with mfld_simps @[simp, mfld_simps] lemma coe_chart_at_fst (p q : Z.to_topological_fiber_bundle_core.total_space) : (((chart_at (model_prod H F) q) : _ → model_prod H F) p).1 = (chart_at H q.1 : _ → H) p.1 := rfl @[simp, mfld_simps] lemma coe_chart_at_symm_fst (p : H × F) (q : Z.to_topological_fiber_bundle_core.total_space) : (((chart_at (model_prod H F) q).symm : model_prod H F → Z.to_topological_fiber_bundle_core.total_space) p).1 = ((chart_at H q.1).symm : H → M) p.1 := rfl /-- Smooth manifold structure on the total space of a basic smooth bundle -/ instance to_smooth_manifold : smooth_manifold_with_corners (I.prod (model_with_corners_self 𝕜 F)) Z.to_topological_fiber_bundle_core.total_space := begin /- We have to check that the charts belong to the smooth groupoid, i.e., they are smooth on their source, and their inverses are smooth on the target. Since both objects are of the same kind, it suffices to prove the first statement in A below, and then glue back the pieces at the end. -/ let J := model_with_corners.to_local_equiv (I.prod (model_with_corners_self 𝕜 F)), have A : ∀ (e e' : local_homeomorph M H) (he : e ∈ atlas H M) (he' : e' ∈ atlas H M), times_cont_diff_on 𝕜 ∞ (J ∘ ((Z.chart he).symm.trans (Z.chart he')) ∘ J.symm) (J.symm ⁻¹' ((Z.chart he).symm.trans (Z.chart he')).source ∩ range J), { assume e e' he he', have : J.symm ⁻¹' ((chart Z he).symm.trans (chart Z he')).source ∩ range J = (I.symm ⁻¹' (e.symm.trans e').source ∩ range I).prod univ, by { simp only [J, chart, model_with_corners.prod], mfld_set_tac }, rw this, -- check separately that the two components of the coordinate change are smooth apply times_cont_diff_on.prod, show times_cont_diff_on 𝕜 ∞ (λ (p : E × F), (I ∘ e' ∘ e.symm ∘ I.symm) p.1) ((I.symm ⁻¹' (e.symm.trans e').source ∩ range I).prod (univ : set F)), { -- the coordinate change on the base is just a coordinate change for `M`, smooth since -- `M` is smooth have A : times_cont_diff_on 𝕜 ∞ (I ∘ (e.symm.trans e') ∘ I.symm) (I.symm ⁻¹' (e.symm.trans e').source ∩ range I) := (has_groupoid.compatible (times_cont_diff_groupoid ∞ I) he he').1, have B : times_cont_diff_on 𝕜 ∞ (λp : E × F, p.1) ((I.symm ⁻¹' (e.symm.trans e').source ∩ range I).prod univ) := times_cont_diff_fst.times_cont_diff_on, exact times_cont_diff_on.comp A B (prod_subset_preimage_fst _ _) }, show times_cont_diff_on 𝕜 ∞ (λ (p : E × F), Z.coord_change ⟨chart_at H (e.symm (I.symm p.1)), _⟩ ⟨e', he'⟩ ((chart_at H (e.symm (I.symm p.1)) : M → H) (e.symm (I.symm p.1))) (Z.coord_change ⟨e, he⟩ ⟨chart_at H (e.symm (I.symm p.1)), _⟩ (e (e.symm (I.symm p.1))) p.2)) ((I.symm ⁻¹' (e.symm.trans e').source ∩ range I).prod (univ : set F)), { /- The coordinate change in the fiber is more complicated as its definition involves the reference chart chosen at each point. However, it appears with its inverse, so using the cocycle property one can get rid of it, and then conclude using the smoothness of the cocycle as given in the definition of basic smooth bundles. -/ have := Z.coord_change_smooth ⟨e, he⟩ ⟨e', he'⟩, rw I.image_eq at this, apply times_cont_diff_on.congr this, rintros ⟨x, v⟩ hx, simp only with mfld_simps at hx, let f := chart_at H (e.symm (I.symm x)), have A : I.symm x ∈ ((e.symm.trans f).trans (f.symm.trans e')).source, by simp only [hx.1.1, hx.1.2] with mfld_simps, rw e.right_inv hx.1.1, have := Z.coord_change_comp ⟨e, he⟩ ⟨f, chart_mem_atlas _ _⟩ ⟨e', he'⟩ (I.symm x) A v, simpa only [] using this } }, constructor, assume e₀ e₀' he₀ he₀', rcases (Z.mem_atlas_iff _).1 he₀ with ⟨e, he, rfl⟩, rcases (Z.mem_atlas_iff _).1 he₀' with ⟨e', he', rfl⟩, rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid], exact ⟨A e e' he he', A e' e he' he⟩ end end basic_smooth_bundle_core section tangent_bundle variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] /-- Basic smooth bundle core version of the tangent bundle of a smooth manifold `M` modelled over a model with corners `I` on `(E, H)`. The fibers are equal to `E`, and the coordinate change in the fiber corresponds to the derivative of the coordinate change in `M`. -/ def tangent_bundle_core : basic_smooth_bundle_core I M E := { coord_change := λi j x v, (fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (range I) (I x) : E → E) v, coord_change_smooth := λi j, begin /- To check that the coordinate change of the bundle is smooth, one should just use the smoothness of the charts, and thus the smoothness of their derivatives. -/ rw I.image_eq, have A : times_cont_diff_on 𝕜 ∞ (I ∘ (i.1.symm.trans j.1) ∘ I.symm) (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) := (has_groupoid.compatible (times_cont_diff_groupoid ∞ I) i.2 j.2).1, have B : unique_diff_on 𝕜 (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) := I.unique_diff_preimage_source, have C : times_cont_diff_on 𝕜 ∞ (λ (p : E × E), (fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) p.1 : E → E) p.2) ((I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I).prod univ) := times_cont_diff_on_fderiv_within_apply A B le_top, have D : ∀ x ∈ (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I), fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (range I) x = fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) x, { assume x hx, have N : I.symm ⁻¹' (i.1.symm.trans j.1).source ∈ nhds x := I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) hx.1), symmetry, rw inter_comm, exact fderiv_within_inter N (I.unique_diff _ hx.2) }, apply times_cont_diff_on.congr C, rintros ⟨x, v⟩ hx, have E : x ∈ I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I, by simpa only [prod_mk_mem_set_prod_eq, and_true, mem_univ] using hx, have : I (I.symm x) = x, by simp [E.2], dsimp [-subtype.val_eq_coe], rw [this, D x E], refl end, coord_change_self := λi x hx v, begin /- Locally, a self-change of coordinate is just the identity, thus its derivative is the identity. One just needs to write this carefully, paying attention to the sets where the functions are defined. -/ have A : I.symm ⁻¹' (i.1.symm.trans i.1).source ∩ range I ∈ 𝓝[range I] (I x), { rw inter_comm, apply inter_mem_nhds_within, apply I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simp only [hx, i.1.map_target] with mfld_simps }, have B : ∀ᶠ y in 𝓝[range I] (I x), (I ∘ i.1 ∘ i.1.symm ∘ I.symm) y = (id : E → E) y, { filter_upwards [A], assume y hy, rw ← I.image_eq at hy, rcases hy with ⟨z, hz⟩, simp only with mfld_simps at hz, simp only [hz.2.symm, hz.1] with mfld_simps }, have C : fderiv_within 𝕜 (I ∘ i.1 ∘ i.1.symm ∘ I.symm) (range I) (I x) = fderiv_within 𝕜 (id : E → E) (range I) (I x) := filter.eventually_eq.fderiv_within_eq I.unique_diff_at_image B (by simp only [hx] with mfld_simps), rw fderiv_within_id I.unique_diff_at_image at C, rw C, refl end, coord_change_comp := λi j u x hx, begin /- The cocycle property is just the fact that the derivative of a composition is the product of the derivatives. One needs however to check that all the functions one considers are smooth, and to pay attention to the domains where these functions are defined, making this proof a little bit cumbersome although there is nothing complicated here. -/ have M : I x ∈ (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) := ⟨by simpa only [mem_preimage, model_with_corners.left_inv] using hx, mem_range_self _⟩, have U : unique_diff_within_at 𝕜 (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) := I.unique_diff_preimage_source _ M, have A : fderiv_within 𝕜 ((I ∘ u.1 ∘ j.1.symm ∘ I.symm) ∘ (I ∘ j.1 ∘ i.1.symm ∘ I.symm)) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) = (fderiv_within 𝕜 (I ∘ u.1 ∘ j.1.symm ∘ I.symm) (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I) ((I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I x))).comp (fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x)), { apply fderiv_within.comp _ _ _ _ U, show differentiable_within_at 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x), { have A : times_cont_diff_on 𝕜 ∞ (I ∘ (i.1.symm.trans j.1) ∘ I.symm) (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) := (has_groupoid.compatible (times_cont_diff_groupoid ∞ I) i.2 j.2).1, have B : differentiable_on 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I), { apply (A.differentiable_on le_top).mono, have : ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ⊆ (i.1.symm.trans j.1).source := inter_subset_left _ _, exact inter_subset_inter (preimage_mono this) (subset.refl (range I)) }, apply B, simpa only [] with mfld_simps using hx }, show differentiable_within_at 𝕜 (I ∘ u.1 ∘ j.1.symm ∘ I.symm) (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I) ((I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I x)), { have A : times_cont_diff_on 𝕜 ∞ (I ∘ (j.1.symm.trans u.1) ∘ I.symm) (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I) := (has_groupoid.compatible (times_cont_diff_groupoid ∞ I) j.2 u.2).1, apply A.differentiable_on le_top, rw [local_homeomorph.trans_source] at hx, simp only with mfld_simps, exact hx.2 }, show (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) ⊆ (I ∘ j.1 ∘ i.1.symm ∘ I.symm) ⁻¹' (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I), { assume y hy, simp only with mfld_simps at hy, rw [local_homeomorph.left_inv] at hy, { simp only [hy] with mfld_simps }, { exact hy.1.1.2 } } }, have B : fderiv_within 𝕜 ((I ∘ u.1 ∘ j.1.symm ∘ I.symm) ∘ (I ∘ j.1 ∘ i.1.symm ∘ I.symm)) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) = fderiv_within 𝕜 (I ∘ u.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x), { have E : ∀ y ∈ (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I), ((I ∘ u.1 ∘ j.1.symm ∘ I.symm) ∘ (I ∘ j.1 ∘ i.1.symm ∘ I.symm)) y = (I ∘ u.1 ∘ i.1.symm ∘ I.symm) y, { assume y hy, simp only [function.comp_app, model_with_corners.left_inv], rw [j.1.left_inv], exact hy.1.1.2 }, exact fderiv_within_congr U E (E _ M) }, have C : fderiv_within 𝕜 (I ∘ u.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) = fderiv_within 𝕜 (I ∘ u.1 ∘ i.1.symm ∘ I.symm) (range I) (I x), { rw inter_comm, apply fderiv_within_inter _ I.unique_diff_at_image, apply I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simpa only [model_with_corners.left_inv] using hx }, have D : fderiv_within 𝕜 (I ∘ u.1 ∘ j.1.symm ∘ I.symm) (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I) ((I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I x)) = fderiv_within 𝕜 (I ∘ u.1 ∘ j.1.symm ∘ I.symm) (range I) ((I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I x)), { rw inter_comm, apply fderiv_within_inter _ I.unique_diff_at_image, apply I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), rw [local_homeomorph.trans_source] at hx, simp only with mfld_simps, exact hx.2 }, have E : fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) = fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (range I) (I x), { rw inter_comm, apply fderiv_within_inter _ I.unique_diff_at_image, apply I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simpa only [model_with_corners.left_inv] using hx }, rw [B, C, D, E] at A, simp only [A, continuous_linear_map.coe_comp'] with mfld_simps end } variable {M} include I /-- The tangent space at a point of the manifold `M`. It is just `E`. We could use instead `(tangent_bundle_core I M).to_topological_fiber_bundle_core.fiber x`, but we use `E` to help the kernel. -/ @[nolint unused_arguments] def tangent_space (x : M) : Type* := E omit I variable (M) /-- The tangent bundle to a smooth manifold, as a plain type. We could use `(tangent_bundle_core I M).to_topological_fiber_bundle_core.total_space`, but instead we use the (definitionally equal) `Σ (x : M), tangent_space I x`, to make sure that rcasing an element of the tangent bundle gives a second component in the tangent space. -/ @[nolint has_inhabited_instance, reducible] -- is empty if the base manifold is empty def tangent_bundle := Σ (x : M), tangent_space I x /-- The projection from the tangent bundle of a smooth manifold to the manifold. As the tangent bundle is represented internally as a product type, the notation `p.1` also works for the projection of the point `p`. -/ def tangent_bundle.proj : tangent_bundle I M → M := λ p, p.1 variable {M} @[simp, mfld_simps] lemma tangent_bundle.proj_apply (x : M) (v : tangent_space I x) : tangent_bundle.proj I M ⟨x, v⟩ = x := rfl section tangent_bundle_instances /- In general, the definition of tangent_bundle and tangent_space are not reducible, so that type class inference does not pick wrong instances. In this section, we record the right instances for them, noting in particular that the tangent bundle is a smooth manifold. -/ variable (M) instance : topological_space (tangent_bundle I M) := (tangent_bundle_core I M).to_topological_fiber_bundle_core.to_topological_space instance : charted_space (model_prod H E) (tangent_bundle I M) := (tangent_bundle_core I M).to_charted_space instance : smooth_manifold_with_corners I.tangent (tangent_bundle I M) := (tangent_bundle_core I M).to_smooth_manifold local attribute [reducible] tangent_space variables {M} (x : M) instance : topological_module 𝕜 (tangent_space I x) := by apply_instance instance : topological_space (tangent_space I x) := by apply_instance instance : add_comm_group (tangent_space I x) := by apply_instance instance : topological_add_group (tangent_space I x) := by apply_instance instance : vector_space 𝕜 (tangent_space I x) := by apply_instance instance : inhabited (tangent_space I x) := ⟨0⟩ end tangent_bundle_instances variable (M) /-- The tangent bundle projection on the basis is a continuous map. -/ lemma tangent_bundle_proj_continuous : continuous (tangent_bundle.proj I M) := topological_fiber_bundle_core.continuous_proj _ /-- The tangent bundle projection on the basis is an open map. -/ lemma tangent_bundle_proj_open : is_open_map (tangent_bundle.proj I M) := topological_fiber_bundle_core.is_open_map_proj _ /-- In the tangent bundle to the model space, the charts are just the canonical identification between a product type and a sigma type, a.k.a. `equiv.sigma_equiv_prod`. -/ @[simp, mfld_simps] lemma tangent_bundle_model_space_chart_at (p : tangent_bundle I H) : (chart_at (model_prod H E) p).to_local_equiv = (equiv.sigma_equiv_prod H E).to_local_equiv := begin have A : ∀ x_fst, fderiv_within 𝕜 (I ∘ I.symm) (range I) (I x_fst) = continuous_linear_map.id 𝕜 E, { assume x_fst, have : fderiv_within 𝕜 (I ∘ I.symm) (range I) (I x_fst) = fderiv_within 𝕜 id (range I) (I x_fst), { refine fderiv_within_congr I.unique_diff_at_image (λy hy, _) (by simp), exact model_with_corners.right_inv _ hy }, rwa fderiv_within_id I.unique_diff_at_image at this }, ext x : 1, show (chart_at (model_prod H E) p : tangent_bundle I H → model_prod H E) x = (equiv.sigma_equiv_prod H E) x, { cases x, simp only [chart_at, basic_smooth_bundle_core.chart, tangent_bundle_core, basic_smooth_bundle_core.to_topological_fiber_bundle_core, A, prod.mk.inj_iff, continuous_linear_map.coe_id'] with mfld_simps, }, show ∀ x, ((chart_at (model_prod H E) p).to_local_equiv).symm x = (equiv.sigma_equiv_prod H E).symm x, { rintros ⟨x_fst, x_snd⟩, simp only [chart_at, basic_smooth_bundle_core.chart, tangent_bundle_core, continuous_linear_map.coe_id', basic_smooth_bundle_core.to_topological_fiber_bundle_core, A] with mfld_simps}, show ((chart_at (model_prod H E) p).to_local_equiv).source = univ, by simp only [chart_at] with mfld_simps, end @[simp, mfld_simps] lemma tangent_bundle_model_space_coe_chart_at (p : tangent_bundle I H) : (chart_at (model_prod H E) p : tangent_bundle I H → model_prod H E) = equiv.sigma_equiv_prod H E := by { unfold_coes, simp only with mfld_simps } @[simp, mfld_simps] lemma tangent_bundle_model_space_coe_chart_at_symm (p : tangent_bundle I H) : ((chart_at (model_prod H E) p).symm : model_prod H E → tangent_bundle I H) = (equiv.sigma_equiv_prod H E).symm := by { unfold_coes, simp only with mfld_simps } variable (H) /-- The canonical identification between the tangent bundle to the model space and the product, as a homeomorphism -/ def tangent_bundle_model_space_homeomorph : tangent_bundle I H ≃ₜ model_prod H E := { continuous_to_fun := begin let p : tangent_bundle I H := ⟨I.symm (0 : E), (0 : E)⟩, have : continuous (chart_at (model_prod H E) p), { rw continuous_iff_continuous_on_univ, convert local_homeomorph.continuous_on _, simp only with mfld_simps }, simpa only with mfld_simps using this, end, continuous_inv_fun := begin let p : tangent_bundle I H := ⟨I.symm (0 : E), (0 : E)⟩, have : continuous (chart_at (model_prod H E) p).symm, { rw continuous_iff_continuous_on_univ, convert local_homeomorph.continuous_on _, simp only with mfld_simps }, simpa only with mfld_simps using this, end, .. equiv.sigma_equiv_prod H E } @[simp, mfld_simps] lemma tangent_bundle_model_space_homeomorph_coe : (tangent_bundle_model_space_homeomorph H I : tangent_bundle I H → model_prod H E) = equiv.sigma_equiv_prod H E := rfl @[simp, mfld_simps] lemma tangent_bundle_model_space_homeomorph_coe_symm : ((tangent_bundle_model_space_homeomorph H I).symm : model_prod H E → tangent_bundle I H) = (equiv.sigma_equiv_prod H E).symm := rfl end tangent_bundle
6440cb35edc20b7e0478110d300251157f53d8e3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1235.lean
b9e0f4b994b643f01a78c4e006a58d205794c944
[ "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
160
lean
opaque f (a b : Nat) : Nat example : f 1 2 = f 2 1 := by generalize h : f 1 = g /- g : ℕ → ℕ h : f 1 = g ⊢ g 2 = f 2 1 -/ trace_state sorry
96b372174b40c12c2580af62c3c18064d247de7c
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/foldConsts.lean
ba00314037152930efc7f80cc2cee53fbc8ad013
[ "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
279
lean
import Init.Lean open Lean def mkTerm : Nat → Expr | 0 => mkApp (mkConst `a) (mkConst `b) | n+1 => mkApp (mkTerm n) (mkTerm n) def collectConsts (e : Expr) : List Name := e.foldConsts [] List.cons def tst1 : IO Unit := IO.println $ collectConsts (mkTerm 1000) #eval tst1
027c4a7c7a2b59e2d9a24e925319e872a6e75fb4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/bench/binarytrees.st.lean
f28a73e3affe05f2f9e3ef315607a8a8c708721d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,405
lean
inductive Tree | nil | node (l r : Tree) instance : Inhabited Tree := ⟨.nil⟩ -- This function has an extra argument to suppress the -- common sub-expression elimination optimization partial def make' (n d : UInt32) : Tree := if d = 0 then .node .nil .nil else .node (make' n (d - 1)) (make' (n + 1) (d - 1)) -- build a tree def make (d : UInt32) := make' d d def check : Tree → UInt32 | .nil => 0 | .node l r => 1 + check l + check r def minN := 4 def out (s : String) (n : Nat) (t : UInt32) : IO Unit := IO.println s!"{s} of depth {n}\t check: {t}" -- allocate and check lots of trees partial def sumT (d i t : UInt32) : UInt32 := if i = 0 then t else let a := check (make d) sumT d (i-1) (t + a) def main : List String → IO UInt32 | [s] => do let n := s.toNat! let maxN := Nat.max (minN + 2) n let stretchN := maxN + 1 -- stretch memory tree let c := check (make $ UInt32.ofNat stretchN) out "stretch tree" stretchN c -- allocate a long lived tree let long := make $ UInt32.ofNat maxN -- allocate, walk, and deallocate many bottom-up binary trees for d in [minN:maxN+1:2] do let n := 2 ^ (maxN - d + minN) let i := sumT (.ofNat d) (.ofNat n) 0 out s!"{n}\t trees" d i -- confirm the long-lived binary tree still exists out "long lived tree" maxN (check long) return 0 | _ => return 1
1908ce06c9c6966ebee45c22ae2d0b125a954654
0003047346476c031128723dfd16fe273c6bc605
/src/algebra/group.lean
802b56e4471525535097fd7da74f0384b52d10ce
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,949
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Various multiplicative and additive structures. -/ import tactic.interactive data.option.defs section pending_1857 /- Transport multiplicative to additive -/ section transport open tactic @[user_attribute] meta def to_additive_attr : user_attribute (name_map name) name := { name := `to_additive, descr := "Transport multiplicative to additive", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do val ← to_additive_attr.get_param n, pure $ dict.insert n val) mk_name_map, []⟩, parser := lean.parser.ident, after_set := some $ λ src _ _, do env ← get_env, dict ← to_additive_attr.get_cache, tgt ← to_additive_attr.get_param src, (get_decl tgt >> skip) <|> transport_with_dict dict src tgt } end transport /- map operations -/ attribute [to_additive has_add.add] has_mul.mul attribute [to_additive has_zero.zero] has_one.one attribute [to_additive has_neg.neg] has_inv.inv attribute [to_additive has_add] has_mul attribute [to_additive has_zero] has_one attribute [to_additive has_neg] has_inv /- map constructors -/ attribute [to_additive has_add.mk] has_mul.mk attribute [to_additive has_zero.mk] has_one.mk attribute [to_additive has_neg.mk] has_inv.mk /- map structures -/ attribute [to_additive add_semigroup] semigroup attribute [to_additive add_semigroup.mk] semigroup.mk attribute [to_additive add_semigroup.to_has_add] semigroup.to_has_mul attribute [to_additive add_semigroup.add_assoc] semigroup.mul_assoc attribute [to_additive add_semigroup.add] semigroup.mul attribute [to_additive add_comm_semigroup] comm_semigroup attribute [to_additive add_comm_semigroup.mk] comm_semigroup.mk attribute [to_additive add_comm_semigroup.to_add_semigroup] comm_semigroup.to_semigroup attribute [to_additive add_comm_semigroup.add_comm] comm_semigroup.mul_comm attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup attribute [to_additive add_left_cancel_semigroup.mk] left_cancel_semigroup.mk attribute [to_additive add_left_cancel_semigroup.to_add_semigroup] left_cancel_semigroup.to_semigroup attribute [to_additive add_left_cancel_semigroup.add_left_cancel] left_cancel_semigroup.mul_left_cancel attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup attribute [to_additive add_right_cancel_semigroup.mk] right_cancel_semigroup.mk attribute [to_additive add_right_cancel_semigroup.to_add_semigroup] right_cancel_semigroup.to_semigroup attribute [to_additive add_right_cancel_semigroup.add_right_cancel] right_cancel_semigroup.mul_right_cancel attribute [to_additive add_monoid] monoid attribute [to_additive add_monoid.mk] monoid.mk attribute [to_additive add_monoid.to_has_zero] monoid.to_has_one attribute [to_additive add_monoid.to_add_semigroup] monoid.to_semigroup attribute [to_additive add_monoid.add] monoid.mul attribute [to_additive add_monoid.add_assoc] monoid.mul_assoc attribute [to_additive add_monoid.zero] monoid.one attribute [to_additive add_monoid.zero_add] monoid.one_mul attribute [to_additive add_monoid.add_zero] monoid.mul_one attribute [to_additive add_comm_monoid] comm_monoid attribute [to_additive add_comm_monoid.mk] comm_monoid.mk attribute [to_additive add_comm_monoid.to_add_monoid] comm_monoid.to_monoid attribute [to_additive add_comm_monoid.to_add_comm_semigroup] comm_monoid.to_comm_semigroup attribute [to_additive add_group] group attribute [to_additive add_group.mk] group.mk attribute [to_additive add_group.to_has_neg] group.to_has_inv attribute [to_additive add_group.to_add_monoid] group.to_monoid attribute [to_additive add_group.add_left_neg] group.mul_left_inv attribute [to_additive add_group.add] group.mul attribute [to_additive add_group.add_assoc] group.mul_assoc attribute [to_additive add_group.zero] group.one attribute [to_additive add_group.zero_add] group.one_mul attribute [to_additive add_group.add_zero] group.mul_one attribute [to_additive add_group.neg] group.inv attribute [to_additive add_comm_group] comm_group attribute [to_additive add_comm_group.mk] comm_group.mk attribute [to_additive add_comm_group.to_add_group] comm_group.to_group attribute [to_additive add_comm_group.to_add_comm_monoid] comm_group.to_comm_monoid /- map theorems -/ attribute [to_additive add_assoc] mul_assoc attribute [to_additive add_semigroup_to_is_associative] semigroup_to_is_associative attribute [to_additive add_comm] mul_comm attribute [to_additive add_comm_semigroup_to_is_commutative] comm_semigroup_to_is_commutative attribute [to_additive add_left_comm] mul_left_comm attribute [to_additive add_right_comm] mul_right_comm attribute [to_additive add_left_cancel] mul_left_cancel attribute [to_additive add_right_cancel] mul_right_cancel attribute [to_additive add_left_cancel_iff] mul_left_cancel_iff attribute [to_additive add_right_cancel_iff] mul_right_cancel_iff attribute [to_additive zero_add] one_mul attribute [to_additive add_zero] mul_one attribute [to_additive add_left_neg] mul_left_inv attribute [to_additive neg_add_self] inv_mul_self attribute [to_additive neg_add_cancel_left] inv_mul_cancel_left attribute [to_additive neg_add_cancel_right] inv_mul_cancel_right attribute [to_additive neg_eq_of_add_eq_zero] inv_eq_of_mul_eq_one attribute [to_additive neg_zero] one_inv attribute [to_additive neg_neg] inv_inv attribute [to_additive add_right_neg] mul_right_inv attribute [to_additive add_neg_self] mul_inv_self attribute [to_additive neg_inj] inv_inj attribute [to_additive add_group.add_left_cancel] group.mul_left_cancel attribute [to_additive add_group.add_right_cancel] group.mul_right_cancel attribute [to_additive add_group.to_left_cancel_add_semigroup] group.to_left_cancel_semigroup attribute [to_additive add_group.to_right_cancel_add_semigroup] group.to_right_cancel_semigroup attribute [to_additive add_neg_cancel_left] mul_inv_cancel_left attribute [to_additive add_neg_cancel_right] mul_inv_cancel_right attribute [to_additive neg_add_rev] mul_inv_rev attribute [to_additive eq_neg_of_eq_neg] eq_inv_of_eq_inv attribute [to_additive eq_neg_of_add_eq_zero] eq_inv_of_mul_eq_one attribute [to_additive eq_add_neg_of_add_eq] eq_mul_inv_of_mul_eq attribute [to_additive eq_neg_add_of_add_eq] eq_inv_mul_of_mul_eq attribute [to_additive neg_add_eq_of_eq_add] inv_mul_eq_of_eq_mul attribute [to_additive add_neg_eq_of_eq_add] mul_inv_eq_of_eq_mul attribute [to_additive eq_add_of_add_neg_eq] eq_mul_of_mul_inv_eq attribute [to_additive eq_add_of_neg_add_eq] eq_mul_of_inv_mul_eq attribute [to_additive add_eq_of_eq_neg_add] mul_eq_of_eq_inv_mul attribute [to_additive add_eq_of_eq_add_neg] mul_eq_of_eq_mul_inv attribute [to_additive neg_add] mul_inv end pending_1857 instance monoid_to_is_left_id {α : Type*} [monoid α] : is_left_id α (*) 1 := ⟨ monoid.one_mul ⟩ instance monoid_to_is_right_id {α : Type*} [monoid α] : is_right_id α (*) 1 := ⟨ monoid.mul_one ⟩ instance add_monoid_to_is_left_id {α : Type*} [add_monoid α] : is_left_id α (+) 0 := ⟨ add_monoid.zero_add ⟩ instance add_monoid_to_is_right_id {α : Type*} [add_monoid α] : is_right_id α (+) 0 := ⟨ add_monoid.add_zero ⟩ universes u v variables {α : Type u} {β : Type v} def additive (α : Type*) := α def multiplicative (α : Type*) := α instance [semigroup α] : add_semigroup (additive α) := { add := ((*) : α → α → α), add_assoc := @mul_assoc _ _ } instance [add_semigroup α] : semigroup (multiplicative α) := { mul := ((+) : α → α → α), mul_assoc := @add_assoc _ _ } instance [comm_semigroup α] : add_comm_semigroup (additive α) := { add_comm := @mul_comm _ _, ..additive.add_semigroup } instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) := { mul_comm := @add_comm _ _, ..multiplicative.semigroup } instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) := { add_left_cancel := @mul_left_cancel _ _, ..additive.add_semigroup } instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) := { mul_left_cancel := @add_left_cancel _ _, ..multiplicative.semigroup } instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) := { add_right_cancel := @mul_right_cancel _ _, ..additive.add_semigroup } instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) := { mul_right_cancel := @add_right_cancel _ _, ..multiplicative.semigroup } @[simp, to_additive add_left_inj] theorem mul_left_inj [left_cancel_semigroup α] (a : α) {b c : α} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ @[simp, to_additive add_right_inj] theorem mul_right_inj [right_cancel_semigroup α] (a : α) {b c : α} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) namespace units variables [monoid α] {a b c : units α} instance : has_coe (units α) α := ⟨val⟩ @[extensionality] theorem ext : ∀ {a b : units α}, (a : α) = b → a = b | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := ⟨congr_arg _, ext⟩ instance [decidable_eq α] : decidable_eq (units α) | a b := decidable_of_iff' _ ext_iff protected def mul (u₁ u₂ : units α) : units α := ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, have u₁.val * (u₂.val * u₂.inv) * u₁.inv = 1, by rw [u₂.val_inv]; rw [mul_one, u₁.val_inv], by simpa only [mul_assoc], have u₂.inv * (u₁.inv * u₁.val) * u₂.val = 1, by rw [u₁.inv_val]; rw [mul_one, u₂.inv_val], by simpa only [mul_assoc]⟩ protected def inv' (u : units α) : units α := ⟨u.inv, u.val, u.inv_val, u.val_inv⟩ instance : has_mul (units α) := ⟨units.mul⟩ instance : has_one (units α) := ⟨⟨1, 1, mul_one 1, one_mul 1⟩⟩ instance : has_inv (units α) := ⟨units.inv'⟩ variables (a b) @[simp] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp] lemma coe_one : ((1 : units α) : α) = 1 := rfl lemma val_coe : (↑a : α) = a.val := rfl lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl @[simp] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[simp] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] instance : group (units α) := by refine {mul := (*), one := 1, inv := has_inv.inv, ..}; { intros, apply ext, simp only [coe_mul, coe_one, mul_assoc, one_mul, mul_one, inv_mul] } instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp] theorem mul_left_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp] theorem mul_right_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ end units theorem nat.units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ instance [monoid α] : add_monoid (additive α) := { zero := (1 : α), zero_add := @one_mul _ _, add_zero := @mul_one _ _, ..additive.add_semigroup } instance [add_monoid α] : monoid (multiplicative α) := { one := (0 : α), one_mul := @zero_add _ _, mul_one := @add_zero _ _, ..multiplicative.semigroup } def free_monoid (α) := list α 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 } @[simp] lemma free_monoid.one_def {α} : (1 : free_monoid α) = [] := rfl @[simp] lemma free_monoid.mul_def {α} (xs ys : list α) : (xs * ys : free_monoid α) = (xs ++ ys : list α) := rfl def free_add_monoid (α) := list α instance {α} : add_monoid (free_add_monoid α) := { zero := [], add := λ x y, (x ++ y : list α), add_zero := by intros; apply list.append_nil, zero_add := by intros; refl, add_assoc := by intros; apply list.append_assoc } @[simp] lemma free_add_monoid.zero_def {α} : (1 : free_monoid α) = [] := rfl @[simp] lemma free_add_monoid.add_def {α} (xs ys : list α) : (xs * ys : free_monoid α) = (xs ++ ys : list α) := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_right_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_right_inj _ theorem divp_eq_one (a : α) (u : units α) : a /ₚ u = 1 ↔ a = u := (units.mul_right_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid instance [comm_monoid α] : add_comm_monoid (additive α) := { add_comm := @mul_comm α _, ..additive.add_monoid } instance [add_comm_monoid α] : comm_monoid (multiplicative α) := { mul_comm := @add_comm α _, ..multiplicative.monoid } instance [group α] : add_group (additive α) := { neg := @has_inv.inv α _, add_left_neg := @mul_left_inv _ _, ..additive.add_monoid } instance [add_group α] : group (multiplicative α) := { inv := @has_neg.neg α _, mul_left_inv := @add_left_neg _ _, ..multiplicative.monoid } section group variables [group α] {a b c : α} instance : has_lift α (units α) := ⟨λ a, ⟨a, a⁻¹, mul_inv_self _, inv_mul_self _⟩⟩ @[simp, to_additive neg_inj'] theorem inv_inj' : a⁻¹ = b⁻¹ ↔ a = b := ⟨λ h, by rw [← inv_inv a, h, inv_inv], congr_arg _⟩ @[to_additive eq_of_neg_eq_neg] theorem eq_of_inv_eq_inv : a⁻¹ = b⁻¹ → a = b := inv_inj'.1 @[simp, to_additive add_self_iff_eq_zero] theorem mul_self_iff_eq_one : a * a = a ↔ a = 1 := by have := @mul_left_inj _ _ a a 1; rwa mul_one at this @[simp, to_additive neg_eq_zero] theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 := by rw [← @inv_inj' _ _ a 1, one_inv] @[simp, to_additive neg_ne_zero] theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 := not_congr inv_eq_one @[to_additive left_inverse_neg] theorem left_inverse_inv (α) [group α] : function.left_inverse (λ a : α, a⁻¹) (λ a, a⁻¹) := assume a, inv_inv a attribute [simp] mul_inv_cancel_left add_neg_cancel_left mul_inv_cancel_right add_neg_cancel_right @[to_additive eq_neg_iff_eq_neg] theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ := ⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩ @[to_additive neg_eq_iff_neg_eq] theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a := by rw [eq_comm, @eq_comm _ _ a, eq_inv_iff_eq_inv] @[to_additive add_eq_zero_iff_eq_neg] theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ := by simpa [mul_left_inv, -mul_right_inj] using @mul_right_inj _ _ b a (b⁻¹) @[to_additive add_eq_zero_iff_neg_eq] theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b := by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm] @[to_additive eq_neg_iff_add_eq_zero] theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 := mul_eq_one_iff_eq_inv.symm @[to_additive neg_eq_iff_add_eq_zero] theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 := mul_eq_one_iff_inv_eq.symm @[to_additive eq_add_neg_iff_add_eq] theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive eq_neg_add_iff_add_eq] theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive neg_add_eq_iff_eq_add] theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive add_neg_eq_iff_eq_add] theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ @[to_additive add_neg_eq_zero] theorem mul_inv_eq_one {a b : α} : a * b⁻¹ = 1 ↔ a = b := by rw [mul_eq_one_iff_eq_inv, inv_inv] @[to_additive neg_comm_of_comm] theorem inv_comm_of_comm {a b : α} (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm, rwa [inv_mul_cancel_left, mul_assoc, mul_inv_cancel_right] at this end end group instance [comm_group α] : add_comm_group (additive α) := { add_comm := @mul_comm α _, ..additive.add_group } instance [add_comm_group α] : comm_group (multiplicative α) := { mul_comm := @add_comm α _, ..multiplicative.group } section add_monoid variables [add_monoid α] {a b c : α} @[simp] lemma bit0_zero : bit0 (0 : α) = 0 := add_zero _ @[simp] lemma bit1_zero [has_one α] : bit1 (0 : α) = 1 := show 0+0+1=(1:α), by rw [zero_add, zero_add] end add_monoid section add_group variables [add_group α] {a b c : α} local attribute [simp] sub_eq_add_neg def sub_sub_cancel := @sub_sub_self @[simp] lemma sub_left_inj : a - b = a - c ↔ b = c := (add_left_inj _).trans neg_inj' @[simp] lemma sub_right_inj : b - a = c - a ↔ b = c := add_right_inj _ lemma sub_add_sub_cancel (a b c : α) : (a - b) + (b - c) = a - c := by rw [← add_sub_assoc, sub_add_cancel] lemma sub_sub_sub_cancel_right (a b c : α) : (a - c) - (b - c) = a - b := by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel] theorem sub_eq_zero : a - b = 0 ↔ a = b := ⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩ theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b := not_congr sub_eq_zero theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b := eq_add_neg_iff_add_eq theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b := add_neg_eq_iff_eq_add theorem eq_iff_eq_of_sub_eq_sub {a b c d : α} (H : a - b = c - d) : a = b ↔ c = d := by rw [← sub_eq_zero, H, sub_eq_zero] theorem left_inverse_sub_add_left (c : α) : function.left_inverse (λ x, x - c) (λ x, x + c) := assume x, add_sub_cancel x c theorem left_inverse_add_left_sub (c : α) : function.left_inverse (λ x, x + c) (λ x, x - c) := assume x, sub_add_cancel x c theorem left_inverse_add_right_neg_add (c : α) : function.left_inverse (λ x, c + x) (λ x, - c + x) := assume x, add_neg_cancel_left c x theorem left_inverse_neg_add_add_right (c : α) : function.left_inverse (λ x, - c + x) (λ x, c + x) := assume x, neg_add_cancel_left c x end add_group section add_comm_group variables [add_comm_group α] {a b c : α} lemma sub_eq_neg_add (a b : α) : a - b = -b + a := add_comm _ _ theorem neg_add' (a b : α) : -(a + b) = -a - b := neg_add a b lemma neg_sub_neg (a b : α) : -a - -b = b - a := by simp lemma eq_sub_iff_add_eq' : a = b - c ↔ c + a = b := by rw [eq_sub_iff_add_eq, add_comm] lemma sub_eq_iff_eq_add' : a - b = c ↔ a = b + c := by rw [sub_eq_iff_eq_add, add_comm] lemma add_sub_cancel' (a b : α) : a + b - a = b := by rw [sub_eq_neg_add, neg_add_cancel_left] lemma add_sub_cancel'_right (a b : α) : a + (b - a) = b := by rw [← add_sub_assoc, add_sub_cancel'] lemma sub_right_comm (a b c : α) : a - b - c = a - c - b := add_right_comm _ _ _ lemma sub_add_sub_cancel' (a b c : α) : (a - b) + (c - a) = c - b := by rw add_comm; apply sub_add_sub_cancel lemma sub_sub_sub_cancel_left (a b c : α) : (c - a) - (c - b) = b - a := by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel] lemma sub_eq_sub_iff_sub_eq_sub {d : α} : a - b = c - d ↔ a - c = b - d := ⟨λ h, by rw eq_add_of_sub_eq h; simp, λ h, by rw eq_add_of_sub_eq h; simp⟩ end add_comm_group section is_conj variables [group α] [group β] def is_conj (a b : α) := ∃ c : α, c * a * c⁻¹ = b @[refl] lemma is_conj_refl (a : α) : is_conj a a := ⟨1, by rw [one_mul, one_inv, mul_one]⟩ @[symm] lemma is_conj_symm {a b : α} : is_conj a b → is_conj b a | ⟨c, hc⟩ := ⟨c⁻¹, by rw [← hc, mul_assoc, mul_inv_cancel_right, inv_mul_cancel_left]⟩ @[trans] lemma is_conj_trans {a b c : α} : is_conj a b → is_conj b c → is_conj a c | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, by rw [← hc₂, ← hc₁, mul_inv_rev]; simp only [mul_assoc]⟩ @[simp] lemma is_conj_one_right {a : α} : is_conj 1 a ↔ a = 1 := ⟨by simp [is_conj, is_conj_refl] {contextual := tt}, by simp [is_conj_refl] {contextual := tt}⟩ @[simp] lemma is_conj_one_left {a : α} : is_conj a 1 ↔ a = 1 := calc is_conj a 1 ↔ is_conj 1 a : ⟨is_conj_symm, is_conj_symm⟩ ... ↔ a = 1 : is_conj_one_right @[simp] lemma is_conj_iff_eq {α : Type*} [comm_group α] {a b : α} : is_conj a b ↔ a = b := ⟨λ ⟨c, hc⟩, by rw [← hc, mul_right_comm, mul_inv_self, one_mul], λ h, by rw h⟩ end is_conj class is_monoid_hom [monoid α] [monoid β] (f : α → β) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y}, f (x * y) = f x * f y) class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) : Prop := (map_zero : f 0 = 0) (map_add : ∀ {x y}, f (x + y) = f x + f y) attribute [to_additive is_add_monoid_hom] is_monoid_hom attribute [to_additive is_add_monoid_hom.map_add] is_monoid_hom.map_mul attribute [to_additive is_add_monoid_hom.mk] is_monoid_hom.mk namespace is_monoid_hom variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] @[to_additive is_add_monoid_hom.id] instance id : is_monoid_hom (@id α) := by refine {..}; intros; refl @[to_additive is_add_monoid_hom.id] instance comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] : is_monoid_hom (g ∘ f) := { map_mul := λ x y, show g _ = g _ * g _, by rw [map_mul f, map_mul g], map_one := show g _ = 1, by rw [map_one f, map_one g] } instance is_add_monoid_hom_mul_left {γ : Type*} [semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, x * y) := by refine_struct {..}; simp [mul_add] instance is_add_monoid_hom_mul_right {γ : Type*} [semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, y * x) := by refine_struct {..}; simp [add_mul] end is_monoid_hom -- TODO rename fields of is_group_hom: mul ↝ map_mul? /-- Predicate for group homomorphism. -/ class is_group_hom [group α] [group β] (f : α → β) : Prop := (mul : ∀ a b : α, f (a * b) = f a * f b) class is_add_group_hom [add_group α] [add_group β] (f : α → β) : Prop := (add : ∀ a b, f (a + b) = f a + f b) attribute [to_additive is_add_group_hom] is_group_hom attribute [to_additive is_add_group_hom.add] is_group_hom.mul attribute [to_additive is_add_group_hom.mk] is_group_hom.mk instance additive.is_add_group_hom [group α] [group β] (f : α → β) [is_group_hom f] : @is_add_group_hom (additive α) (additive β) _ _ f := ⟨@is_group_hom.mul α β _ _ f _⟩ instance multiplicative.is_group_hom [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] : @is_group_hom (multiplicative α) (multiplicative β) _ _ f := ⟨@is_add_group_hom.add α β _ _ f _⟩ namespace is_group_hom variables [group α] [group β] (f : α → β) [is_group_hom f] @[to_additive is_add_group_hom.zero] theorem one : f 1 = 1 := mul_self_iff_eq_one.1 $ by rw [← mul f, one_mul] @[to_additive is_add_group_hom.neg] theorem inv (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← mul f, inv_mul_self, one f] @[to_additive is_add_group_hom.id] instance id : is_group_hom (@id α) := ⟨λ _ _, rfl⟩ @[to_additive is_add_group_hom.comp] instance comp {γ} [group γ] (g : β → γ) [is_group_hom g] : is_group_hom (g ∘ f) := ⟨λ x y, show g _ = g _ * g _, by rw [mul f, mul g]⟩ protected lemma is_conj (f : α → β) [is_group_hom f] {a b : α} : is_conj a b → is_conj (f a) (f b) | ⟨c, hc⟩ := ⟨f c, by rw [← is_group_hom.mul f, ← is_group_hom.inv f, ← is_group_hom.mul f, hc]⟩ @[to_additive is_add_group_hom.to_is_add_monoid_hom] lemma to_is_monoid_hom (f : α → β) [is_group_hom f] : is_monoid_hom f := ⟨is_group_hom.one f, is_group_hom.mul f⟩ @[to_additive is_add_group_hom.injective_iff] lemma injective_iff (f : α → β) [is_group_hom f] : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h _, by rw ← is_group_hom.one f; exact @h _ _, λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← is_group_hom.inv f, ← is_group_hom.mul f] at hxy; simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩ attribute [instance] is_group_hom.to_is_monoid_hom is_add_group_hom.to_is_add_monoid_hom end is_group_hom @[to_additive is_add_group_hom_add] lemma is_group_hom_mul {α β} [group α] [comm_group β] (f g : α → β) [is_group_hom f] [is_group_hom g] : is_group_hom (λa, f a * g a) := ⟨assume a b, by simp only [is_group_hom.mul f, is_group_hom.mul g, mul_comm, mul_assoc, mul_left_comm]⟩ attribute [instance] is_group_hom_mul is_add_group_hom_add @[to_additive is_add_group_hom_neg] lemma is_group_hom_inv {α β} [group α] [comm_group β] (f : α → β) [is_group_hom f] : is_group_hom (λa, (f a)⁻¹) := ⟨assume a b, by rw [is_group_hom.mul f, mul_inv]⟩ attribute [instance] is_group_hom_inv is_add_group_hom_neg @[to_additive neg.is_add_group_hom] lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) := ⟨by simp [mul_inv_rev, mul_comm]⟩ attribute [instance] inv.is_group_hom neg.is_add_group_hom /-- Predicate for group anti-homomorphism, or a homomorphism into the opposite group. -/ class is_group_anti_hom {β : Type*} [group α] [group β] (f : α → β) : Prop := (mul : ∀ a b : α, f (a * b) = f b * f a) namespace is_group_anti_hom variables [group α] [group β] (f : α → β) [w : is_group_anti_hom f] include w theorem one : f 1 = 1 := mul_self_iff_eq_one.1 $ by rw [← mul f, one_mul] theorem inv (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← mul f, mul_inv_self, one f] end is_group_anti_hom theorem inv_is_group_anti_hom [group α] : is_group_anti_hom (λ x : α, x⁻¹) := ⟨mul_inv_rev⟩ namespace is_add_group_hom variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] lemma sub (a b) : f (a - b) = f a - f b := calc f (a - b) = f (a + -b) : rfl ... = f a + f (-b) : add f _ _ ... = f a - f b : by simp[neg f] end is_add_group_hom lemma is_add_group_hom_sub {α β} [add_group α] [add_comm_group β] (f g : α → β) [is_add_group_hom f] [is_add_group_hom g] : is_add_group_hom (λa, f a - g a) := is_add_group_hom_add f (λa, - g a) attribute [instance] is_add_group_hom_sub namespace units variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] definition map : units α → units β := λ u, ⟨f u.val, f u.inv, by rw [← is_monoid_hom.map_mul f, u.val_inv, is_monoid_hom.map_one f], by rw [← is_monoid_hom.map_mul f, u.inv_val, is_monoid_hom.map_one f] ⟩ instance : is_group_hom (units.map f) := ⟨λ a b, by ext; exact is_monoid_hom.map_mul f ⟩ instance : is_monoid_hom (coe : units α → α) := ⟨by simp, by simp⟩ @[simp] lemma coe_map (u : units α) : (map f u : β) = f u := rfl end units @[to_additive with_zero] def with_one (α) := option α @[to_additive with_zero.monad] instance : monad with_one := option.monad @[to_additive with_zero.has_zero] instance : has_one (with_one α) := ⟨none⟩ @[to_additive with_zero.has_coe_t] instance : has_coe_t α (with_one α) := ⟨some⟩ @[simp, to_additive with_zero.zero_ne_coe] lemma with_one.one_ne_coe {a : α} : (1 : with_one α) ≠ a := λ h, option.no_confusion h @[simp, to_additive with_zero.coe_ne_zero] lemma with_one.coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := λ h, option.no_confusion h @[to_additive with_zero.ne_zero_iff_exists] lemma with_one.ne_one_iff_exists : ∀ {x : with_one α}, x ≠ 1 ↔ ∃ (a : α), x = a | 1 := ⟨λ h, false.elim $ h rfl, by { rintros ⟨a,ha⟩ h, simpa using h }⟩ | (a : α) := ⟨λ h, ⟨a, rfl⟩, λ h, with_one.coe_ne_one⟩ @[to_additive with_zero.coe_inj] lemma with_one.coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj @[elab_as_eliminator, to_additive with_zero.cases_on] protected lemma with_one.cases_on (P : with_one α → Prop) : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on attribute [to_additive with_zero.has_zero.equations._eqn_1] with_one.has_one.equations._eqn_1 @[to_additive with_zero.has_add] instance [has_mul α] : has_mul (with_one α) := { mul := option.lift_or_get (*) } @[simp, to_additive with_zero.add_coe] lemma with_one.mul_coe [has_mul α] (a b : α) : (a : with_one α) * b = (a * b : α) := rfl attribute [to_additive with_zero.has_add.equations._eqn_1] with_one.has_mul.equations._eqn_1 instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1, ..with_one.has_one, ..with_one.has_mul } attribute [to_additive with_zero.add_monoid._proof_1] with_one.monoid._proof_1 attribute [to_additive with_zero.add_monoid._proof_2] with_one.monoid._proof_2 attribute [to_additive with_zero.add_monoid._proof_3] with_one.monoid._proof_3 attribute [to_additive with_zero.add_monoid] with_one.monoid attribute [to_additive with_zero.add_monoid.equations._eqn_1] with_one.monoid.equations._eqn_1 instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } instance [add_comm_semigroup α] : add_comm_monoid (with_zero α) := { add_comm := (option.lift_or_get_comm _).1, ..with_zero.add_monoid } attribute [to_additive with_zero.add_comm_monoid] with_one.comm_monoid namespace with_zero instance [one : has_one α] : has_one (with_zero α) := { ..one } instance [has_one α] : zero_ne_one_class (with_zero α) := { zero_ne_one := λ h, option.no_confusion h, ..with_zero.has_zero, ..with_zero.has_one } lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a * b)), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp] lemma mul_coe [has_mul α] (a b : α) : (a : with_zero α) * b = (a * b : α) := rfl instance [semigroup α] : semigroup (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup } instance [monoid α] : monoid (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.zero_ne_one_class, ..with_zero.semigroup } instance [comm_monoid α] : comm_monoid (with_zero α) := { ..with_zero.monoid, ..with_zero.comm_semigroup } definition inv [has_inv α] (x : with_zero α) : with_zero α := do a ← x, return a⁻¹ instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩ @[simp] lemma inv_coe [has_inv α] (a : α) : (a : with_zero α)⁻¹ = (a⁻¹ : α) := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl section group variables [group α] @[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 := show ((1⁻¹ : α) : with_zero α) = 1, by simp [coe_one] definition with_zero.div (x y : with_zero α) : with_zero α := x * y⁻¹ instance : has_div (with_zero α) := ⟨with_zero.div⟩ @[simp] lemma zero_div (a : with_zero α) : 0 / a = 0 := rfl @[simp] lemma div_zero (a : with_zero α) : a / 0 = 0 := by change a * _ = _; simp lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl lemma one_div (x : with_zero α) : 1 / x = x⁻¹ := one_mul _ @[simp] lemma div_one : ∀ (x : with_zero α), x / 1 = x | 0 := rfl | (a : α) := show _ * _ = _, by simp @[simp] lemma mul_right_inv : ∀ (x : with_zero α) (h : x ≠ 0), x * x⁻¹ = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_left_inv : ∀ (x : with_zero α) (h : x ≠ 0), x⁻¹ * x = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_inv_rev : ∀ (x y : with_zero α), (x * y)⁻¹ = y⁻¹ * x⁻¹ | 0 0 := rfl | 0 (b : α) := rfl | (a : α) 0 := rfl | (a : α) (b : α) := by simp @[simp] lemma mul_div_cancel {a b : with_zero α} (hb : b ≠ 0) : a * b / b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] @[simp] lemma div_mul_cancel {a b : with_zero α} (hb : b ≠ 0) : a / b * b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] lemma div_eq_iff_mul_eq {a b c : with_zero α} (hb : b ≠ 0) : a / b = c ↔ c * b = a := by split; intro h; simp [h.symm, hb] end group section comm_group variables [comm_group α] {a b c d : with_zero α} lemma div_eq_div (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = b * c := begin rw ne_zero_iff_exists at hb hd, rcases hb with ⟨b, rfl⟩, rcases hd with ⟨d, rfl⟩, induction a using with_zero.cases_on; induction c using with_zero.cases_on, { refl }, { simp [div_coe] }, { simp [div_coe] }, erw [with_zero.coe_inj, with_zero.coe_inj], show a * b⁻¹ = c * d⁻¹ ↔ a * d = b * c, split; intro H, { rw mul_inv_eq_iff_eq_mul at H, rw [H, mul_right_comm, inv_mul_cancel_right, mul_comm] }, { rw [mul_inv_eq_iff_eq_mul, mul_right_comm, mul_comm c, ← H, mul_inv_cancel_right] } end end comm_group end with_zero
c53f98885887b4081e4837fca38c91ff9dbc6e43
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/rewrite_tactic.lean
173556caeed59ebab051b5981e8d82ddd9e9a317
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
477
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.relation_tactics import Mathlib.Lean3Lib.init.meta.occurrences universes l namespace Mathlib namespace tactic /-- Configuration options for the `rewrite` tactic. -/ structure rewrite_cfg extends apply_cfg where symm : Bool occs : occurrences
57c237c727311e029d7c22c1658c48a16d1eb977
da2388aff16df48b4a928b575bcec678b8e7f2cf
/src/mwe.lean
7f65cdef9794f26ea407a1f937ffdfd278a23524
[]
no_license
ADedecker/series
1d0d282d4333c7599f07cc705a35cf5edfb87a3b
12fbcdd16b3cdeda4476165a4645fcccc0fb3234
refs/heads/master
1,674,828,739,868
1,607,618,619,000
1,607,618,619,000
304,379,894
0
0
null
null
null
null
UTF-8
Lean
false
false
1,192
lean
import analysis.calculus.deriv open filter asymptotics open_locale topological_space lemma is_o_pow_pow {α : Type*} [normed_field α] [discrete_linear_ordered_field α] {p q : ℕ} (hpq : p < q) : is_o (λ (x : α), x^p) (λ x, x^q) at_top := begin rw is_o_iff_tendsto sorry, suffices h : tendsto (λ (x : α), x ^ ((p : ℤ) - q)) at_top (𝓝 0), { refine (tendsto_congr' ((eventually_gt_at_top (0 : α)).mono (λ x hx, _))).mp h, simp [fpow_sub hx.ne.symm] }, rw ← neg_sub, rw ← int.coe_nat_sub hpq.le, have : 1 ≤ q - p := nat.sub_pos_of_lt hpq, exact @tendsto_pow_neg_at_top α _ _ (by apply_instance) _ this, end lemma tendsto_pow_div_pow {α : Type*} [normed_field α] [discrete_linear_ordered_field α] {p q : ℕ} (hpq : p < q) : tendsto (λ (x : α), x^p / x^q) at_top (𝓝 0) := begin suffices h : tendsto (λ (x : α), x ^ ((p : ℤ) - q)) at_top (𝓝 0), { refine (tendsto_congr' ((eventually_gt_at_top (0 : α)).mono (λ x hx, _))).mp h, simp [fpow_sub hx.ne.symm] }, rw ← neg_sub, rw ← int.coe_nat_sub hpq.le, have : 1 ≤ q - p := nat.sub_pos_of_lt hpq, exact @tendsto_pow_neg_at_top α _ _ (by apply_instance) _ this, end
e4615bd715e96ae3f4ec28c91a7f0a7d55e925b2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Calc.lean
0e5a5cde41c71ca71ba4e8faf547ed7c794b8131
[ "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
4,982
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.App namespace Lean.Elab.Term open Meta /-- Decompose `e` into `(r, a, b)`. Remark: it assumes the last two arguments are explicit. -/ def getCalcRelation? (e : Expr) : MetaM (Option (Expr × Expr × Expr)) := if e.getAppNumArgs < 2 then return none else return some (e.appFn!.appFn!, e.appFn!.appArg!, e.appArg!) private def getRelUniv (r : Expr) : MetaM Level := do let rType ← inferType r forallTelescopeReducing rType fun _ sort => do let .sort u ← whnf sort | throwError "unexpected relation type{indentExpr rType}" return u def mkCalcTrans (result resultType step stepType : Expr) : MetaM (Expr × Expr) := do let some (r, a, b) ← getCalcRelation? resultType | unreachable! let some (s, _, c) ← getCalcRelation? (← instantiateMVars stepType) | unreachable! let u ← getRelUniv r let v ← getRelUniv s let (α, β, γ) := (← inferType a, ← inferType b, ← inferType c) let (u_1, u_2, u_3) := (← getLevel α, ← getLevel β, ← getLevel γ) let w ← mkFreshLevelMVar let t ← mkFreshExprMVar (← mkArrow α (← mkArrow γ (mkSort w))) let selfType := mkAppN (Lean.mkConst ``Trans [u, v, w, u_1, u_2, u_3]) #[α, β, γ, r, s, t] match (← trySynthInstance selfType) with | .some self => let result := mkAppN (Lean.mkConst ``Trans.trans [u, v, w, u_1, u_2, u_3]) #[α, β, γ, r, s, t, self, a, b, c, result, step] let resultType := (← instantiateMVars (← inferType result)).headBeta unless (← getCalcRelation? resultType).isSome do throwError "invalid 'calc' step, step result is not a relation{indentExpr resultType}" return (result, resultType) | _ => throwError "invalid 'calc' step, failed to synthesize `Trans` instance{indentExpr selfType}" /-- Adds a type annotation to a hole that occurs immediately at the beginning of the term. This is so that coercions can trigger when elaborating the term. See https://github.com/leanprover/lean4/issues/2040 for futher rationale. - `_ < 3` is annotated - `(_) < 3` is not, because it occurs after an atom - in `_ < _` only the first one is annotated - `_ + 2 < 3` is annotated (not the best heuristic, ideally we'd like to annotate `_ + 2`) - `lt _ 3` is not, because it occurs after an identifier -/ partial def annotateFirstHoleWithType (t : Term) (type : Expr) : TermElabM Term := -- The state is true if we should annotate the immediately next hole with the type. return ⟨← StateT.run' (go t) true⟩ where go (t : Syntax) := do unless ← get do return t match t with | .node _ ``Lean.Parser.Term.hole _ => set false `(($(⟨t⟩) : $(← exprToSyntax type))) | .node i k as => return .node i k (← as.mapM go) | _ => set false; return t def getCalcFirstStep (step0 : TSyntax ``calcFirstStep) : TermElabM (TSyntax ``calcStep) := match step0 with | `(calcFirstStep| $term:term) => `(calcStep| $term = _ := rfl) | `(calcFirstStep| $term := $proof) => `(calcStep| $term := $proof) | _ => throwUnsupportedSyntax def getCalcSteps (steps : TSyntax ``calcSteps) : TermElabM (Array (TSyntax ``calcStep)) := match steps with | `(calcSteps| $step0:calcFirstStep $rest*) => do let step0 ← getCalcFirstStep step0 pure (#[step0] ++ rest) | _ => unreachable! def elabCalcSteps (steps : TSyntax ``calcSteps) : TermElabM Expr := do let mut result? := none let mut prevRhs? := none for step in ← getCalcSteps steps do let `(calcStep| $pred := $proofTerm) := step | unreachable! let type ← elabType <| ← do if let some prevRhs := prevRhs? then annotateFirstHoleWithType pred (← inferType prevRhs) else pure pred let some (_, lhs, rhs) ← getCalcRelation? type | throwErrorAt pred "invalid 'calc' step, relation expected{indentExpr type}" if let some prevRhs := prevRhs? then unless (← isDefEqGuarded lhs prevRhs) do throwErrorAt pred "invalid 'calc' step, left-hand-side is{indentD m!"{lhs} : {← inferType lhs}"}\nprevious right-hand-side is{indentD m!"{prevRhs} : {← inferType prevRhs}"}" -- " let proof ← withFreshMacroScope do elabTermEnsuringType proofTerm type result? := some <| ← do if let some (result, resultType) := result? then synthesizeSyntheticMVarsUsingDefault withRef pred do mkCalcTrans result resultType proof type else pure (proof, type) prevRhs? := rhs return result?.get!.1 /-- Elaborator for the `calc` term mode variant. -/ @[builtin_term_elab «calc»] def elabCalc : TermElab := fun stx expectedType? => do let steps : TSyntax ``calcSteps := ⟨stx[1]⟩ let result ← elabCalcSteps steps synthesizeSyntheticMVarsUsingDefault let result ← ensureHasType expectedType? result return result
ee04468785133c8cf86d3392e7d7a7e23fda0b92
618003631150032a5676f229d13a079ac875ff77
/test/lint_coe_t.lean
6cd2995373a04f40ceccae37fadac3e54b4e82f6
[ "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,084
lean
import tactic.lint open tactic -- bad, because every iteration of tc search will loop, generating nested quotients section local attribute [instance] def a_to_quot {α} (R : setoid α) : has_coe α (quotient R) := ⟨quotient.mk⟩ run_cmd do d ← get_decl ``a_to_quot, some _ ← linter.has_coe_variable.test d, d ← get_decl ``has_coe_to_fun, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end -- good, because the term gets smaller in every iteration noncomputable instance quot_to_a {α} (R : setoid α) : has_coe (quotient R) α := ⟨λ q, quot.rec_on q (λ a, classical.choice ⟨a⟩) (by cc)⟩ #eval do decl ← get_decl ``quot_to_a, -- linter does not complain none ← linter.has_coe_variable.test decl, skip -- bad, because it introduces a metavariable section local attribute [instance] def int_to_a {α} [inhabited α] : has_coe ℤ α := ⟨λ _, default _⟩ #eval do decl ← get_decl ``int_to_a, -- linter does not complain some _ ← linter.has_coe_variable.test decl, skip end
022fc847b708a60ab48937728d8556841a74750a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/polynomial/expand.lean
8df70d7d9590a6a4ef7743de5272dcfc79798780
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,731
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.polynomial.basic import ring_theory.ideal.local_ring import tactic.ring_exp /-! # Expand a polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`. * `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ universes u v w open_locale classical big_operators polynomial open finset namespace polynomial section comm_semiring variables (R : Type u) [comm_semiring R] {S : Type v} [comm_semiring S] (p q : ℕ) /-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/ noncomputable def expand : R[X] →ₐ[R] R[X] := { commutes' := λ r, eval₂_C _ _, .. (eval₂_ring_hom C (X ^ p) : R[X] →+* R[X]) } lemma coe_expand : (expand R p : R[X] → R[X]) = eval₂ C (X ^ p) := rfl variables {R} lemma expand_eq_sum {f : R[X]} : expand R p f = f.sum (λ e a, C a * (X ^ p) ^ e) := by { dsimp [expand, eval₂], refl, } @[simp] lemma expand_C (r : R) : expand R p (C r) = C r := eval₂_C _ _ @[simp] lemma expand_X : expand R p X = X ^ p := eval₂_X _ _ @[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r := by simp_rw [← smul_X_eq_monomial, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul] theorem expand_expand (f : R[X]) : expand R p (expand R q f) = expand R (p * q) f := polynomial.induction_on f (λ r, by simp_rw expand_C) (λ f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, alg_hom.map_pow, expand_X, pow_mul]) theorem expand_mul (f : R[X]) : expand R (p * q) f = expand R p (expand R q f) := (expand_expand p q f).symm @[simp] theorem expand_zero (f : R[X]) : expand R 0 f = C (eval 1 f) := by simp [expand] @[simp] theorem expand_one (f : R[X]) : expand R 1 f = f := polynomial.induction_on f (λ r, by rw expand_C) (λ f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one]) theorem expand_pow (f : R[X]) : expand R (p ^ q) f = (expand R p ^[q] f) := nat.rec_on q (by rw [pow_zero, expand_one, function.iterate_zero, id]) $ λ n ih, by rw [function.iterate_succ_apply', pow_succ, expand_mul, ih] theorem derivative_expand (f : R[X]) : (expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) := by rw [coe_expand, derivative_eval₂_C, derivative_pow, C_eq_nat_cast, derivative_X, mul_one] theorem coeff_expand {p : ℕ} (hp : 0 < p) (f : R[X]) (n : ℕ) : (expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 := begin simp only [expand_eq_sum], simp_rw [coeff_sum, ← pow_mul, C_mul_X_pow_eq_monomial, coeff_monomial, sum], split_ifs with h, { rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl], { intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] }, { intro hn, rw not_mem_support_iff.1 hn, split_ifs; refl } }, { rw finset.sum_eq_zero, intros k hk, rw if_neg, exact λ hkn, h ⟨k, hkn.symm⟩, }, end @[simp] theorem coeff_expand_mul {p : ℕ} (hp : 0 < p) (f : R[X]) (n : ℕ) : (expand R p f).coeff (n * p) = f.coeff n := by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp] @[simp] theorem coeff_expand_mul' {p : ℕ} (hp : 0 < p) (f : R[X]) (n : ℕ) : (expand R p f).coeff (p * n) = f.coeff n := by rw [mul_comm, coeff_expand_mul hp] /-- Expansion is injective. -/ lemma expand_injective {n : ℕ} (hn : 0 < n) : function.injective (expand R n) := λ g g' H, ext $ λ k, by rw [← coeff_expand_mul hn, H, coeff_expand_mul hn] theorem expand_inj {p : ℕ} (hp : 0 < p) {f g : R[X]} : expand R p f = expand R p g ↔ f = g := (expand_injective hp).eq_iff theorem expand_eq_zero {p : ℕ} (hp : 0 < p) {f : R[X]} : expand R p f = 0 ↔ f = 0 := (expand_injective hp).eq_iff' (map_zero _) theorem expand_ne_zero {p : ℕ} (hp : 0 < p) {f : R[X]} : expand R p f ≠ 0 ↔ f ≠ 0 := (expand_eq_zero hp).not theorem expand_eq_C {p : ℕ} (hp : 0 < p) {f : R[X]} {r : R} : expand R p f = C r ↔ f = C r := by rw [← expand_C, expand_inj hp, expand_C] theorem nat_degree_expand (p : ℕ) (f : R[X]) : (expand R p f).nat_degree = f.nat_degree * p := begin cases p.eq_zero_or_pos with hp hp, { rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, eval₂_hom, nat_degree_C] }, by_cases hf : f = 0, { rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] }, have hf1 : expand R p f ≠ 0 := mt (expand_eq_zero hp).1 hf, rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1], refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ λ n hn, _) _, { rw coeff_expand hp, split_ifs with hpn, { rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn, rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn }, { refl } }, { refine le_degree_of_ne_zero _, rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf } end lemma monic.expand {p : ℕ} {f : R[X]} (hp : 0 < p) (h : f.monic) : (expand R p f).monic := begin rw [monic.def, leading_coeff, nat_degree_expand, coeff_expand hp], simp [hp, h], end theorem map_expand {p : ℕ} {f : R →+* S} {q : R[X]} : map f (expand R p q) = expand S p (map f q) := begin by_cases hp : p = 0, { simp [hp] }, ext, rw [coeff_map, coeff_expand (nat.pos_of_ne_zero hp), coeff_expand (nat.pos_of_ne_zero hp)], split_ifs; simp, end @[simp] lemma expand_eval (p : ℕ) (P : R[X]) (r : R) : eval r (expand R p P) = eval (r ^ p) P := begin refine polynomial.induction_on P (λ a, by simp) (λ f g hf hg, _) (λ n a h, by simp), rw [alg_hom.map_add, eval_add, eval_add, hf, hg] end @[simp] lemma expand_aeval {A : Type*} [semiring A] [algebra R A] (p : ℕ) (P : R[X]) (r : A) : aeval r (expand R p P) = aeval (r ^ p) P := begin refine polynomial.induction_on P (λ a, by simp) (λ f g hf hg, _) (λ n a h, by simp), rw [alg_hom.map_add, aeval_add, aeval_add, hf, hg] end /-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ noncomputable def contract (p : ℕ) (f : R[X]) : R[X] := ∑ n in range (f.nat_degree + 1), monomial n (f.coeff (n * p)) theorem coeff_contract {p : ℕ} (hp : p ≠ 0) (f : R[X]) (n : ℕ) : (contract p f).coeff n = f.coeff (n * p) := begin simp only [contract, coeff_monomial, sum_ite_eq', finset_sum_coeff, mem_range, not_lt, ite_eq_left_iff], assume hn, apply (coeff_eq_zero_of_nat_degree_lt _).symm, calc f.nat_degree < f.nat_degree + 1 : nat.lt_succ_self _ ... ≤ n * 1 : by simpa only [mul_one] using hn ... ≤ n * p : mul_le_mul_of_nonneg_left (show 1 ≤ p, from hp.bot_lt) (zero_le n) end theorem contract_expand {f : R[X]} (hp : p ≠ 0) : contract p (expand R p f) = f := begin ext, simp [coeff_contract hp, coeff_expand hp.bot_lt, nat.mul_div_cancel _ hp.bot_lt] end section char_p variable [char_p R p] theorem expand_contract [no_zero_divisors R] {f : R[X]} (hf : f.derivative = 0) (hp : p ≠ 0) : expand R p (contract p f) = f := begin ext n, rw [coeff_expand hp.bot_lt, coeff_contract hp], split_ifs with h, { rw nat.div_mul_cancel h }, { cases n, { exact absurd (dvd_zero p) h }, have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this }, rw [← nat.cast_succ, char_p.cast_eq_zero_iff R p] at this, exact absurd this h } end variable [hp : fact p.prime] include hp theorem expand_char (f : R[X]) : map (frobenius R p) (expand R p f) = f ^ p := begin refine f.induction_on' (λ a b ha hb, _) (λ n a, _), { rw [alg_hom.map_add, polynomial.map_add, ha, hb, add_pow_char], }, { rw [expand_monomial, map_monomial, ← C_mul_X_pow_eq_monomial, ← C_mul_X_pow_eq_monomial, mul_pow, ← C.map_pow, frobenius_def], ring_exp } end theorem map_expand_pow_char (f : R[X]) (n : ℕ) : map ((frobenius R p) ^ n) (expand R (p ^ n) f) = f ^ (p ^ n) := begin induction n, { simp [ring_hom.one_def] }, symmetry, rw [pow_succ', pow_mul, ← n_ih, ← expand_char, pow_succ, ring_hom.mul_def, ← map_map, mul_comm, expand_mul, ← map_expand] end end char_p end comm_semiring section is_domain variables (R : Type u) [comm_ring R] [is_domain R] theorem is_local_ring_hom_expand {p : ℕ} (hp : 0 < p) : is_local_ring_hom (↑(expand R p) : R[X] →+* R[X]) := begin refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1, have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1), rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2, rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C] end variable {R} theorem of_irreducible_expand {p : ℕ} (hp : p ≠ 0) {f : R[X]} (hf : irreducible (expand R p f)) : irreducible f := let _ := is_local_ring_hom_expand R hp.bot_lt in by exactI of_irreducible_map ↑(expand R p) hf theorem of_irreducible_expand_pow {p : ℕ} (hp : p ≠ 0) {f : R[X]} {n : ℕ} : irreducible (expand R (p ^ n) f) → irreducible f := nat.rec_on n (λ hf, by rwa [pow_zero, expand_one] at hf) $ λ n ih hf, ih $ of_irreducible_expand hp $ by { rw pow_succ at hf, rwa [expand_expand] } end is_domain end polynomial
e412c468d2d192cf45b8175c18d9b43734281e82
367134ba5a65885e863bdc4507601606690974c1
/src/data/list/nat_antidiagonal.lean
a1e0281ba661222b303030113a144bb67777604a
[ "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,839
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.list.range open list function nat namespace list namespace nat /-- The antidiagonal of a natural number `n` is the list of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : list (ℕ × ℕ) := (range (n+1)).map (λ i, (i, n - i)) /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := begin rw [antidiagonal, mem_map], split, { rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_sub_of_le hi }, { rintro rfl, refine ⟨x.fst, _, _⟩, { rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ }, { exact prod.ext rfl (nat.add_sub_cancel_left _ _) } } end /-- The length of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 := by rw [antidiagonal, length_map, length_range] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] := rfl /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := nodup_map (@left_inverse.injective ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl) (nodup_range _) @[simp] lemma antidiagonal_succ {n : ℕ} : antidiagonal (n + 1) = (0, n + 1) :: ((antidiagonal n).map (prod.map nat.succ id) ) := begin simp only [antidiagonal, range_succ_eq_map, map_cons, true_and, nat.add_succ_sub_one, add_zero, id.def, eq_self_iff_true, nat.sub_zero, map_map, prod.map_mk], apply congr (congr rfl _) rfl, ext; simp, end end nat end list
5d6842eb1cf693f425379981a7aed5d7a9a20ddc
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/special_functions/trigonometric/chebyshev.lean
69dd2162d0021cf838dfd9d85bcb5f3934f0ea0a
[ "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
2,276
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import analysis.complex.basic import ring_theory.polynomial.chebyshev import data.complex.exponential /-! # Multiple angle formulas in terms of Chebyshev polynomials * `polynomial.chebyshev.T_complex_cos`: the `n`-th Chebyshev polynomial evaluates on `complex.cos θ` to the value `complex.cos (n * θ)`. -/ namespace polynomial.chebyshev open polynomial complex /-- The `n`-th Chebyshev polynomial of the first kind evaluates on `cos θ` to the value `cos (n * θ)`. -/ lemma T_complex_cos (θ : ℂ) : ∀ n, (T ℂ n).eval (cos θ) = cos (n * θ) | 0 := by simp only [T_zero, eval_one, nat.cast_zero, zero_mul, cos_zero] | 1 := by simp only [eval_X, one_mul, T_one, nat.cast_one] | (n + 2) := begin simp only [eval_X, eval_one, T_add_two, eval_sub, eval_bit0, nat.cast_succ, eval_mul], rw [T_complex_cos (n + 1), T_complex_cos n], have aux : sin θ * sin θ = 1 - cos θ * cos θ, { rw ← sin_sq_add_cos_sq θ, ring, }, simp only [nat.cast_add, nat.cast_one, add_mul, cos_add, one_mul, sin_add, mul_assoc, aux], ring, end /-- `cos (n * θ)` is equal to the `n`-th Chebyshev polynomial of the first kind evaluated on `cos θ`. -/ lemma cos_nat_mul (n : ℕ) (θ : ℂ) : cos (n * θ) = (T ℂ n).eval (cos θ) := (T_complex_cos θ n).symm /-- The `n`-th Chebyshev polynomial of the second kind evaluates on `cos θ` to the value `sin ((n+1) * θ) / sin θ`. -/ lemma U_complex_cos (θ : ℂ) (n : ℕ) : (U ℂ n).eval (cos θ) * sin θ = sin ((n+1) * θ) := begin induction n with d hd, { simp only [U_zero, nat.cast_zero, eval_one, mul_one, zero_add, one_mul] }, { rw U_eq_X_mul_U_add_T, simp only [eval_add, eval_mul, eval_X, T_complex_cos, add_mul, mul_assoc, hd, one_mul], conv_rhs { rw [sin_add, mul_comm] }, push_cast, simp only [add_mul, one_mul] } end /-- `sin ((n + 1) * θ)` is equal to `sin θ` multiplied with the `n`-th Chebyshev polynomial of the second kind evaluated on `cos θ`. -/ lemma sin_nat_succ_mul (n : ℕ) (θ : ℂ) : sin ((n + 1) * θ) = (U ℂ n).eval (cos θ) * sin θ := (U_complex_cos θ n).symm end polynomial.chebyshev
4a75943ade42cedcd6b106494176e2425d834954
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/arith2.lean
740659f251c0816f8a3201fd96669573bbd182b4
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
262
lean
import Int. import Real. print 1/2 eval 4/6 print 3 div 2 variable x : Real variable i : Int variable n : Nat print x + i + 1 + n set_option lean::pp::coercion true print x + i + 1 + n print x * i + x print x - i + x - x >= 0 print x < x print x <= x print x > x
bb09ed688aeb76a17bbcd323a7405d8df8f61be6
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch6/ex0501.lean
e83bb1b01288ebcae8d0775b4505a6155fcef377
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
942
lean
namespace hidden variables {α : Type} (r : α → α → Prop) definition reflexive : Prop := ∀ (a : α), r a a definition symmetric : Prop := ∀ {a b : α}, r a b → r b a definition transitive : Prop := ∀ {a b c : α}, r a b → r b c → r a c definition euclidean : Prop := ∀ {a b c : α}, r a b → r a c → r b c variable {r} theorem th1 (reflr : reflexive r) (euclr : euclidean r) : symmetric r := assume (a b : α), assume : (r a b), show r b a, from euclr this (reflr _) theorem th2 (symmr : symmetric r) (euclr : euclidean r) : transitive r := assume (a b c : α), assume (rab : r a b) (rbc : r b c), euclr (symmr rab) rbc -- error: /- theorem th3 (reflr : reflexive r) (euclr : euclidean r) : transitive r := th2 (th1 reflr euclr) euclr -/ theorem th3 (reflr : reflexive r) (euclr : euclidean r) : transitive r := @th2 _ _ (@th1 _ _ reflr @euclr) @euclr end hidden
8b5168d9dc64506d32099f68680597fa1a2b733f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/norm_cast.lean
a054c66ae5d9e8cb080ad56c02395c84f238e56d
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
9,106
lean
/- Copyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul-Nicolas Madelaine, Robert Y. Lewis Normalizing casts inside expressions. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.converter.interactive import Mathlib.tactic.hint import Mathlib.PostPort universes l u_1 u_2 namespace Mathlib /-! # A tactic for normalizing casts inside expressions This tactic normalizes casts inside expressions. It can be thought of as a call to the simplifier with a specific set of lemmas to move casts upwards in the expression. It has special handling of numerals and a simple heuristic to help moving casts "past" binary operators. Contrary to simp, it should be safe to use as a non-terminating tactic. The algorithm implemented here is described in the paper <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. ## Important definitions * `tactic.interactive.norm_cast` * `tactic.interactive.push_cast` * `tactic.interactive.exact_mod_cast` * `tactic.interactive.apply_mod_cast` * `tactic.interactive.rw_mod_cast` * `tactic.interactive.assumption_mod_cast` -/ namespace tactic /-- Runs `mk_instance` with a time limit. This is a work around to the fact that in some cases mk_instance times out instead of failing, for example: `has_lift_t ℤ ℕ` `mk_instance_fast` is used when we assume the type class search should end instantly. -/ end tactic namespace norm_cast /-- Output a trace message if `trace.norm_cast` is enabled. -/ /-- `label` is a type used to classify `norm_cast` lemmas. * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes -/ inductive label where | elim : label | move : label | squash : label namespace label /-- Convert `label` into `string`. -/ protected def to_string : label → string := sorry protected instance has_to_string : has_to_string label := has_to_string.mk label.to_string protected instance has_repr : has_repr label := has_repr.mk label.to_string /-- Convert `string` into `label`. -/ def of_string : string → Option label := sorry end label /-- Count how many coercions are at the top of the expression. -/ /-- Count how many coercions are inside the expression, including the top ones. -/ /-- Count how many coercions are inside the expression, excluding the top ones. -/ /-- Classifies a declaration of type `ty` as a `norm_cast` rule. -/ /-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/ /-- Empty `norm_cast_cache`. -/ /-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/ /-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/ /-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/ /-- The type of the `norm_cast` attribute. The optional label is used to overwrite the classifier. -/ /-- Efficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`. See Note [user attribute parameters]. -/ /-- `add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`. -/ -- special lemmas to handle the ≥, > and ≠ operators /-- `mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes for names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes. -/ -- names has the declarations in reverse order --some special lemmas to handle binary relations /-- The `norm_cast` attribute. -/ /-- Classify a declaration as a `norm_cast` rule. -/ /-- Gets the `norm_cast` classification label for a declaration. Applies the override specified on the attribute, if necessary. -/ end norm_cast namespace tactic.interactive /-- `push_cast` rewrites the expression to move casts toward the leaf nodes. For example, `↑(a + b)` will be written to `↑a + ↑b`. Equivalent to `simp only with push_cast`. Can also be used at hypotheses. `push_cast` can also be used at hypotheses and with extra simp rules. ```lean example (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast at h1, push_cast [int.add_zero] at h2, end ``` -/ end tactic.interactive namespace norm_cast /-- Prove `a = b` using the given simp set. -/ /-- Prove `a = b` by simplifying using move and squash lemmas. -/ /-- This is the main heuristic used alongside the elim and move lemmas. The goal is to help casts move past operators by adding intermediate casts. An expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ) is rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ) when (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma -/ /-- Discharging function used during simplification in the "squash" step. TODO: norm_cast takes a list of expressions to use as lemmas for the discharger TODO: a tactic to print the results the discharger fails to proove -/ /-- Core rewriting function used in the "squash" step, which moves casts upwards and eliminates them. It tries to rewrite an expression using the elim and move lemmas. On failure, it calls the splitting procedure heuristic. -/ /-! The following auxiliary functions are used to handle numerals. -/ /-- If possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`. Returns a pair of the new expression and proof that they are equal. -/ /-- If possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral. Returns a pair of the new expression and proof that they are equal. -/ /-- A local variant on `simplify_top_down`. -/ /-- The core simplification routine of `norm_cast`. -/ /-- A small variant of `push_cast` suited for non-interactive use. `derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`. -/ end norm_cast namespace tactic /-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it also normalizes the goal. -/ /-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the goal. -/ /-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/ /-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also normalizes `h` and tries to use that to close the goal. -/ end tactic namespace tactic.interactive /-- Normalize casts at the given locations by moving them "upwards". As opposed to simp, norm_cast can be used without necessarily closing the goal. -/ /-- Rewrite with the given rules and normalize casts between steps. -/ /-- Normalize the goal and the given expression, then close the goal with exact. -/ /-- Normalize the goal and the given expression, then apply the expression to the goal. -/ /-- Normalize the goal and every expression in the local context, then close the goal with assumption. -/ end tactic.interactive namespace conv.interactive /-- the converter version of `norm_cast' -/ end conv.interactive -- TODO: move this elsewhere? theorem ite_cast {α : Sort u_1} {β : Sort u_2} [has_lift_t α β] {c : Prop} [Decidable c] {a : α} {b : α} : ↑(ite c a b) = ite c ↑a ↑b := sorry /-- The `norm_cast` family of tactics is used to normalize casts inside expressions. It is basically a simp tactic with a specific set of lemmas to move casts upwards in the expression. Therefore it can be used more safely as a non-terminating tactic. It also has special handling of numerals. For instance, given an assumption ```lean a b : ℤ h : ↑a + ↑b < (10 : ℚ) ``` writing `norm_cast at h` will turn `h` into ```lean h : a + b < 10 ``` You can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast` or `assumption_mod_cast`. Writing `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and `h` before using `exact h` or `apply h`. Writing `assumption_mod_cast` will normalize the goal and for every expression `h` in the context it will try to normalize `h` and use `exact h`. `rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps. `push_cast` rewrites the expression to move casts toward the leaf nodes. This uses `norm_cast` lemmas in the forward direction. For example, `↑(a + b)` will be written to `↑a + ↑b`. It is equivalent to `simp only with push_cast`. It can also be used at hypotheses with `push_cast at h` and with extra simp lemmas with `push_cast [int.add_zero]`. ```lean example (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast at h1, push_cast [int.add_zero] at h2, end ``` The implementation and behavior of the `norm_cast` family is described in detail at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ /-- The `norm_cast` attribute should be given to lemmas that describe the
dd0d1020b930e54d3c1583cb8f1c1b2ae1bf6faa
7c92a46ce39266c13607ecdef7f228688f237182
/src/for_mathlib/data/set/basic.lean
d44f5e2d3e0fd594c36816e1a426aba7ce59d7a6
[ "Apache-2.0" ]
permissive
asym57/lean-perfectoid-spaces
3217d01f6ddc0d13e9fb68651749469750420767
359187b429f254a946218af4411d45f08705c83e
refs/heads/master
1,609,457,937,251
1,577,542,616,000
1,577,542,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,446
lean
import data.finset open set universes u v lemma set.mem_compl_singleton_iff {α : Type*} {a x : α} : x ∈ -({a} : set α) ↔ x ≠ a := by simp only [set.mem_singleton_iff, set.mem_compl_eq] lemma set.subset_compl_singleton_iff {α : Type*} {a : α} {s : set α} : s ⊆ -({a} : set α) ↔ a ∉ s := by { rw subset_compl_comm, simp } variables {α : Type*} {β : Type*} (f : α → β) lemma set.image_ne_empty (s : set α) (h : s ≠ ∅) : f '' s ≠ ∅ := λ H, h (image_eq_empty.1 H) @[simp] lemma set.exists_mem_range {α : Type u} {β : Type v} {f : α → β} {P : β → Prop} : (∃ b ∈ range f, P b) ↔ ∃ a, P (f a) := ⟨by rintros ⟨b, ⟨a, rfl⟩, h⟩ ; exact ⟨a, h⟩, λ ⟨a, h⟩, ⟨f a, mem_range_self a, h⟩⟩ @[simp] lemma set.exists_mem_range' {α : Type u} {β : Type v} {f : α → β} {P : β → Prop} : (∃ b, b ∈ range f ∧ P b) ↔ ∃ a, P (f a) := ⟨by rintros ⟨b, ⟨a, rfl⟩, h⟩ ; exact ⟨a, h⟩, λ ⟨a, h⟩, ⟨f a, mem_range_self a, h⟩⟩ lemma set.image_inter_subset (s t : set α) : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := by { rintros _ ⟨x, x_in, rfl⟩, exact ⟨mem_image_of_mem f x_in.1, mem_image_of_mem f x_in.2⟩ } def prod.map' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ := λ p : α₁ × β₁, ⟨f p.1, g p.2⟩ infix ` ⨯ `:90 := prod.map'
dbb1cc19e7cad4e5a0d352e089b8dcc7ae224123
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/direct_sum/internal.lean
87dbb2e9fb0160c6b087b49250dddccb1e92a4c6
[ "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
9,798
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Kevin Buzzard, Jujian Zhang -/ import algebra.algebra.operations import algebra.algebra.subalgebra.basic import algebra.direct_sum.algebra /-! # Internally graded rings and algebras This module provides `gsemiring` and `gcomm_semiring` instances for a collection of subobjects `A` when a `set_like.graded_monoid` instance is available: * `set_like.gnon_unital_non_assoc_semiring` * `set_like.gsemiring` * `set_like.gcomm_semiring` With these instances in place, it provides the bundled canonical maps out of a direct sum of subobjects into their carrier type: * `direct_sum.coe_ring_hom` (a `ring_hom` version of `direct_sum.coe_add_monoid_hom`) * `direct_sum.coe_alg_hom` (an `alg_hom` version of `direct_sum.submodule_coe`) Strictly the definitions in this file are not sufficient to fully define an "internal" direct sum; to represent this case, `(h : direct_sum.is_internal A) [set_like.graded_monoid A]` is needed. In the future there will likely be a data-carrying, constructive, typeclass version of `direct_sum.is_internal` for providing an explicit decomposition function. When `complete_lattice.independent (set.range A)` (a weaker condition than `direct_sum.is_internal A`), these provide a grading of `⨆ i, A i`, and the mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as `direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`. ## tags internally graded ring -/ open_locale direct_sum big_operators variables {ι : Type*} {σ S R : Type*} instance add_comm_monoid.of_submonoid_on_semiring [semiring R] [set_like σ R] [add_submonoid_class σ R] (A : ι → σ) : ∀ i, add_comm_monoid (A i) := λ i, by apply_instance instance add_comm_group.of_subgroup_on_ring [ring R] [set_like σ R] [add_subgroup_class σ R] (A : ι → σ) : ∀ i, add_comm_group (A i) := λ i, by apply_instance lemma set_like.algebra_map_mem_graded [has_zero ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [set_like.has_graded_one A] (s : S) : algebra_map S R s ∈ A 0 := begin rw algebra.algebra_map_eq_smul_one, exact ((A 0).smul_mem s $ set_like.one_mem_graded _), end lemma set_like.nat_cast_mem_graded [has_zero ι] [add_monoid_with_one R] [set_like σ R] [add_submonoid_class σ R] (A : ι → σ) [set_like.has_graded_one A] (n : ℕ) : (n : R) ∈ A 0 := begin induction n, { rw nat.cast_zero, exact zero_mem (A 0), }, { rw nat.cast_succ, exact add_mem n_ih (set_like.one_mem_graded _), }, end lemma set_like.int_cast_mem_graded [has_zero ι] [add_group_with_one R] [set_like σ R] [add_subgroup_class σ R] (A : ι → σ) [set_like.has_graded_one A] (z : ℤ) : (z : R) ∈ A 0:= begin induction z, { rw int.cast_of_nat, exact set_like.nat_cast_mem_graded _ _, }, { rw int.cast_neg_succ_of_nat, exact neg_mem (set_like.nat_cast_mem_graded _ _), }, end section direct_sum variables [decidable_eq ι] /-! #### From `add_submonoid`s and `add_subgroup`s -/ namespace set_like /-- Build a `gnon_unital_non_assoc_semiring` instance for a collection of additive submonoids. -/ instance gnon_unital_non_assoc_semiring [has_add ι] [non_unital_non_assoc_semiring R] [set_like σ R] [add_submonoid_class σ R] (A : ι → σ) [set_like.has_graded_mul A] : direct_sum.gnon_unital_non_assoc_semiring (λ i, A i) := { mul_zero := λ i j _, subtype.ext (mul_zero _), zero_mul := λ i j _, subtype.ext (zero_mul _), mul_add := λ i j _ _ _, subtype.ext (mul_add _ _ _), add_mul := λ i j _ _ _, subtype.ext (add_mul _ _ _), ..set_like.ghas_mul A } /-- Build a `gsemiring` instance for a collection of additive submonoids. -/ instance gsemiring [add_monoid ι] [semiring R] [set_like σ R] [add_submonoid_class σ R] (A : ι → σ) [set_like.graded_monoid A] : direct_sum.gsemiring (λ i, A i) := { mul_zero := λ i j _, subtype.ext (mul_zero _), zero_mul := λ i j _, subtype.ext (zero_mul _), mul_add := λ i j _ _ _, subtype.ext (mul_add _ _ _), add_mul := λ i j _ _ _, subtype.ext (add_mul _ _ _), nat_cast := λ n, ⟨n, set_like.nat_cast_mem_graded _ _⟩, nat_cast_zero := subtype.ext nat.cast_zero, nat_cast_succ := λ n, subtype.ext (nat.cast_succ n), ..set_like.gmonoid A } /-- Build a `gcomm_semiring` instance for a collection of additive submonoids. -/ instance gcomm_semiring [add_comm_monoid ι] [comm_semiring R] [set_like σ R] [add_submonoid_class σ R] (A : ι → σ) [set_like.graded_monoid A] : direct_sum.gcomm_semiring (λ i, A i) := { ..set_like.gcomm_monoid A, ..set_like.gsemiring A, } /-- Build a `gring` instance for a collection of additive subgroups. -/ instance gring [add_monoid ι] [ring R] [set_like σ R] [add_subgroup_class σ R] (A : ι → σ) [set_like.graded_monoid A] : direct_sum.gring (λ i, A i) := { int_cast := λ z, ⟨z, set_like.int_cast_mem_graded _ _⟩, int_cast_of_nat := λ n, subtype.ext $ int.cast_of_nat _, int_cast_neg_succ_of_nat := λ n, subtype.ext $ int.cast_neg_succ_of_nat n, ..set_like.gsemiring A } /-- Build a `gcomm_semiring` instance for a collection of additive submonoids. -/ instance gcomm_ring [add_comm_monoid ι] [comm_ring R] [set_like σ R] [add_subgroup_class σ R] (A : ι → σ) [set_like.graded_monoid A] : direct_sum.gcomm_ring (λ i, A i) := { ..set_like.gcomm_monoid A, ..set_like.gring A, } end set_like /-- The canonical ring isomorphism between `⨁ i, A i` and `R`-/ def direct_sum.coe_ring_hom [add_monoid ι] [semiring R] [set_like σ R] [add_submonoid_class σ R] (A : ι → σ) [set_like.graded_monoid A] : (⨁ i, A i) →+* R := direct_sum.to_semiring (λ i, add_submonoid_class.subtype (A i)) rfl (λ _ _ _ _, rfl) /-- The canonical ring isomorphism between `⨁ i, A i` and `R`-/ @[simp] lemma direct_sum.coe_ring_hom_of [add_monoid ι] [semiring R] [set_like σ R] [add_submonoid_class σ R] (A : ι → σ) [set_like.graded_monoid A] (i : ι) (x : A i) : direct_sum.coe_ring_hom A (direct_sum.of (λ i, A i) i x) = x := direct_sum.to_semiring_of _ _ _ _ _ lemma direct_sum.coe_mul_apply [add_monoid ι] [semiring R] [set_like σ R] [add_submonoid_class σ R] (A : ι → σ) [set_like.graded_monoid A] [Π (i : ι) (x : A i), decidable (x ≠ 0)] (r r' : ⨁ i, A i) (i : ι) : ((r * r') i : R) = ∑ ij in (r.support ×ˢ r'.support).filter (λ ij : ι × ι, ij.1 + ij.2 = i), r ij.1 * r' ij.2 := begin rw [direct_sum.mul_eq_sum_support_ghas_mul, dfinsupp.finset_sum_apply, add_submonoid_class.coe_finset_sum], simp_rw [direct_sum.coe_of_apply, ←finset.sum_filter, set_like.coe_ghas_mul], end /-! #### From `submodule`s -/ namespace submodule /-- Build a `galgebra` instance for a collection of `submodule`s. -/ instance galgebra [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [set_like.graded_monoid A] : direct_sum.galgebra S (λ i, A i) := { to_fun := ((algebra.linear_map S R).cod_restrict (A 0) $ set_like.algebra_map_mem_graded A).to_add_monoid_hom, map_one := subtype.ext $ by exact (algebra_map S R).map_one, map_mul := λ x y, sigma.subtype_ext (add_zero 0).symm $ (algebra_map S R).map_mul _ _, commutes := λ r ⟨i, xi⟩, sigma.subtype_ext ((zero_add i).trans (add_zero i).symm) $ algebra.commutes _ _, smul_def := λ r ⟨i, xi⟩, sigma.subtype_ext (zero_add i).symm $ algebra.smul_def _ _ } @[simp] lemma set_like.coe_galgebra_to_fun [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [set_like.graded_monoid A] (s : S) : ↑(@direct_sum.galgebra.to_fun _ S (λ i, A i) _ _ _ _ _ _ _ s) = (algebra_map S R s : R) := rfl /-- A direct sum of powers of a submodule of an algebra has a multiplicative structure. -/ instance nat_power_graded_monoid [comm_semiring S] [semiring R] [algebra S R] (p : submodule S R) : set_like.graded_monoid (λ i : ℕ, p ^ i) := { one_mem := by { rw [←one_le, pow_zero], exact le_rfl }, mul_mem := λ i j p q hp hq, by { rw pow_add, exact submodule.mul_mem_mul hp hq } } end submodule /-- The canonical algebra isomorphism between `⨁ i, A i` and `R`. -/ def direct_sum.coe_alg_hom [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [set_like.graded_monoid A] : (⨁ i, A i) →ₐ[S] R := direct_sum.to_algebra S _ (λ i, (A i).subtype) rfl (λ _ _ _ _, rfl) (λ _, rfl) /-- The supremum of submodules that form a graded monoid is a subalgebra, and equal to the range of `direct_sum.coe_alg_hom`. -/ lemma submodule.supr_eq_to_submodule_range [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [set_like.graded_monoid A] : (⨆ i, A i) = (direct_sum.coe_alg_hom A).range.to_submodule := (submodule.supr_eq_range_dfinsupp_lsum A).trans $ set_like.coe_injective rfl @[simp] lemma direct_sum.coe_alg_hom_of [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [set_like.graded_monoid A] (i : ι) (x : A i) : direct_sum.coe_alg_hom A (direct_sum.of (λ i, A i) i x) = x := direct_sum.to_semiring_of _ rfl (λ _ _ _ _, rfl) _ _ end direct_sum section homogeneous_element lemma set_like.is_homogeneous_zero_submodule [has_zero ι] [semiring S] [add_comm_monoid R] [module S R] (A : ι → submodule S R) : set_like.is_homogeneous A (0 : R) := ⟨0, submodule.zero_mem _⟩ lemma set_like.is_homogeneous.smul [comm_semiring S] [semiring R] [algebra S R] {A : ι → submodule S R} {s : S} {r : R} (hr : set_like.is_homogeneous A r) : set_like.is_homogeneous A (s • r) := let ⟨i, hi⟩ := hr in ⟨i, submodule.smul_mem _ _ hi⟩ end homogeneous_element
31e598e20a79c2dc20d1b3318db4a5fe43029bd2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/primProjEtaIssue.lean
582981a337455f753aa49de401afbae4b5157324
[ "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
272
lean
example (f : Fin n → Prop) (h : ∀ i h, i = 0 → f ⟨i, h⟩) : f i := by apply h rw [show i.1 = 0 from sorry] def foo (x : Fin n) : Nat := match x with | ⟨i, _⟩ => 5 + i example (x : Fin n) : foo x = 5 := by simp [foo] rw [show x.1 = 0 from sorry]
f9825b85988b0951297f7e4247a32d511e3f9e86
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/ToExpr.lean
0f56dc29d486779786f325eacaf9cfdc3f51acc9
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
2,708
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.Expr universe u namespace Lean class ToExpr (α : Type u) where toExpr : α → Expr toTypeExpr : Expr export ToExpr (toExpr toTypeExpr) instance : ToExpr Expr where toExpr := id toTypeExpr := mkConst ``Expr instance : ToExpr Nat where toExpr := mkNatLit toTypeExpr := mkConst ``Nat instance : ToExpr Bool where toExpr := fun b => if b then mkConst ``Bool.true else mkConst ``Bool.false toTypeExpr := mkConst ``Bool instance : ToExpr Char where toExpr := fun c => mkApp (mkConst ``Char.ofNat) (toExpr c.toNat) toTypeExpr := mkConst ``Char instance : ToExpr String where toExpr := mkStrLit toTypeExpr := mkConst ``String instance : ToExpr Unit where toExpr := fun _ => mkConst `Unit.unit toTypeExpr := mkConst ``Unit def Name.toExprAux : Name → Expr | Name.anonymous => mkConst `Lean.Name.anonymous | Name.str p s _ => mkAppB (mkConst ``Lean.Name.mkStr) (toExprAux p) (toExpr s) | Name.num p n _ => mkAppB (mkConst ``Lean.Name.mkNum) (toExprAux p) (toExpr n) instance : ToExpr Name where toExpr := Name.toExprAux toTypeExpr := mkConst ``Name instance {α : Type} [ToExpr α] : ToExpr (Option α) := let type := toTypeExpr α { toExpr := fun o => match o with | none => mkApp (mkConst ``Option.none [levelZero]) type | some a => mkApp2 (mkConst ``Option.some [levelZero]) type (toExpr a), toTypeExpr := mkApp (mkConst ``Option [levelZero]) type } def List.toExprAux {α} [ToExpr α] (nilFn : Expr) (consFn : Expr) : List α → Expr | [] => nilFn | a::as => mkApp2 consFn (toExpr a) (toExprAux nilFn consFn as) instance {α : Type} [ToExpr α] : ToExpr (List α) := let type := toTypeExpr α let nil := mkApp (mkConst ``List.nil [levelZero]) type let cons := mkApp (mkConst ``List.cons [levelZero]) type { toExpr := List.toExprAux nil cons, toTypeExpr := mkApp (mkConst ``List [levelZero]) type } instance {α : Type} [ToExpr α] : ToExpr (Array α) := let type := toTypeExpr α { toExpr := fun as => mkApp2 (mkConst ``List.toArray [levelZero]) type (toExpr as.toList), toTypeExpr := mkApp (mkConst ``Array [levelZero]) type } instance {α : Type} {β : Type} [ToExpr α] [ToExpr β] : ToExpr (α × β) := let αType := toTypeExpr α let βType := toTypeExpr β { toExpr := fun ⟨a, b⟩ => mkApp4 (mkConst ``Prod.mk [levelZero, levelZero]) αType βType (toExpr a) (toExpr b), toTypeExpr := mkApp2 (mkConst ``Prod [levelZero, levelZero]) αType βType } end Lean
0408474a87c7a69ac3b2157666b1acac64c27ac9
94e33a31faa76775069b071adea97e86e218a8ee
/src/tactic/ring.lean
8aff0fdd568ab42f7135c0705c8cbec989092b37
[ "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
32,374
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 tactic.norm_num /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (α : Type) : Type := reader_t cache tactic α /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : ℕ) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m ℕ := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. This version of `ring_m.run` uses an external atoms ref, so that subexpressions can be named across multiple `ring_m` calls. -/ meta def ring_m.run' (red : transparency) (atoms : ref (buffer expr)) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache α, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(ℕ), using_new_ref ic $ λ r, using_new_ref nc $ λ nr, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := using_new_ref mk_buffer $ λ atoms, ring_m.run' red atoms e m /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/ @[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α} (f : instance_cache → tactic (instance_cache × α)) : ring_m α := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `α`. -/ @[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `ℕ`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `ℕ` and `ℚ` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : ℚ) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr → expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr → bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr (λ _, expr → expr) := ⟨λ e, ⇑(e : expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr → string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr → tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ λ nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm (x ^ n)]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := ic_lift $ λ ic, do let n := c₁ + c₂, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ e₂ e c₁ c₂ n, return (ic, const e n, p) | he₁@(const e₁ c₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``zero_add [e₂], return (ic, he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂ c₂) := do c ← get_cache, if c₂ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek n₂.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0 0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₂.1 ek n₁.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0 0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ic_lift $ λ ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr × ℚ) : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic e₁ e₂ c₁ c₂, return (const e' (c₁ * c₂), p) | (const e₁ c₁) e₂ := if c₁ = 0 then do c ← get_cache, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ λ ic, ic.mk_app ``zero_mul [e₂], return (const α0 0, p) else if c₁ = 1 then do p ← ic_lift $ λ ic, ic.mk_app ``one_mul [e₂], return (e₂, p) else eval_const_mul (e₁, c₁) e₂ | e₁ he₂@(const e₂ c₂) := do p₁ ← ic_lift $ λ ic, ic.mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (haa, h₂) ← eval_horner aa x₁ n₂ (const α0 0), if b₂.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] theorem pow_succ {α} [comm_semiring α] (a n b c) (h₁ : (a:α) ^ n = b) (h₂ : b * a = c) : a ^ (n + 1) = c := by rw [← h₂, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], p ← ic_lift $ λ ic, ic.mk_app ``pow_zero [e], return (const α1 1, p) | e (_, 1) := do p ← ic_lift $ λ ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (e₂, m) := ic_lift $ λ ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic e₂, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ λ nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', h₂) ← eval_pow a m, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const α0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← nc_lift $ λ nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, e₂, tl, t, hl, p₂]) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], return (xadd' c (const α1 1) (e, i) (`(1), 1) (const α0 0), c.cs_app ``horner_atom [e]) /-- Evaluate `a` where `a` is an atom. -/ meta def eval_norm_atom (norm_atom : expr → tactic (expr × expr)) (e : expr) : ring_m (horner_expr × expr) := do o ← lift $ try_core (guard (e.get_app_args.length > 0) >> norm_atom e), match o with | none := eval_atom e | some (e', p) := do (e₂, p₂) ← eval_atom e', prod.mk e₂ <$> lift (mk_eq_trans p p₂) end lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := by rw [div_eq_mul_inv, h] /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval (norm_atom : expr → tactic (expr × expr)) : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%inst %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_neg.neg [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_sub [e₁, e₂, e', p], return (e', p')) (eval_norm_atom norm_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_norm_atom norm_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ic_lift $ λ ic, ic.mk_app ``div_inv_monoid.to_has_div [], lift $ is_def_eq inst inst')) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_inv.inv [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_div [e₁, e₂, e', p], return (e', p')) (eval_norm_atom norm_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | _, _ := eval_norm_atom norm_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_norm_atom norm_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (atoms : ref (buffer expr)) (norm_atom : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := ring_m.run' red atoms e $ do (e', p) ← eval norm_atom e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := (sub_eq_add_neg a b).symm /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive [has_reflect, decidable_eq]] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. See `normalize`. This version takes a list of atoms to persist across multiple calls. * `atoms`: a mutable reference containing the atom set from the previous call * `red`: the reducibility setting to use when comparing atoms for defeq * `mode`: the normalization style (see `normalize_mode`) * `recursive`: if true, atoms will be reduced recursively using `normalize'` * `e`: the expression to normalize * `inner`: This should be set to `ff`. It is used internally to disable normalization at the top level when called from `eval` in order to prevent an infinite loop `eval' -> eval_atom -> normalize' -> eval'` when called on something that can't be simplified like `x`. -/ meta def normalize' (atoms : ref (buffer expr)) (red : transparency) (mode := normalize_mode.horner) (recursive := tt) : expr → opt_param _ ff → tactic (expr × expr) | e inner := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, trans_conv (λ e, do guard (mode ≠ normalize_mode.raw), (e', pr, _) ← simplify simp_lemmas.mk [] e, pure (e', pr)) (λ e, do a ← read_ref atoms, let norm_rec := if recursive then λ e, normalize' e tt else λ _, failed, (a, e', pr) ← ext_simplify_core a {} simp_lemmas.mk (λ _, failed) (λ a _ _ p e, do guard (inner → p.is_some), write_ref atoms a, (new_e, pr) ← eval' red atoms norm_rec e, (new_e, pr) ← match mode with | normalize_mode.raw := λ _, pure (new_e, pr) | normalize_mode.horner := trans_conv (λ _, pure (new_e, pr)) (λ e, do (e', prf, _) ← simplify lemmas [] e, pure (e', prf)) | normalize_mode.SOP := trans_conv (λ _, pure (new_e, pr)) $ trans_conv (λ e, do (e', prf, _) ← simplify lemmas [] e, pure (e', prf)) $ simp_bottom_up' (λ e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), a ← read_ref atoms, pure (a, new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, write_ref atoms a, pure (e', pr)) e /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (recursive := tt) (e : expr) : tactic (expr × expr) := using_new_ref mk_buffer $ λ atoms, normalize' atoms red mode recursive e /-- Configuration for `ring_nf`. * `recursive`: if true, atoms inside ring expressions will be reduced recursively -/ @[derive inhabited] structure ring_nf_cfg := (recursive := tt) end ring namespace interactive open tactic.ring setup_tactic_parser /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target >>= instantiate_mvars, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval (λ _, failed) e₁ <*> eval (λ _, failed) e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring_nf`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := pure ring.normalize_mode.horner | some `horner := pure ring.normalize_mode.horner | some `SOP := pure ring.normalize_mode.SOP | some `raw := pure ring.normalize_mode.raw | _ := failed end /-- Simplification tactic for expressions in the language of commutative (semi)rings, which rewrites all ring expressions into a normal form. When writing a normal form, `ring_nf SOP` will use sum-of-products form instead of horner form. `ring_nf!` will use a more aggressive reducibility setting to identify atoms. -/ meta def ring_nf (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) (cfg : ring_nf_cfg := {}) : tactic unit := do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← using_new_ref mk_buffer $ λ atoms, tactic.replace_at (normalize' atoms transp SOP cfg.recursive) ns loc.include_goal | fail "ring_nf failed to simplify", when loc.include_goal $ try tactic.reflexivity /-- Tactic for solving equations in the language of *commutative* (semi)rings. `ring!` will use a more aggressive reducibility setting to identify atoms. If the goal is not solvable, it falls back to rewriting all ring expressions into a normal form, with a suggestion to use `ring_nf` instead, if this is the intent. See also `ring1`, which is the same as `ring` but without the fallback behavior. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) : tactic unit := ring1 red <|> (ring_nf red normalize_mode.horner (loc.ns [none]) >> trace "Try this: ring_nf") add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [``ring, ``ring_nf, ``ring1], inherit_description_from := ``ring, tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize normalize_mode.horner) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring_nf (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) (cfg : ring.ring_nf_cfg := {}) : conv unit := let transp := if red.is_some then semireducible else reducible in replace_lhs (normalize transp SOP cfg.recursive) <|> fail "ring_nf failed to simplify" /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> (replace_lhs (normalize transp normalize_mode.horner) >> trace "Try this: ring_nf") <|> fail "ring failed to simplify" end conv.interactive
23dd74162e79326c9ddff2c5794a12f34ca9eae7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/Simp/InlineCandidate.lean
d0c3fa33cf72cdc27b608fc9494d71be83d0bb9c
[ "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
4,396
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.Simp.SimpM namespace Lean.Compiler.LCNF namespace Simp /-- Result of `inlineCandidate?`. It contains information for inlining local and global functions. -/ structure InlineCandidateInfo where isLocal : Bool params : Array Param /-- Value (lambda expression) of the function to be inlined. -/ value : Code fType : Expr args : Array Arg /-- `ifReduce = true` if the declaration being inlined was tagged with `inline_if_reduce`. -/ ifReduce : Bool /-- `recursive = true` if the declaration being inline is in a mutually recursive block. -/ recursive : Bool := false /-- The arity (aka number of parameters) of the function to be inlined. -/ def InlineCandidateInfo.arity : InlineCandidateInfo → Nat | { params, .. } => params.size /-- Return `some info` if `e` should be inlined. -/ def inlineCandidate? (e : LetValue) : SimpM (Option InlineCandidateInfo) := do let mut e := e let mut mustInline := false if let .const ``inline _ #[_, .fvar argFVarId] := e then let some decl ← findLetDecl? argFVarId | return none e := decl.value mustInline := true if let .const declName us args := e then unless (← read).config.inlineDefs do return none let some decl ← getDecl? declName | return none let shouldInline : SimpM Bool := do if !decl.inlineIfReduceAttr && decl.recursive then return false if mustInline then return true /- We don't inline instances tagged with `[inline]/[always_inline]/[inline_if_reduce]` at the base phase We assume that at the base phase these annotations are for the instance methods that have been lambda lifted. -/ if (← inBasePhase <&&> Meta.isInstance decl.name) then unless decl.name == ``instDecidableEqBool do /- TODO: remove this hack after we refactor `Decidable` as suggested by Gabriel. Recall that the current `Decidable` class is special case since it is an inductive datatype which is not a structure like all other type classes. This is bad since it prevents us from treating all classes in a uniform way. After we change `Decidable` to a structure as suggested by Gabriel, we should only accept type classes that are structures. Moreover, we should reject instances that have only one exit point producing an explicit structure. -/ return false if decl.alwaysInlineAttr then return true -- TODO: check inlining quota if decl.inlineAttr || decl.inlineIfReduceAttr then return true unless decl.noinlineAttr do if (← isSmall decl.value) then return true return false unless (← shouldInline) do return none /- check arity -/ let arity := decl.getArity let inlinePartial := (← read).config.inlinePartial if !mustInline && !inlinePartial && args.size < arity then return none if decl.inlineIfReduceAttr then let some paramIdx := decl.isCasesOnParam? | return none unless paramIdx < args.size do return none let arg := args[paramIdx]! unless (← arg.isConstructorApp) do return none let params := decl.instantiateParamsLevelParams us let value := decl.instantiateValueLevelParams us let type := decl.instantiateTypeLevelParams us incInline return some { isLocal := false fType := type args := args ifReduce := decl.inlineIfReduceAttr recursive := decl.recursive params, value } else if let .fvar f args := e then let some decl ← findFunDecl'? f | return none unless args.size > 0 do return none -- It is not worth to inline a local function that does not take any arguments unless mustInline || (← shouldInlineLocal decl) do return none -- Remark: we inline local function declarations even if they are partial applied incInlineLocal modify fun s => { s with inlineLocal := s.inlineLocal + 1 } return some { isLocal := true fType := (← getType f) args := args params := decl.params value := decl.value ifReduce := false } else return none builtin_initialize registerTraceClass `Compiler.simp.inline
56de2dd4dfa12583c4a73c485b183a03acd6ac0f
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebraic_geometry/stalks.lean
4977ee080479ce49ec91904cf77118bcd6ab4471
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
2,054
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebraic_geometry.presheafed_space import topology.sheaves.stalks /-! # Stalks for presheaved spaces This file lifts constructions of stalks and pushforwards of stalks to work with the category of presheafed spaces. -/ universes v u v' u' open category_theory open category_theory.limits category_theory.category category_theory.functor open algebraic_geometry open topological_space variables {C : Type u} [category.{v} C] [has_colimits C] local attribute [tidy] tactic.op_induction' open Top.presheaf namespace algebraic_geometry.PresheafedSpace def stalk (X : PresheafedSpace C) (x : X) : C := X.𝒪.stalk x def stalk_map {X Y : PresheafedSpace C} (α : X ⟶ Y) (x : X) : Y.stalk (α x) ⟶ X.stalk x := (stalk_functor C (α x)).map (α.c) ≫ X.𝒪.stalk_pushforward C α x namespace stalk_map @[simp] lemma id (X : PresheafedSpace C) (x : X) : stalk_map (𝟙 X) x = 𝟙 (X.stalk x) := begin dsimp [stalk_map], simp only [stalk_pushforward.id], rw [←map_comp], convert (stalk_functor C x).map_id X.𝒪, tidy, end -- TODO understand why this proof is still gross (i.e. requires using `erw`) @[simp] lemma comp {X Y Z : PresheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (x : X) : stalk_map (α ≫ β) x = (stalk_map β (α x) : Z.stalk (β (α x)) ⟶ Y.stalk (α x)) ≫ (stalk_map α x : Y.stalk (α x) ⟶ X.stalk x) := begin dsimp [stalk_map, stalk_functor, stalk_pushforward], ext U, op_induction U, cases U, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre, whisker_left_app, whisker_right_app, assoc, id_comp, map_id, map_comp], dsimp, simp only [map_id, assoc, pushforward.comp_inv_app], -- FIXME Why doesn't simp do this: erw [category_theory.functor.map_id], erw [category_theory.functor.map_id], erw [id_comp, id_comp, id_comp], end end stalk_map end algebraic_geometry.PresheafedSpace
28f8e2cf67f4d308ac2270eec1ad311f5d1f251e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/Basic.lean
009ffc7ae78eeafd012181981bd7c23f6d73329c
[ "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
25,497
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr import Lean.Meta.Instances import Lean.Compiler.InlineAttrs import Lean.Compiler.Specialize import Lean.Compiler.LCNF.Types namespace Lean.Compiler.LCNF /-! # Lean Compiler Normal Form (LCNF) It is based on the [A-normal form](https://en.wikipedia.org/wiki/A-normal_form), and the approach described in the paper [Compiling without continuations](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/compiling-without-continuations.pdf). -/ structure Param where fvarId : FVarId binderName : Name type : Expr borrow : Bool deriving Inhabited, BEq def Param.toExpr (p : Param) : Expr := .fvar p.fvarId inductive AltCore (Code : Type) where | alt (ctorName : Name) (params : Array Param) (code : Code) | default (code : Code) deriving Inhabited inductive LitValue where | natVal (val : Nat) | strVal (val : String) -- TODO: add constructors for `Int`, `Float`, `UInt` ... deriving Inhabited, BEq, Hashable def LitValue.toExpr : LitValue → Expr | .natVal v => .lit (.natVal v) | .strVal v => .lit (.strVal v) inductive Arg where | erased | fvar (fvarId : FVarId) | type (expr : Expr) deriving Inhabited, BEq, Hashable def Param.toArg (p : Param) : Arg := .fvar p.fvarId def Arg.toExpr (arg : Arg) : Expr := match arg with | .erased => erasedExpr | .fvar fvarId => .fvar fvarId | .type e => e private unsafe def Arg.updateTypeImp (arg : Arg) (type' : Expr) : Arg := match arg with | .type ty => if ptrEq ty type' then arg else .type type' | _ => unreachable! @[implemented_by Arg.updateTypeImp] opaque Arg.updateType! (arg : Arg) (type : Expr) : Arg private unsafe def Arg.updateFVarImp (arg : Arg) (fvarId' : FVarId) : Arg := match arg with | .fvar fvarId => if fvarId' == fvarId then arg else .fvar fvarId' | _ => unreachable! @[implemented_by Arg.updateFVarImp] opaque Arg.updateFVar! (arg : Arg) (fvarId' : FVarId) : Arg inductive LetValue where | value (value : LitValue) | erased | proj (typeName : Name) (idx : Nat) (struct : FVarId) | const (declName : Name) (us : List Level) (args : Array Arg) | fvar (fvarId : FVarId) (args : Array Arg) -- TODO: add constructors for mono and impure phases deriving Inhabited, BEq, Hashable def Arg.toLetValue (arg : Arg) : LetValue := match arg with | .fvar fvarId => .fvar fvarId #[] | .erased | .type .. => .erased private unsafe def LetValue.updateProjImp (e : LetValue) (fvarId' : FVarId) : LetValue := match e with | .proj s i fvarId => if fvarId == fvarId' then e else .proj s i fvarId' | _ => unreachable! @[implemented_by LetValue.updateProjImp] opaque LetValue.updateProj! (e : LetValue) (fvarId' : FVarId) : LetValue private unsafe def LetValue.updateConstImp (e : LetValue) (declName' : Name) (us' : List Level) (args' : Array Arg) : LetValue := match e with | .const declName us args => if declName == declName' && ptrEq us us' && ptrEq args args' then e else .const declName' us' args' | _ => unreachable! @[implemented_by LetValue.updateConstImp] opaque LetValue.updateConst! (e : LetValue) (declName' : Name) (us' : List Level) (args' : Array Arg) : LetValue private unsafe def LetValue.updateFVarImp (e : LetValue) (fvarId' : FVarId) (args' : Array Arg) : LetValue := match e with | .fvar fvarId args => if fvarId == fvarId' && ptrEq args args' then e else .fvar fvarId' args' | _ => unreachable! @[implemented_by LetValue.updateFVarImp] opaque LetValue.updateFVar! (e : LetValue) (fvarId' : FVarId) (args' : Array Arg) : LetValue private unsafe def LetValue.updateArgsImp (e : LetValue) (args' : Array Arg) : LetValue := match e with | .const declName us args => if ptrEq args args' then e else .const declName us args' | .fvar fvarId args => if ptrEq args args' then e else .fvar fvarId args' | _ => unreachable! @[implemented_by LetValue.updateArgsImp] opaque LetValue.updateArgs! (e : LetValue) (args' : Array Arg) : LetValue def LetValue.toExpr (e : LetValue) : Expr := match e with | .value (.natVal val) => .lit (.natVal val) | .value (.strVal val) => .lit (.strVal val) | .erased => erasedExpr | .proj n i s => .proj n i (.fvar s) | .const n us as => mkAppN (.const n us) (as.map Arg.toExpr) | .fvar fvarId as => mkAppN (.fvar fvarId) (as.map Arg.toExpr) structure LetDecl where fvarId : FVarId binderName : Name type : Expr value : LetValue deriving Inhabited, BEq structure FunDeclCore (Code : Type) where fvarId : FVarId binderName : Name params : Array Param type : Expr value : Code deriving Inhabited def FunDeclCore.getArity (decl : FunDeclCore Code) : Nat := decl.params.size structure CasesCore (Code : Type) where typeName : Name resultType : Expr discr : FVarId alts : Array (AltCore Code) deriving Inhabited inductive Code where | let (decl : LetDecl) (k : Code) | fun (decl : FunDeclCore Code) (k : Code) | jp (decl : FunDeclCore Code) (k : Code) | jmp (fvarId : FVarId) (args : Array Arg) | cases (cases : CasesCore Code) | return (fvarId : FVarId) | unreach (type : Expr) deriving Inhabited abbrev Alt := AltCore Code abbrev FunDecl := FunDeclCore Code abbrev Cases := CasesCore Code /-- Return the constructor names that have an explicit (non-default) alternative. -/ def CasesCore.getCtorNames (c : Cases) : NameSet := c.alts.foldl (init := {}) fun ctorNames alt => match alt with | .default _ => ctorNames | .alt ctorName .. => ctorNames.insert ctorName inductive CodeDecl where | let (decl : LetDecl) | fun (decl : FunDecl) | jp (decl : FunDecl) deriving Inhabited def CodeDecl.fvarId : CodeDecl → FVarId | .let decl | .fun decl | .jp decl => decl.fvarId def attachCodeDecls (decls : Array CodeDecl) (code : Code) : Code := go decls.size code where go (i : Nat) (code : Code) : Code := if i > 0 then match decls[i-1]! with | .let decl => go (i-1) (.let decl code) | .fun decl => go (i-1) (.fun decl code) | .jp decl => go (i-1) (.jp decl code) else code mutual private unsafe def eqImp (c₁ c₂ : Code) : Bool := if ptrEq c₁ c₂ then true else match c₁, c₂ with | .let d₁ k₁, .let d₂ k₂ => d₁ == d₂ && eqImp k₁ k₂ | .fun d₁ k₁, .fun d₂ k₂ | .jp d₁ k₁, .jp d₂ k₂ => eqFunDecl d₁ d₂ && eqImp k₁ k₂ | .cases c₁, .cases c₂ => eqCases c₁ c₂ | .jmp j₁ as₁, .jmp j₂ as₂ => j₁ == j₂ && as₁ == as₂ | .return r₁, .return r₂ => r₁ == r₂ | .unreach t₁, .unreach t₂ => t₁ == t₂ | _, _ => false private unsafe def eqFunDecl (d₁ d₂ : FunDecl) : Bool := if ptrEq d₁ d₂ then true else d₁.fvarId == d₂.fvarId && d₁.binderName == d₂.binderName && d₁.params == d₂.params && d₁.type == d₂.type && eqImp d₁.value d₂.value private unsafe def eqCases (c₁ c₂ : Cases) : Bool := c₁.resultType == c₂.resultType && c₁.discr == c₂.discr && c₁.typeName == c₂.typeName && c₁.alts.isEqv c₂.alts eqAlt private unsafe def eqAlt (a₁ a₂ : Alt) : Bool := match a₁, a₂ with | .default k₁, .default k₂ => eqImp k₁ k₂ | .alt c₁ ps₁ k₁, .alt c₂ ps₂ k₂ => c₁ == c₂ && ps₁ == ps₂ && eqImp k₁ k₂ | _, _ => false end @[implemented_by eqImp] protected opaque Code.beq : Code → Code → Bool instance : BEq Code where beq := Code.beq @[implemented_by eqFunDecl] protected opaque FunDecl.beq : FunDecl → FunDecl → Bool instance : BEq FunDecl where beq := FunDecl.beq def AltCore.getCode : Alt → Code | .default k => k | .alt _ _ k => k def AltCore.getParams : Alt → Array Param | .default _ => #[] | .alt _ ps _ => ps def AltCore.forCodeM [Monad m] (alt : Alt) (f : Code → m Unit) : m Unit := do match alt with | .default k => f k | .alt _ _ k => f k private unsafe def updateAltCodeImp (alt : Alt) (k' : Code) : Alt := match alt with | .default k => if ptrEq k k' then alt else .default k' | .alt ctorName ps k => if ptrEq k k' then alt else .alt ctorName ps k' @[implemented_by updateAltCodeImp] opaque AltCore.updateCode (alt : Alt) (c : Code) : Alt private unsafe def updateAltImp (alt : Alt) (ps' : Array Param) (k' : Code) : Alt := match alt with | .alt ctorName ps k => if ptrEq k k' && ptrEq ps ps' then alt else .alt ctorName ps' k' | _ => unreachable! @[implemented_by updateAltImp] opaque AltCore.updateAlt! (alt : Alt) (ps' : Array Param) (k' : Code) : Alt @[inline] private unsafe def updateAltsImp (c : Code) (alts : Array Alt) : Code := match c with | .cases cs => if ptrEq cs.alts alts then c else .cases { cs with alts } | _ => unreachable! @[implemented_by updateAltsImp] opaque Code.updateAlts! (c : Code) (alts : Array Alt) : Code @[inline] private unsafe def updateCasesImp (c : Code) (resultType : Expr) (discr : FVarId) (alts : Array Alt) : Code := match c with | .cases cs => if ptrEq cs.alts alts && ptrEq cs.resultType resultType && cs.discr == discr then c else .cases { cs with discr, resultType, alts } | _ => unreachable! @[implemented_by updateCasesImp] opaque Code.updateCases! (c : Code) (resultType : Expr) (discr : FVarId) (alts : Array Alt) : Code @[inline] private unsafe def updateLetImp (c : Code) (decl' : LetDecl) (k' : Code) : Code := match c with | .let decl k => if ptrEq k k' && ptrEq decl decl' then c else .let decl' k' | _ => unreachable! @[implemented_by updateLetImp] opaque Code.updateLet! (c : Code) (decl' : LetDecl) (k' : Code) : Code @[inline] private unsafe def updateContImp (c : Code) (k' : Code) : Code := match c with | .let decl k => if ptrEq k k' then c else .let decl k' | .fun decl k => if ptrEq k k' then c else .fun decl k' | .jp decl k => if ptrEq k k' then c else .jp decl k' | _ => unreachable! @[implemented_by updateContImp] opaque Code.updateCont! (c : Code) (k' : Code) : Code @[inline] private unsafe def updateFunImp (c : Code) (decl' : FunDecl) (k' : Code) : Code := match c with | .fun decl k => if ptrEq k k' && ptrEq decl decl' then c else .fun decl' k' | .jp decl k => if ptrEq k k' && ptrEq decl decl' then c else .jp decl' k' | _ => unreachable! @[implemented_by updateFunImp] opaque Code.updateFun! (c : Code) (decl' : FunDecl) (k' : Code) : Code @[inline] private unsafe def updateReturnImp (c : Code) (fvarId' : FVarId) : Code := match c with | .return fvarId => if fvarId == fvarId' then c else .return fvarId' | _ => unreachable! @[implemented_by updateReturnImp] opaque Code.updateReturn! (c : Code) (fvarId' : FVarId) : Code @[inline] private unsafe def updateJmpImp (c : Code) (fvarId' : FVarId) (args' : Array Arg) : Code := match c with | .jmp fvarId args => if fvarId == fvarId' && ptrEq args args' then c else .jmp fvarId' args' | _ => unreachable! @[implemented_by updateJmpImp] opaque Code.updateJmp! (c : Code) (fvarId' : FVarId) (args' : Array Arg) : Code @[inline] private unsafe def updateUnreachImp (c : Code) (type' : Expr) : Code := match c with | .unreach type => if ptrEq type type' then c else .unreach type' | _ => unreachable! @[implemented_by updateUnreachImp] opaque Code.updateUnreach! (c : Code) (type' : Expr) : Code private unsafe def updateParamCoreImp (p : Param) (type : Expr) : Param := if ptrEq type p.type then p else { p with type } /-- Low-level update `Param` function. It does not update the local context. Consider using `Param.update : Param → Expr → CompilerM Param` if you want the local context to be updated. -/ @[implemented_by updateParamCoreImp] opaque Param.updateCore (p : Param) (type : Expr) : Param private unsafe def updateLetDeclCoreImp (decl : LetDecl) (type : Expr) (value : LetValue) : LetDecl := if ptrEq type decl.type && ptrEq value decl.value then decl else { decl with type, value } /-- Low-level update `LetDecl` function. It does not update the local context. Consider using `LetDecl.update : LetDecl → Expr → Expr → CompilerM LetDecl` if you want the local context to be updated. -/ @[implemented_by updateLetDeclCoreImp] opaque LetDecl.updateCore (decl : LetDecl) (type : Expr) (value : LetValue) : LetDecl private unsafe def updateFunDeclCoreImp (decl: FunDecl) (type : Expr) (params : Array Param) (value : Code) : FunDecl := if ptrEq type decl.type && ptrEq params decl.params && ptrEq value decl.value then decl else { decl with type, params, value } /-- Low-level update `FunDecl` function. It does not update the local context. Consider using `FunDecl.update : LetDecl → Expr → Array Param → Code → CompilerM FunDecl` if you want the local context to be updated. -/ @[implemented_by updateFunDeclCoreImp] opaque FunDeclCore.updateCore (decl: FunDecl) (type : Expr) (params : Array Param) (value : Code) : FunDecl def CasesCore.extractAlt! (cases : Cases) (ctorName : Name) : Alt × Cases := let found (i : Nat) := (cases.alts[i]!, { cases with alts := cases.alts.eraseIdx i }) if let some i := cases.alts.findIdx? fun | .alt ctorName' .. => ctorName == ctorName' | _ => false then found i else if let some i := cases.alts.findIdx? fun | .default _ => true | _ => false then found i else unreachable! def AltCore.mapCodeM [Monad m] (alt : Alt) (f : Code → m Code) : m Alt := do return alt.updateCode (← f alt.getCode) def Code.isDecl : Code → Bool | .let .. | .fun .. | .jp .. => true | _ => false def Code.isFun : Code → Bool | .fun .. => true | _ => false def Code.isReturnOf : Code → FVarId → Bool | .return fvarId, fvarId' => fvarId == fvarId' | _, _ => false partial def Code.size (c : Code) : Nat := go c 0 where go (c : Code) (n : Nat) : Nat := match c with | .let _ k => go k (n+1) | .jp decl k | .fun decl k => go k <| go decl.value n | .cases c => c.alts.foldl (init := n+1) fun n alt => go alt.getCode (n+1) | .jmp .. => n+1 | .return .. | unreach .. => n -- `return` & `unreach` have weight zero /-- Return true iff `c.size ≤ n` -/ partial def Code.sizeLe (c : Code) (n : Nat) : Bool := match go c |>.run 0 with | .ok .. => true | .error .. => false where inc : EStateM Unit Nat Unit := do modify (·+1) unless (← get) <= n do throw () go (c : Code) : EStateM Unit Nat Unit := do match c with | .let _ k => inc; go k | .jp decl k | .fun decl k => inc; go decl.value; go k | .cases c => inc; c.alts.forM fun alt => go alt.getCode | .jmp .. => inc | .return .. | unreach .. => return () partial def Code.forM [Monad m] (c : Code) (f : Code → m Unit) : m Unit := go c where go (c : Code) : m Unit := do f c match c with | .let _ k => go k | .fun decl k | .jp decl k => go decl.value; go k | .cases c => c.alts.forM fun alt => go alt.getCode | .unreach .. | .return .. | .jmp .. => return () /-- Declaration being processed by the Lean to Lean compiler passes. -/ structure Decl where /-- The name of the declaration from the `Environment` it came from -/ name : Name /-- Universe level parameter names. -/ levelParams : List Name /-- The type of the declaration. Note that this is an erased LCNF type instead of the fully dependent one that might have been the original type of the declaration in the `Environment`. -/ type : Expr /-- Parameters. -/ params : Array Param /-- The body of the declaration, usually changes as it progresses through compiler passes. -/ value : Code /-- We set this flag to true during LCNF conversion. When we receive a block of functions to be compiled, we set this flag to `true` if there is an application to the function in the block containing it. This is an approximation, but it should be good enough because in the frontend, we invoke the compiler with blocks of strongly connected components only. We use this information to control inlining. -/ recursive : Bool := false /-- We set this flag to false during LCNF conversion if the Lean function associated with this function was tagged as partial or unsafe. This information affects how static analyzers treat function applications of this kind. See `DefinitionSafety`. `partial` and `unsafe` functions may not be terminating, but Lean functions terminate, and some static analyzers exploit this fact. So, we use the following semantics. Suppose whe hav a (large) natural number `C`. We consider a nondeterministic model for computation of Lean expressions as follows: Each call to a partial/unsafe function uses up one "recursion token". Prior to consuming `C` recursion tokens all partial functions must be called as normal. Once the model has used up `C` recursion tokens, a subsequent call to a partial function has the following nondeterministic options: it can either call the function again, or return any value of the target type (even a noncomputable one). Larger values of `C` yield less nondeterminism in the model, but even the intersection of all choices of `C` yields nondeterminism where `def loop : A := loop` returns any value of type `A`. The compiler fixes a choice for `C`. This is a fixed constant greater than 2^2^64, which is allowed to be compiler and architecture dependent, and promises that it will produce an execution consistent with every possible nondeterministic outcome of the `C`-model. In the event that different nondeterministic executions disagree, the compiler is required to exhaust resources or output a looping computation. -/ safe : Bool := true /-- We store the inline attribute at LCNF declarations to make sure we can set them for auxliary declarations created during compilation. -/ inlineAttr? : Option InlineAttributeKind deriving Inhabited, BEq def Decl.size (decl : Decl) : Nat := decl.value.size def Decl.getArity (decl : Decl) : Nat := decl.params.size def Decl.inlineAttr (decl : Decl) : Bool := decl.inlineAttr? matches some .inline def Decl.noinlineAttr (decl : Decl) : Bool := decl.inlineAttr? matches some .noinline def Decl.inlineIfReduceAttr (decl : Decl) : Bool := decl.inlineAttr? matches some .inlineIfReduce def Decl.alwaysInlineAttr (decl : Decl) : Bool := decl.inlineAttr? matches some .alwaysInline /-- Return `true` if the given declaration has been annotated with `[inline]`, `[inline_if_reduce]`, `[macro_inline]`, or `[always_inline]` -/ def Decl.inlineable (decl : Decl) : Bool := match decl.inlineAttr? with | some .noinline => false | some _ => true | none => false /-- Return `some i` if `decl` is of the form ``` def f (a_0 ... a_i ...) := ... cases a_i | ... | ... ``` That is, `f` is a sequence of declarations followed by a `cases` on the parameter `i`. We use this function to decide whether we should inline a declaration tagged with `[inline_if_reduce]` or not. -/ def Decl.isCasesOnParam? (decl : Decl) : Option Nat := go decl.value where go (code : Code) : Option Nat := match code with | .let _ k | .jp _ k | .fun _ k => go k | .cases c => decl.params.findIdx? fun param => param.fvarId == c.discr | _ => none def Decl.instantiateTypeLevelParams (decl : Decl) (us : List Level) : Expr := decl.type.instantiateLevelParamsNoCache decl.levelParams us def Decl.instantiateParamsLevelParams (decl : Decl) (us : List Level) : Array Param := decl.params.mapMono fun param => param.updateCore (param.type.instantiateLevelParamsNoCache decl.levelParams us) partial def Decl.instantiateValueLevelParams (decl : Decl) (us : List Level) : Code := instCode decl.value where instLevel (u : Level) := u.instantiateParams decl.levelParams us instExpr (e : Expr) := e.instantiateLevelParamsNoCache decl.levelParams us instParams (ps : Array Param) := ps.mapMono fun p => p.updateCore (instExpr p.type) instAlt (alt : Alt) := match alt with | .default k => alt.updateCode (instCode k) | .alt _ ps k => alt.updateAlt! (instParams ps) (instCode k) instArg (arg : Arg) : Arg := match arg with | .type e => arg.updateType! (instExpr e) | .fvar .. | .erased => arg instLetValue (e : LetValue) : LetValue := match e with | .const declName vs args => e.updateConst! declName (vs.mapMono instLevel) (args.mapMono instArg) | .fvar fvarId args => e.updateFVar! fvarId (args.mapMono instArg) | .proj .. | .value .. | .erased => e instLetDecl (decl : LetDecl) := decl.updateCore (instExpr decl.type) (instLetValue decl.value) instFunDecl (decl : FunDecl) := decl.updateCore (instExpr decl.type) (instParams decl.params) (instCode decl.value) instCode (code : Code) := match code with | .let decl k => code.updateLet! (instLetDecl decl) (instCode k) | .jp decl k | .fun decl k => code.updateFun! (instFunDecl decl) (instCode k) | .cases c => code.updateCases! (instExpr c.resultType) c.discr (c.alts.mapMono instAlt) | .jmp fvarId args => code.updateJmp! fvarId (args.mapMono instArg) | .return .. => code | .unreach type => code.updateUnreach! (instExpr type) /-- Return `true` if the arrow type contains an instance implicit argument. -/ def hasLocalInst (type : Expr) : Bool := match type with | .forallE _ _ b bi => bi.isInstImplicit || hasLocalInst b | _ => false /-- Return `true` if `decl` is supposed to be inlined/specialized. -/ def Decl.isTemplateLike (decl : Decl) : CoreM Bool := do if hasLocalInst decl.type then return true -- `decl` applications will be specialized else if (← Meta.isInstance decl.name) then return true -- `decl` is "fuel" for code specialization else if decl.inlineable || hasSpecializeAttribute (← getEnv) decl.name then return true -- `decl` is going to be inlined or specialized else return false private partial def collectType (e : Expr) : FVarIdSet → FVarIdSet := match e with | .forallE _ d b _ => collectType b ∘ collectType d | .lam _ d b _ => collectType b ∘ collectType d | .app f a => collectType f ∘ collectType a | .fvar fvarId => fun s => s.insert fvarId | .proj .. | .letE .. | .mdata .. => unreachable! | _ => id private def collectArg (arg : Arg) (s : FVarIdSet) : FVarIdSet := match arg with | .erased => s | .fvar fvarId => s.insert fvarId | .type e => collectType e s private def collectArgs (args : Array Arg) (s : FVarIdSet) : FVarIdSet := args.foldl (init := s) fun s arg => collectArg arg s private def collectLetValue (e : LetValue) (s : FVarIdSet) : FVarIdSet := match e with | .fvar fvarId args => collectArgs args <| s.insert fvarId | .const _ _ args => collectArgs args s | .proj _ _ fvarId => s.insert fvarId | .value .. | .erased => s private partial def collectParams (ps : Array Param) (s : FVarIdSet) : FVarIdSet := ps.foldl (init := s) fun s p => collectType p.type s mutual partial def FunDeclCore.collectUsed (decl : FunDecl) (s : FVarIdSet := {}) : FVarIdSet := decl.value.collectUsed <| collectParams decl.params <| collectType decl.type s partial def Code.collectUsed (code : Code) (s : FVarIdSet := {}) : FVarIdSet := match code with | .let decl k => k.collectUsed <| collectLetValue decl.value <| collectType decl.type s | .jp decl k | .fun decl k => k.collectUsed <| decl.collectUsed s | .cases c => let s := s.insert c.discr let s := collectType c.resultType s c.alts.foldl (init := s) fun s alt => match alt with | .default k => k.collectUsed s | .alt _ ps k => k.collectUsed <| collectParams ps s | .return fvarId => s.insert fvarId | .unreach type => collectType type s | .jmp fvarId args => collectArgs args <| s.insert fvarId end abbrev collectUsedAtExpr (s : FVarIdSet) (e : Expr) : FVarIdSet := collectType e s /-- Traverse the given block of potentially mutually recursive functions and mark a declaration `f` as recursive if there is an application `f ...` in the block. This is an overapproximation, and relies on the fact that our frontend computes strongly connected components. See comment at `recursive` field. -/ partial def markRecDecls (decls : Array Decl) : Array Decl := let (_, isRec) := go |>.run {} decls.map fun decl => if isRec.contains decl.name then { decl with recursive := true } else decl where visit (code : Code) : StateM NameSet Unit := do match code with | .jp decl k | .fun decl k => visit decl.value; visit k | .cases c => c.alts.forM fun alt => visit alt.getCode | .unreach .. | .jmp .. | .return .. => return () | .let decl k => if let .const declName _ _ := decl.value then if decls.any (·.name == declName) then modify fun s => s.insert declName visit k go : StateM NameSet Unit := decls.forM fun decl => visit decl.value def instantiateRangeArgs (e : Expr) (beginIdx endIdx : Nat) (args : Array Arg) : Expr := if !e.hasLooseBVars then e else e.instantiateRange beginIdx endIdx (args.map (·.toExpr)) def instantiateRevRangeArgs (e : Expr) (beginIdx endIdx : Nat) (args : Array Arg) : Expr := if !e.hasLooseBVars then e else e.instantiateRevRange beginIdx endIdx (args.map (·.toExpr)) end Lean.Compiler.LCNF
cb0a1a820127e07f0846ce8802691abc2ae2327f
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/for_mathlib/nonarchimedean/basic.lean
5606049736be0dcfa7bcddc1401035e96a155f20
[ "Apache-2.0" ]
permissive
semorrison/lean-perfectoid-spaces
78c1572cedbfae9c3e460d8aaf91de38616904d8
bb4311dff45791170bcb1b6a983e2591bee88a19
refs/heads/master
1,588,841,765,494
1,554,805,620,000
1,554,805,620,000
180,353,546
0
1
null
1,554,809,880,000
1,554,809,880,000
null
UTF-8
Lean
false
false
28,660
lean
import order.filter.lift import topology.algebra.ring import ring_theory.algebra import ring_theory.ideal_operations import tactic.abel tactic.chain import for_mathlib.subgroup import for_mathlib.submodule import for_mathlib.topological_groups import for_mathlib.rings import for_mathlib.pointwise local attribute [instance] set.pointwise_mul_semiring section variables (G : Type*) [group G] [topological_space G] [topological_group G] @[to_additive open_add_subgroup] def open_subgroup := { U : set G // is_open U ∧ is_subgroup U } end namespace open_subgroup open function lattice variables {G : Type*} [group G] [topological_space G] [topological_group G] variables {U V : open_subgroup G} @[to_additive open_add_subgroup.has_coe] instance : has_coe (open_subgroup G) (set G) := ⟨λ U, U.1⟩ attribute [to_additive open_add_subgroup.has_coe.equations._eqn_1] open_subgroup.has_coe.equations._eqn_1 @[to_additive open_add_subgroup.has_mem] instance : has_mem G (open_subgroup G) := ⟨λ g U, g ∈ (U : set G)⟩ attribute [to_additive open_add_subgroup.has_mem.equations._eqn_1] open_subgroup.has_mem.equations._eqn_1 @[to_additive open_add_subgroup.ext'] lemma ext' : (U = V) ↔ ((U : set G) = V) := by cases U; cases V; split; intro h; try {congr}; assumption @[extensionality, to_additive open_add_subgroup.ext] lemma ext (h : (U : set G) = V) : (U = V) := ext'.mpr h @[to_additive open_add_subgroup.coe_injective] lemma coe_injective : injective (λ U : open_subgroup G, (U : set G)) := λ U V h, ext h @[to_additive open_add_subgroup.is_add_subgroup] instance : is_subgroup (U : set G) := U.2.2 variable (U) protected lemma is_open : is_open (U : set G) := U.2.1 protected lemma one_mem : (1 : G) ∈ U := is_submonoid.one_mem (U : set G) protected lemma inv_mem {g : G} (h : g ∈ U) : g⁻¹ ∈ U := @is_subgroup.inv_mem G _ U _ g h protected lemma mul_mem {g₁ g₂ : G} (h₁ : g₁ ∈ U) (h₂ : g₂ ∈ U) : g₁ * g₂ ∈ U := @is_submonoid.mul_mem G _ U _ g₁ g₂ h₁ h₂ lemma mem_nhds_one : (U : set G) ∈ nhds (1 : G) := mem_nhds_sets U.is_open U.one_mem variable {U} instance : inhabited (open_subgroup G) := { default := ⟨set.univ, ⟨is_open_univ, by apply_instance⟩⟩ } @[to_additive open_add_subgroup.is_open_of_open_add_subgroup] lemma is_open_of_open_subgroup {s : set G} (h₁ : is_subgroup s) (h₂ : ∃ U : open_subgroup G, (U : set G) ⊆ s) : is_open s := begin rw is_open_iff_forall_mem_open, intros x hx, rcases h₂ with ⟨⟨U, h₁U, h₂U⟩, H⟩, use (λ y, y * x⁻¹) ⁻¹' U, split, { intros u hu, erw set.mem_preimage_eq at hu, replace hu := H hu, simpa using is_submonoid.mul_mem hu hx }, split, { apply continuous_mul continuous_id continuous_const, { exact h₁U }, { apply_instance } }, { erw set.mem_preimage_eq, simpa using is_submonoid.one_mem _, exact h₂U.to_is_submonoid } end section variables {H : Type*} [group H] [topological_space H] [topological_group H] def prod (U : open_subgroup G) (V : open_subgroup H) : open_subgroup (G × H) := ⟨(U : set G).prod (V : set H), is_open_prod U.is_open V.is_open, by apply_instance⟩ end instance : partial_order (open_subgroup G) := partial_order.lift _ coe_injective instance : semilattice_inf_top (open_subgroup G) := { inf := λ U V, ⟨(U : set G) ∩ V, is_open_inter U.is_open V.is_open, by apply_instance⟩, inf_le_left := λ U V, set.inter_subset_left _ _, inf_le_right := λ U V, set.inter_subset_right _ _, le_inf := λ U V W hV hW, set.subset_inter hV hW, top := default _, le_top := λ U, set.subset_univ _, ..open_subgroup.partial_order } instance : semilattice_sup_top (open_subgroup G) := { sup := λ U V, { val := group.closure ((U : set G) ∪ V), property := begin have subgrp := _, refine ⟨_, subgrp⟩, { apply is_open_of_open_subgroup subgrp, exact ⟨U, set.subset.trans (set.subset_union_left _ _) group.subset_closure⟩ }, { apply_instance } end }, le_sup_left := λ U V, set.subset.trans (set.subset_union_left _ _) group.subset_closure, le_sup_right := λ U V, set.subset.trans (set.subset_union_right _ _) group.subset_closure, sup_le := λ U V W hU hV, group.closure_subset $ set.union_subset hU hV, ..open_subgroup.lattice.semilattice_inf_top } @[simp] lemma coe_inf : (↑(U ⊓ V) : set G) = (U : set G) ∩ V := rfl lemma le_iff : U ≤ V ↔ (U : set G) ⊆ V := iff.rfl end open_subgroup namespace open_add_subgroup open lattice variables {G : Type*} [add_group G] [topological_space G] [topological_add_group G] variables {U V : open_add_subgroup G} variable (U) protected lemma is_open : is_open (U : set G) := U.2.1 attribute [to_additive open_add_subgroup.is_open] open_subgroup.is_open protected lemma zero_mem : (0 : G) ∈ U := is_add_submonoid.zero_mem (U : set G) attribute [to_additive open_add_subgroup.zero_mem] open_subgroup.one_mem protected lemma neg_mem {g : G} (h : g ∈ U) : -g ∈ U := @is_add_subgroup.neg_mem G _ U _ g h attribute [to_additive open_add_subgroup.neg_mem] open_subgroup.inv_mem protected lemma add_mem {g₁ g₂ : G} (h₁ : g₁ ∈ U) (h₂ : g₂ ∈ U) : g₁ + g₂ ∈ U := @is_add_submonoid.add_mem G _ U _ g₁ g₂ h₁ h₂ attribute [to_additive open_add_subgroup.add_mem] open_subgroup.mul_mem lemma mem_nhds_zero : (U : set G) ∈ nhds (0 : G) := mem_nhds_sets U.is_open U.zero_mem attribute [to_additive open_add_subgroup.mem_nhds_zero] open_subgroup.mem_nhds_one variable {U} variable {U} section variables {H : Type*} [add_group H] [topological_space H] [topological_add_group H] def prod (U : open_add_subgroup G) (V : open_add_subgroup H) : open_add_subgroup (G × H) := ⟨(U : set G).prod (V : set H), is_open_prod U.is_open V.is_open, by apply_instance⟩ attribute [to_additive open_add_subgroup.prod] open_subgroup.prod attribute [to_additive open_add_subgroup.prod.equations._eqn_1] open_subgroup.prod.equations._eqn_1 end instance : inhabited (open_add_subgroup G) := { default := ⟨set.univ, ⟨is_open_univ, by apply_instance⟩⟩ } attribute [to_additive open_add_subgroup.inhabited] open_subgroup.inhabited instance : partial_order (open_add_subgroup G) := partial_order.lift _ coe_injective attribute [to_additive open_add_subgroup.partial_order] open_subgroup.partial_order attribute [to_additive open_add_subgroup.partial_order.equations._eqn_1] open_subgroup.partial_order.equations._eqn_1 instance : semilattice_inf_top (open_add_subgroup G) := { inf := λ U V, ⟨(U : set G) ∩ V, is_open_inter U.is_open V.is_open, by apply_instance⟩, inf_le_left := λ U V, set.inter_subset_left _ _, inf_le_right := λ U V, set.inter_subset_right _ _, le_inf := λ U V W hV hW, set.subset_inter hV hW, top := default _, le_top := λ U, set.subset_univ _, ..open_add_subgroup.partial_order } attribute [to_additive open_add_subgroup.lattice.semilattice_inf_top] open_subgroup.lattice.semilattice_inf_top attribute [to_additive open_add_subgroup.lattice.semilattice_inf_top.equations._eqn_1] open_subgroup.lattice.semilattice_inf_top.equations._eqn_1 instance : semilattice_sup_top (open_add_subgroup G) := { sup := λ U V, { val := add_group.closure ((U : set G) ∪ V), property := begin have subgrp := _, refine ⟨_, subgrp⟩, { apply is_open_of_open_add_subgroup subgrp, exact ⟨U, set.subset.trans (set.subset_union_left _ _) add_group.subset_closure⟩ }, { apply_instance } end }, le_sup_left := λ U V, set.subset.trans (set.subset_union_left _ _) group.subset_closure, le_sup_right := λ U V, set.subset.trans (set.subset_union_right _ _) group.subset_closure, sup_le := λ U V W hU hV, group.closure_subset $ set.union_subset hU hV, ..open_add_subgroup.lattice.semilattice_inf_top } attribute [to_additive open_add_subgroup.lattice.semilattice_sup_top] open_subgroup.lattice.semilattice_sup_top attribute [to_additive open_add_subgroup.lattice.semilattice_sup_top.equations._eqn_1] open_subgroup.lattice.semilattice_sup_top.equations._eqn_1 @[simp] lemma coe_inf : (↑(U ⊓ V) : set G) = (U : set G) ∩ V := rfl attribute [to_additive open_add_subgroup.coe_inf] open_subgroup.coe_inf lemma le_iff : U ≤ V ↔ (U : set G) ⊆ V := iff.rfl attribute [to_additive open_add_subgroup.le_iff] open_subgroup.le_iff end open_add_subgroup /--A topological group is non-archimedean if every neighborhood of 1 contains an open subgroup.-/ definition topological_group.nonarchimedean (G : Type*) [group G] [topological_space G] [topological_group G] : Prop := ∀ U ∈ nhds (1 : G), ∃ V : open_subgroup G, (V : set G) ⊆ U /--A topological additive group is non-archimedean if every neighborhood of 0 contains an open subgroup.-/ definition topological_add_group.nonarchimedean (G : Type*) [add_group G] [topological_space G] [topological_add_group G] : Prop := ∀ U ∈ nhds (0 : G), ∃ V : open_add_subgroup G, (V : set G) ⊆ U attribute [to_additive topological_add_group.nonarchimedean] topological_group.nonarchimedean namespace topological_group open function set variables {G₀ : Type*} [group G₀] [topological_space G₀] [topological_group G₀] variables {G : Type*} [group G] [topological_space G] [topological_group G] variables (f : G₀ → G) [is_group_hom f] @[to_additive topological_add_group.nonarchimedean_of_nonarchimedean_open_embedding] lemma nonarchimedean_of_nonarchimedean_open_embedding (emb : embedding f) (hf : is_open (range f)) (h : nonarchimedean G₀) : nonarchimedean G := begin intros U hU, cases h (f ⁻¹' U) _ with V hV, { refine ⟨⟨f '' V, _, _⟩, _⟩, { exact embedding_open emb hf V.is_open }, { apply_instance }, { rwa ← set.image_subset_iff at hV } }, { apply continuous.tendsto (emb.continuous), rwa is_group_hom.one f } end end topological_group namespace topological_add_group namespace nonarchimedean open topological_ring variables {R : Type*} [ring R] [topological_space R] [topological_ring R] variables {S : Type*} [ring S] [topological_space S] [topological_ring S] lemma left_mul_subset (h : nonarchimedean R) (U : open_add_subgroup R) (r : R) : ∃ V : open_add_subgroup R, r • (V : set R) ⊆ U := begin let V : open_add_subgroup R := ⟨_, _, _⟩, { use V, intros x hx, rw set.mem_smul_set at hx, rcases hx with ⟨y, hy, rfl⟩, exact hy }, { apply continuous_mul continuous_const continuous_id, exact U.is_open, apply_instance }, { refine {..}; intros, { show r * 0 ∈ U, simpa using U.zero_mem }, { show r * (_ + _) ∈ U, rw left_distrib, apply U.add_mem, assumption' }, { show r * _ ∈ U, rw mul_neg_eq_neg_mul_symm, apply U.neg_mem, assumption } }, end lemma prod_subset (hR : nonarchimedean R) (hS : nonarchimedean S) : ∀ U ∈ nhds (0 : R × S), ∃ (V : open_add_subgroup R) (W : open_add_subgroup S), (V : set R).prod (W : set S) ⊆ U := begin intros U hU, erw [nhds_prod_eq, filter.mem_prod_iff] at hU, rcases hU with ⟨U₁, hU₁, U₂, hU₂, h⟩, cases hR _ hU₁ with V hV, cases hS _ hU₂ with W hW, use [V, W, set.subset.trans (set.prod_mono hV hW) h] end lemma prod_self_subset (hR : nonarchimedean R) : ∀ U ∈ nhds (0 : R × R), ∃ (V : open_add_subgroup R), (V : set R).prod (V : set R) ⊆ U := begin intros U hU, rcases prod_subset hR hR U hU with ⟨V, W, h⟩, use V ⊓ W, refine set.subset.trans (set.prod_mono _ _) ‹_›; simp end lemma prod (hR : nonarchimedean R) (hS : nonarchimedean S) : nonarchimedean (R × S) := begin intros U hU, rcases prod_subset hR hS U hU with ⟨V, W, h⟩, refine ⟨V.prod W, ‹_›⟩ end lemma mul_subset (h : nonarchimedean R) (U : open_add_subgroup R) : ∃ V : open_add_subgroup R, (V : set R) * V ⊆ U := begin rcases prod_self_subset h _ _ with ⟨V, H⟩, use V, work_on_goal 0 { rwa [set.pointwise_mul_eq_image, set.image_subset_iff] }, apply mem_nhds_sets (continuous_mul' _ U.is_open), simpa only [prod.fst_zero, prod.snd_zero, set.mem_preimage_eq, mul_zero] using U.zero_mem end end nonarchimedean end topological_add_group section bases open filter set variables {α : Type*} {ι : Type*} {s : ι → set α} [inhabited ι] lemma generate_eq_of_base (H : ∀ i j, ∃ k, s k ⊆ s i ∩ s j) (U : set α) : U ∈ generate (range s) ↔ ∃ i, s i ⊆ U := begin split ; intro h, { induction h with U U_in U V U_gen UV U_union U V U_gen V_gen U_union V_union, { rcases U_in with ⟨i, rfl⟩, use i }, { use default ι, exact (univ_mem_sets : univ ∈ principal (s $ default ι))}, { cases U_union with i Ui, use i, exact subset.trans Ui UV }, { cases U_union with i Ui, cases V_union with j Vj, cases H i j with k k_sub, use k, cases subset_inter_iff.1 k_sub with ki kj, exact subset_inter_iff.2 ⟨subset.trans ki Ui, subset.trans kj Vj⟩ }}, { cases h with i Ui, exact generate_sets.superset (generate_sets.basic $ mem_range_self i) Ui }, end lemma mem_infi_range_of_base (H : ∀ i j, ∃ k, s k ⊆ s i ∩ s j) (U : set α) : U ∈ (⨅ i, principal (s i)) ↔ ∃ i, s i ⊆ U := begin rw mem_infi, { split, { exact λ ⟨_, ⟨i, rfl⟩, Ui⟩, ⟨i, Ui⟩ }, { rintro ⟨i, Ui⟩, rw mem_Union, use [i, Ui] } }, { rintros i j, cases H i j with k k_sub, use k, split ; apply principal_mono.2 ; simp [set.subset_inter_iff.1 k_sub] }, { apply_instance } end lemma generate_eq_infi (H : ∀ i j, ∃ k, s k ⊆ s i ∩ s j) : generate (range s) = ⨅ i, principal (s i) := by ext t ; rw [generate_eq_of_base H, mem_infi_range_of_base H] end bases namespace add_group_with_zero_nhd variables {α : Type*} [add_group_with_zero_nhd α] open filter lemma nhds_eq' (a : α) : nhds a = map (λx, a + x) (Z α) := by convert nhds_eq a ; ext ; simp end add_group_with_zero_nhd section universe u open filter class ring_with_zero_nhd (α : Type u) extends ring α:= (Z : filter α) (zero_Z {} : pure 0 ≤ Z) (sub_Z {} : tendsto (λp:α×α, p.1 - p.2) (Z.prod Z) Z) (left_mul (x₀ : α) : tendsto (λ x : α, x₀ * x) Z Z) (right_mul (x₀ : α) : tendsto (λ x : α, x * x₀) Z Z) (mul_Z {} : tendsto (λp:α×α, p.1 * p.2) (Z.prod Z) Z) end namespace ring_with_zero_nhd variables (α : Type*) [ring_with_zero_nhd α] open filter add_group_with_zero_nhd function local notation `Z` := add_group_with_zero_nhd.Z instance to_add_group_with_zero_nhd {α :Type*} [ring_with_zero_nhd α] : add_group_with_zero_nhd α := {..‹ring_with_zero_nhd α›} def topological_space : topological_space α := by apply_instance instance : topological_ring α := begin refine {..add_group_with_zero_nhd.topological_add_group, ..}, rw continuous_iff_continuous_at, rintro ⟨x₀, y₀⟩, rw [continuous_at, nhds_prod_eq, nhds_eq', nhds_eq', nhds_eq', filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λ (x : α), x + x₀ * y₀) ∘ (λ (p : α × α), p.fst + p.snd) ∘ (λ (p : α × α), (p.1*y₀ + x₀*p.2, p.1*p.2))) (filter.prod (Z α) $ Z α) (map (λ (x : α), x + x₀ * y₀) $ Z α), { convert this using 1, { ext, simp only [comp_app], repeat { rw mul_add <|> rw add_mul }, abel }, simp }, refine tendsto.comp _ tendsto_map, refine tendsto.comp _ add_Z, apply tendsto.prod_mk _ ring_with_zero_nhd.mul_Z, { change tendsto ((λ p : α × α, p.1 + p.2) ∘ (λ (x : α × α), (x.fst * y₀, x₀ * x.snd))) (filter.prod (Z α) (Z α)) (Z α), refine tendsto.comp _ add_Z, apply tendsto.prod_mk, { exact tendsto_fst.comp (ring_with_zero_nhd.right_mul y₀) }, { exact tendsto_snd.comp (ring_with_zero_nhd.left_mul x₀) } }, end end ring_with_zero_nhd section open filter set lattice add_group_with_zero_nhd variables {A : Type*} [ring A] {ι : Type*} [inhabited ι] (G : ι → set A) [∀ i, is_add_subgroup $ G i] (h_directed : ∀ i j, ∃ k, G k ⊆ G i ∩ G j) (h_left_mul : ∀ x i, ∃ j, (λ y : A, x*y) '' (G j) ⊆ G i) (h_right_mul : ∀ x i, ∃ j, (λ y : A, y*x) '' (G j) ⊆ G i) (h_mul : ∀ i, ∃ j, G j * G j ⊆ G i) include h_directed h_left_mul h_right_mul h_mul def of_subgroups : ring_with_zero_nhd A := { Z := (⨅ i, principal (G i)), zero_Z := assume U H, mem_pure $ let ⟨i, hi⟩ := (mem_infi_range_of_base h_directed U).1 H in hi (is_add_submonoid.zero_mem (G i)), sub_Z := begin rw tendsto_infi, intro i, rw tendsto_prod_self_iff, intros W W_in, use G i, have ineq : (⨅ (i : ι), principal (G i)) ≤ principal (G i), from infi_le _ _, use ineq (mem_principal_self $ G i), intros x y x_in y_in, exact W_in (is_add_subgroup.sub_mem _ x y x_in y_in) end, left_mul := begin intro x₀, rw tendsto_infi, intro i, rw tendsto_principal, rcases h_left_mul x₀ i with ⟨j, hj⟩, rw mem_infi_range_of_base h_directed, use j, rwa image_subset_iff at hj, end, right_mul := begin intro x₀, rw tendsto_infi, intro i, rw tendsto_principal, rcases h_right_mul x₀ i with ⟨j, hj⟩, rw mem_infi_range_of_base h_directed, use j, rwa image_subset_iff at hj, end, mul_Z := begin rw tendsto_infi, intro i, rw tendsto_prod_self_iff, intros W W_in, rcases h_mul i with ⟨j, hj⟩, use G j, have ineq : (⨅ (i : ι), principal (G i)) ≤ principal (G j), from infi_le _ _, use ineq (mem_principal_self $ G j), intros x y x_in y_in, apply W_in, apply hj, exact ⟨_, x_in, _, y_in, rfl⟩ end, to_ring := ‹ring A› } def topology_of_subgroups : topological_space A := @ring_with_zero_nhd.topological_space A (of_subgroups _ h_directed h_left_mul h_right_mul h_mul) variables {G h_directed h_left_mul h_right_mul h_mul} lemma of_subgroups.nhds_zero (U : set A) : U ∈ @nhds A (topology_of_subgroups _ h_directed h_left_mul h_right_mul h_mul) (0 : A) ↔ ∃ i, G i ⊆ U := begin letI rnz := (of_subgroups _ h_directed h_left_mul h_right_mul h_mul), rw @add_group_with_zero_nhd.nhds_zero_eq_Z A (@ring_with_zero_nhd.to_add_group_with_zero_nhd A rnz), change U ∈ (⨅ i, principal (G i)) ↔ _, rw mem_infi_range_of_base h_directed, end lemma of_subgroups.is_open (i : ι) : @is_open A (topology_of_subgroups G h_directed h_left_mul h_right_mul h_mul) (G i) := begin letI rnz := (of_subgroups _ h_directed h_left_mul h_right_mul h_mul), rw is_open_iff_nhds, intros a ha, erw [nhds_eq, le_principal_iff, filter.mem_map, filter.mem_infi], { rw set.mem_Union, use i, rw show {x : A | x + a ∈ G i} = G i, { ext g, split; intro h, { rw ← (is_add_subgroup.add_mem_cancel_left (G i) ha), assumption }, { rw ← (is_add_subgroup.add_mem_cancel_left (G i) ha) at h, assumption } }, exact mem_principal_self _ }, { intros i j, cases h_directed i j with k hk, use k, split; show principal _ ≤ principal _; rw principal_mono; refine set.subset.trans hk _, { apply set.inter_subset_left }, { apply set.inter_subset_right } }, { apply_instance } end lemma of_subgroups.nonarchimedean : @topological_add_group.nonarchimedean A _ (topology_of_subgroups G h_directed h_left_mul h_right_mul h_mul) (by letI := of_subgroups G h_directed h_left_mul h_right_mul h_mul; apply_instance) := begin intros U hU, rw of_subgroups.nhds_zero at hU, cases hU with i hi, exact ⟨⟨G i, of_subgroups.is_open i, by apply_instance⟩, hi⟩, end section variables {α : Type*} [add_group α] [topological_space α] [topological_add_group α] variables (f : α → A) [is_add_group_hom f] lemma of_subgroups.continuous (h : ∀ i, is_open (f ⁻¹' (G i))) : @continuous _ _ _ (topology_of_subgroups G h_directed h_left_mul h_right_mul h_mul) f := begin letI rnz := (of_subgroups _ h_directed h_left_mul h_right_mul h_mul), apply topological_add_group.continuous_of_continuous_at_zero f, intros U hU, rw [is_add_group_hom.zero f, of_subgroups.nhds_zero] at hU, cases hU with i hi, rw mem_map_sets_iff, refine ⟨f ⁻¹' G i, mem_nhds_sets (h i) _, set.subset.trans _ hi⟩, { apply is_add_submonoid.zero_mem }, { apply image_preimage_subset } end end end section comm_ring variables {A : Type*} [comm_ring A] {ι : Type*} [inhabited ι] (G : ι → set A) [∀ i, is_add_subgroup $ G i] (h_directed : ∀ i j, ∃ k, G k ⊆ G i ∩ G j) (h_left_mul : ∀ (x : A) i, ∃ j, x • (G j) ⊆ G i) (h_mul : ∀ i, ∃ j, G j * G j ⊆ G i) include h_directed h_left_mul h_mul def of_subgroups_comm : ring_with_zero_nhd A := of_subgroups G h_directed (by simpa only [set.smul_set_eq_image] using h_left_mul) (by simpa only [set.smul_set_eq_image, mul_comm] using h_left_mul) h_mul def topology_of_subgroups_comm : topological_space A := topology_of_subgroups G h_directed (by simpa only [set.smul_set_eq_image] using h_left_mul) (by simpa only [set.smul_set_eq_image, mul_comm] using h_left_mul) h_mul variables {G h_directed h_left_mul h_mul} lemma of_subgroups_comm.is_open (i : ι) : @is_open A (topology_of_subgroups_comm G h_directed h_left_mul h_mul) (G i) := of_subgroups.is_open i section variables {α : Type*} [add_group α] [topological_space α] [topological_add_group α] variables (f : α → A) [is_add_group_hom f] lemma of_subgroups_comm.continuous (h : ∀ i, is_open (f ⁻¹' (G i))) : @continuous _ _ _ (topology_of_subgroups_comm G h_directed h_left_mul h_mul) f := of_subgroups.continuous f h end end comm_ring section comm_algebra open algebra submodule variables {R : Type*} {A: Type*} [comm_ring R] [comm_ring A] [algebra R A] {ι : Type*} [inhabited ι] (M : ι → submodule R A) (h_directed : ∀ i j, ∃ k, M k ≤ M i ⊓ M j) (h_left_mul : ∀ (a : A) i, ∃ j, a • M j ≤ M i) (h_mul : ∀ i, ∃ j, M j * M j ≤ M i) include h_directed h_left_mul h_mul def of_submodules_comm : ring_with_zero_nhd A := of_subgroups_comm (λ i, (M i : set A)) h_directed begin intros x i, cases h_left_mul x i with j hj, use j, erw smul_singleton at hj, erw set.smul_set_eq_image, exact hj end begin intro i, cases h_mul i with j hj, use j, rintros _ ⟨x, hx, y, hy, rfl⟩, apply hj, exact mul_mem_mul hx hy, end def topology_of_submodules_comm : topological_space A := topology_of_subgroups_comm (λ i, (M i : set A)) h_directed begin intros x i, cases h_left_mul x i with j hj, use j, erw smul_singleton at hj, erw set.smul_set_eq_image, exact hj end begin intro i, cases h_mul i with j hj, use j, rintros _ ⟨x, hx, y, hy, rfl⟩, apply hj, exact mul_mem_mul hx hy, end variables {M h_directed h_left_mul h_mul} lemma of_submodules_comm.nhds_zero (U : set A) : U ∈ @nhds A (topology_of_submodules_comm _ h_directed h_left_mul h_mul) (0 : A) ↔ ∃ i, (M i : set A) ⊆ U := of_subgroups.nhds_zero U lemma of_submodules_comm.is_open (i : ι) : @is_open A (topology_of_submodules_comm M h_directed h_left_mul h_mul) (M i) := by convert of_subgroups_comm.is_open i lemma of_submodules_comm.nonarchimedean : @topological_add_group.nonarchimedean A _ (topology_of_submodules_comm M h_directed h_left_mul h_mul) (by letI := of_submodules_comm M h_directed h_left_mul h_mul; apply_instance) := of_subgroups.nonarchimedean section variables {α : Type*} [add_group α] [topological_space α] [topological_add_group α] variables (f : α → A) [is_add_group_hom f] lemma of_submodules_comm.continuous (h : ∀ i, is_open (f ⁻¹' (M i))) : @continuous _ _ _ (topology_of_submodules_comm M h_directed h_left_mul h_mul) f := of_subgroups.continuous f h end end comm_algebra namespace submodule variables {R : Type*} {M : Type*} [comm_ring R] variables [add_comm_group M] [topological_space M] [topological_add_group M] [module R M] lemma is_open_of_open_submodule {P : submodule R M} (h : ∃ U : submodule R M, is_open (U : set M) ∧ U ≤ P) : is_open (P : set M) := begin letI H : is_add_subgroup (P : set M) := by apply_instance, apply open_add_subgroup.is_open_of_open_add_subgroup H, rcases h with ⟨U, h₁, h₂⟩, exact ⟨⟨U, h₁, by apply_instance⟩, h₂⟩ end end submodule namespace ideal open lattice variables {R : Type*} [comm_ring R] def adic_topology (I : ideal R) : topological_space R := topology_of_submodules_comm (λ n : ℕ, I^n) (by { intros i j, use (i + j), rw pow_add, exact mul_le_inf }) (by { intros r i, use i, exact le_trans mul_le_inf inf_le_right }) (by { intro i, use i, exact le_trans mul_le_inf inf_le_left }) def adic_ring (I : ideal R) := R namespace adic_ring variable {I : ideal R} instance : ring_with_zero_nhd I.adic_ring := by delta adic_ring; exact of_submodules_comm (λ n : ℕ, I^n) (by { intros i j, use (i + j), rw pow_add, exact mul_le_inf }) (by { intros r i, use i, exact le_trans mul_le_inf inf_le_right }) (by { intro i, use i, exact le_trans mul_le_inf inf_le_left }) instance : topological_space I.adic_ring := by apply_instance instance : topological_ring I.adic_ring := by apply_instance lemma nonarchimedean : topological_add_group.nonarchimedean I.adic_ring := of_submodules_comm.nonarchimedean lemma is_open_pow_ideal (n : ℕ) : @is_open I.adic_ring _ (I^n).carrier := of_submodules_comm.is_open n end adic_ring section variables [topological_space R] [topological_ring R] lemma is_open_of_open_subideal {I : ideal R} (h : ∃ U : ideal R, is_open (U : set R) ∧ U ≤ I) : is_open (I : set R) := submodule.is_open_of_open_submodule h end end ideal section open ideal topological_add_group variables {R : Type*} [comm_ring R] def is_ideal_adic [H : topological_space R] [topological_ring R] (J : ideal R) : Prop := H = J.adic_topology notation `is-`J`-adic` := is_ideal_adic J lemma is_ideal_adic_iff [topological_space R] [topological_ring R] (J : ideal R) : is-J-adic ↔ (∀ n : ℕ, is_open (↑(J^n) : set R)) ∧ (∀ s ∈ nhds (0 : R), ∃ n : ℕ, ↑(J^n) ⊆ s) := begin split, { intro H, delta is_ideal_adic at H, erw H at *, split, { exact adic_ring.is_open_pow_ideal, }, { intros s hs, erw ← of_submodules_comm.nhds_zero, exact hs, }, }, { rintro ⟨H₁, H₂⟩, apply topological_add_group.ext, { apply @topological_ring.to_topological_add_group }, { apply @topological_ring.to_topological_add_group (J.adic_ring) }, { ext s, split; intro H, { exact (of_submodules_comm.nhds_zero _).mpr (H₂ s H) }, { rcases (of_submodules_comm.nhds_zero _).mp H with ⟨n, hn⟩, rw mem_nhds_sets_iff, refine ⟨_, hn, H₁ n, (J^n).zero_mem⟩ } } } end variables (R) [topological_space R] [topological_ring R] def is_adic : Prop := ∃ (J : ideal R), is-J-adic variable {R} lemma is_ideal_adic.nonarchimedean {J : ideal R} (h : is-J-adic) : nonarchimedean R := begin delta is_ideal_adic at h, unfreezeI, subst h, exact adic_ring.nonarchimedean end lemma is_adic.nonarchimedean (h : is_adic R) : nonarchimedean R := by { cases h with J hJ, exact hJ.nonarchimedean } lemma is_ideal_adic_pow {J : ideal R} (h : is-J-adic) {n : ℕ} (hn : n > 0) : is-J^n-adic := begin rw is_ideal_adic_iff at h ⊢, split, { intro m, rw ← pow_mul, apply h.left }, { intros V hV, cases h.right V hV with m hm, use m, refine set.subset.trans _ hm, cases n, { exfalso, exact nat.not_succ_le_zero 0 hn }, rw [← pow_mul, nat.succ_mul], apply ideal.pow_le_pow, apply nat.le_add_left } end lemma exists_ideal_adic_subset (h : is_adic R) (U : set R) (hU : U ∈ nhds (0:R)) : ∃ I : ideal R, is-I-adic ∧ (I : set R) ⊆ U := begin cases h with J hJ, have H := (is_ideal_adic_iff J).mp hJ, cases H.right U hU with n hn, refine ⟨J^(n + 1), _, _⟩, { apply is_ideal_adic_pow hJ, apply nat.succ_pos }, { refine set.subset.trans (J.pow_le_pow _) hn, apply nat.le_succ } end end
ef6f2113b8c3c302e8ac422e3f885467cde6888e
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/monad/algebra.lean
203c8b0804808a41da9edddc70802258a2bc056f
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
6,881
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.reflect_isomorphisms /-! # Eilenberg-Moore (co)algebras for a (co)monad 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₁ -- declare the `v`'s first; see `category_theory.category` for an explanation 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 : C ⥤ C) [monad T] : Type (max u₁ v₁) := (A : C) (a : T.obj A ⟶ A) (unit' : (η_ T).app A ≫ a = 𝟙 A . obviously) (assoc' : ((μ_ T).app A ≫ a) = (T.map a ≫ a) . obviously) restate_axiom algebra.unit' restate_axiom algebra.assoc' namespace algebra variables {T : C ⥤ C} [monad T] /-- A morphism of Eilenberg–Moore algebras for the monad `T`. -/ @[ext] structure hom (A B : algebra T) := (f : A.A ⟶ B.A) (h' : T.map f ≫ B.a = A.a ≫ f . obviously) restate_axiom hom.h' attribute [simp] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore algebra. -/ @[simps] def id (A : algebra T) : hom A A := { f := 𝟙 A.A } /-- Composition of Eilenberg–Moore algebra homomorphisms. -/ @[simps] def comp {P Q R : algebra T} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f, h' := by rw [functor.map_comp, category.assoc, g.h, ←category.assoc, f.h, category.assoc] } end hom /-- The category of Eilenberg-Moore algebras for a monad. cf Definition 5.2.4 in [Riehl][riehl2017]. -/ @[simps] instance EilenbergMoore : category (algebra T) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ _ } end algebra variables (T : C ⥤ C) [monad T] /-- 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' := (monad.assoc _).symm }, map := λ X Y f, { f := T.map f, h' := by erw (μ_ T).naturality } } /-- The adjunction between the free and forgetful constructions for Eilenberg-Moore algebras for a monad. cf Lemma 5.2.8 of [Riehl][riehl2017]. -/ def adj : free T ⊣ forget T := 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' := begin dsimp, simp, conv { to_rhs, rw [←category.assoc, ←(μ_ T).naturality, category.assoc], erw algebra.assoc }, refl, end }, left_inv := λ f, begin ext1, dsimp, simp only [free_obj_a, functor.map_comp, algebra.hom.h, category.assoc], erw [←category.assoc, monad.right_unit, id_comp], end, right_inv := λ f, begin dsimp, erw [←category.assoc, ←(η_ T).naturality, functor.id_map, category.assoc, Y.unit, comp_id], end }} /-- Given an algebra morphism whose carrier part is an isomorphism, we get an algebra isomorphism. -/ def algebra_iso_of_iso {A B : algebra T} (f : A ⟶ B) [i : is_iso f.f] : is_iso f := { inv := { f := i.inv, h' := begin erw (as_iso f.f).eq_comp_inv, slice_lhs 2 3 {erw ← f.h}, slice_lhs 1 2 {rw ← T.map_comp}, rw [is_iso.inv_hom_id, T.map_id, category.id_comp] end } } instance forget_reflects_iso : reflects_isomorphisms (forget T) := { reflects := λ A B, algebra_iso_of_iso T } end monad namespace comonad /-- An Eilenberg-Moore coalgebra for a comonad `T`. -/ @[nolint has_inhabited_instance] structure coalgebra (G : C ⥤ C) [comonad G] : Type (max u₁ v₁) := (A : C) (a : A ⟶ G.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' namespace coalgebra variables {G : C ⥤ C} [comonad G] /-- A morphism of Eilenberg-Moore coalgebras for the comonad `G`. -/ @[ext, nolint has_inhabited_instance] structure hom (A B : coalgebra G) := (f : A.A ⟶ B.A) (h' : A.a ≫ G.map f = f ≫ B.a . obviously) restate_axiom hom.h' attribute [simp] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore coalgebra. -/ @[simps] def id (A : coalgebra G) : hom A A := { f := 𝟙 A.A } /-- Composition of Eilenberg–Moore coalgebra homomorphisms. -/ @[simps] def comp {P Q R : coalgebra G} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f, h' := by rw [functor.map_comp, ← category.assoc, f.h, category.assoc, g.h, category.assoc] } end hom /-- The category of Eilenberg-Moore coalgebras for a comonad. -/ @[simps] instance EilenbergMoore : category (coalgebra G) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ _ } end coalgebra variables (G : C ⥤ C) [comonad G] /-- 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' := (comonad.coassoc _).symm }, map := λ X Y f, { f := G.map f, h' := by erw (δ_ G).naturality; refl} } /-- The adjunction between the cofree and forgetful constructions for Eilenberg-Moore coalgebras for a comonad. -/ def adj : forget G ⊣ cofree G := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, { f := X.a ≫ G.map f, h' := by { rw [functor.map_comp, ← category.assoc, ← coalgebra.coassoc], simp } }, inv_fun := λ g, g.f ≫ (ε_ G).app Y, left_inv := λ f, begin dsimp, rw [category.assoc, (ε_ G).naturality, functor.id_map, ← category.assoc, X.counit, id_comp], end, right_inv := λ g, begin ext1, dsimp, rw [functor.map_comp, ← category.assoc, coalgebra.hom.h, assoc, cofree_obj_a, comonad.right_counit], dsimp, simp end }} end comonad end category_theory
5c2e84a4d28af5c7b0bf369540907067f9bc2f8b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/graded_object.lean
5152ed2b6fd4256d49c24f1d011e913e74f5c7df
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
6,136
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.shift import category_theory.concrete_category import category_theory.pi.basic /-! # The category of graded objects For any type `β`, a `β`-graded object over some category `C` is just a function `β → C` into the objects of `C`. We put the "pointwise" category structure on these, as the non-dependent specialization of `category_theory.pi`. We describe the `comap` functors obtained by precomposing with functions `β → γ`. As a consequence a fixed element (e.g. `1`) in an additive group `β` provides a shift functor on `β`-graded objects When `C` has coproducts we construct the `total` functor `graded_object β C ⥤ C`, show that it is faithful, and deduce that when `C` is concrete so is `graded_object β C`. -/ open category_theory.pi open category_theory.limits namespace category_theory universes w v u /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C`. -/ def graded_object (β : Type w) (C : Type u) : Type (max w u) := β → C -- Satisfying the inhabited linter... instance inhabited_graded_object (β : Type w) (C : Type u) [inhabited C] : inhabited (graded_object β C) := ⟨λ b, inhabited.default C⟩ /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C` with a shift functor given by translation by `s`. -/ @[nolint unused_arguments] -- `s` is here to distinguish type synonyms asking for different shifts abbreviation graded_object_with_shift {β : Type w} [add_comm_group β] (s : β) (C : Type u) : Type (max w u) := graded_object β C namespace graded_object variables {C : Type u} [category.{v} C] instance category_of_graded_objects (β : Type w) : category.{(max w v)} (graded_object β C) := category_theory.pi (λ _, C) section variable (C) /-- The natural isomorphism comparing between pulling back along two propositionally equal functions. -/ @[simps] def comap_eq {β γ : Type w} {f g : β → γ} (h : f = g) : comap (λ _, C) f ≅ comap (λ _, C) g := { hom := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, inv := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, } lemma comap_eq_symm {β γ : Type w} {f g : β → γ} (h : f = g) : comap_eq C h.symm = (comap_eq C h).symm := by tidy lemma comap_eq_trans {β γ : Type w} {f g h : β → γ} (k : f = g) (l : g = h) : comap_eq C (k.trans l) = comap_eq C k ≪≫ comap_eq C l := begin ext X b, simp, end /-- The equivalence between β-graded objects and γ-graded objects, given an equivalence between β and γ. -/ @[simps] def comap_equiv {β γ : Type w} (e : β ≃ γ) : (graded_object β C) ≌ (graded_object γ C) := { functor := comap (λ _, C) (e.symm : γ → β), inverse := comap (λ _, C) (e : β → γ), counit_iso := (comap_comp (λ _, C) _ _).trans (comap_eq C (by { ext, simp } )), unit_iso := (comap_eq C (by { ext, simp } )).trans (comap_comp _ _ _).symm, functor_unit_iso_comp' := λ X, by { ext b, dsimp, simp, }, } -- See note [dsimp, simp]. end instance has_shift {β : Type*} [add_comm_group β] (s : β) : has_shift (graded_object_with_shift s C) := { shift := comap_equiv C { to_fun := λ b, b-s, inv_fun := λ b, b+s, left_inv := λ x, (by simp), right_inv := λ x, (by simp), } } @[simp] lemma shift_functor_obj_apply {β : Type*} [add_comm_group β] (s : β) (X : β → C) (t : β) : (shift (graded_object_with_shift s C)).functor.obj X t = X (t + s) := rfl @[simp] lemma shift_functor_map_apply {β : Type*} [add_comm_group β] (s : β) {X Y : graded_object_with_shift s C} (f : X ⟶ Y) (t : β) : (shift (graded_object_with_shift s C)).functor.map f t = f (t + s) := rfl instance has_zero_morphisms [has_zero_morphisms C] (β : Type w) : has_zero_morphisms.{(max w v)} (graded_object β C) := { has_zero := λ X Y, { zero := λ b, 0 } } @[simp] lemma zero_apply [has_zero_morphisms C] (β : Type w) (X Y : graded_object β C) (b : β) : (0 : X ⟶ Y) b = 0 := rfl section local attribute [instance] has_zero_object.has_zero instance has_zero_object [has_zero_object C] [has_zero_morphisms C] (β : Type w) : has_zero_object.{(max w v)} (graded_object β C) := { zero := λ b, (0 : C), unique_to := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, unique_from := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, } end end graded_object namespace graded_object -- The universes get a little hairy here, so we restrict the universe level for the grading to 0. -- Since we're typically interested in grading by ℤ or a finite group, this should be okay. -- If you're grading by things in higher universes, have fun! variables (β : Type) variables (C : Type u) [category.{v} C] variables [has_coproducts C] /-- The total object of a graded object is the coproduct of the graded components. -/ noncomputable def total : graded_object β C ⥤ C := { obj := λ X, ∐ (λ i : ulift.{v} β, X i.down), map := λ X Y f, limits.sigma.map (λ i, f i.down) }. variables [has_zero_morphisms C] /-- The `total` functor taking a graded object to the coproduct of its graded components is faithful. To prove this, we need to know that the coprojections into the coproduct are monomorphisms, which follows from the fact we have zero morphisms and decidable equality for the grading. -/ instance : faithful (total β C) := { map_injective' := λ X Y f g w, begin classical, ext i, replace w := sigma.ι (λ i : ulift β, X i.down) ⟨i⟩ ≫= w, erw [colimit.ι_map, colimit.ι_map] at w, exact mono.right_cancellation _ _ w, end } end graded_object namespace graded_object noncomputable theory variables (β : Type) variables (C : Type (u+1)) [large_category C] [concrete_category C] [has_coproducts C] [has_zero_morphisms C] instance : concrete_category (graded_object β C) := { forget := total β C ⋙ forget C } instance : has_forget₂ (graded_object β C) C := { forget₂ := total β C } end graded_object end category_theory
8bd10a672e9cda81d1aa8c7ca4dabb0cbda2aa39
7b4371534ac437ca8cfb325dd5c6638ff111d31a
/boolean_rings.lean
10d1f0cd0a4ea395978b6112f15f39e39ea24285
[]
no_license
Shamrock-Frost/boolean_rings
6d78294568b6b9ad7b9c67b5de5e9545227826da
5da11beeaa37ec186c1deff946f2dbf7594fceb4
refs/heads/master
1,588,394,857,485
1,553,973,949,000
1,553,973,949,000
177,757,941
0
0
null
null
null
null
UTF-8
Lean
false
false
30,074
lean
import .logic_util .algebra_util .heq import .finite .partial_order_induction import .sum_over @[reducible] def is_boolean (R) [ring R] : Prop := ∀ a : R, a * a = a section parameters {R : Type _} [ring R] lemma boolean_ring.has_char_2 (is_bool : is_boolean R) : ring.one R + ring.one R = 0 := begin suffices : (ring.one R + ring.one R) + (ring.one R + ring.one R) = (ring.one R + ring.one R) + ring.zero R, { apply add_left_cancel, assumption }, rw (_ : ring.one R + ring.one R + ring.zero R = ring.one R + ring.one R), transitivity (ring.one R + ring.one R)*(ring.one R + ring.one R), { rw FOIL, rw ring.mul_one, ac_refl }, { apply is_bool }, { rw ring.add_zero } end lemma boolean_ring.add_self_zero (is_bool : is_boolean R) : ∀ a : R, a + a = 0 := λ a, calc a + a = a * 1 + a * 1 : by { rw mul_one a } ... = a * (1 + 1) : eq.symm $ left_distrib a 1 1 ... = a * (ring.one R + ring.one R) : rfl ... = a * 0 : by { rw boolean_ring.has_char_2 is_bool } ... = 0 : mul_zero a lemma boolean_ring.neg_eq_self (is_bool : is_boolean R) : ∀ a : R, a = -a := λ a, eq_neg_of_add_eq_zero $ boolean_ring.add_self_zero is_bool a lemma boolean_ring.eq_if_add_zero (is_bool : is_boolean R) : ∀ x y : R, x + y = 0 → x = y := by { intros, have : (x + y) + y = y, { rw a, apply zero_add }, rw [add_assoc x y y,boolean_ring.add_self_zero is_bool, add_zero] at this, assumption } theorem boolean_ring.comm (is_bool : is_boolean R) : ∀ (x y : R), x * y = y * x := begin intros x y, have h1 : x*y + y*x = x*y + x*y*x + y*x*y + y*x := calc x*y + y*x = (x*y + y*x)*(x*y + y*x) : eq.symm $ is_bool (x*y + y*x) ... = (x*y)*(x*y) + (x*y)*(y*x) + (y*x)*(x*y) + (y*x)*(y*x) : by { apply FOIL } ... = x * y + (x*y)*(y*x) + (y*x)*(x*y) + y*x : by { rw [is_bool (x*y), is_bool (y*x)] } ... = x * y + x*y*x + (y*x)*(x*y) + y*x : by { rw (_ : (x*y)*(y*x) = x*(y*y)*x), rw is_bool y, repeat {rw mul_assoc}, } ... = x * y + x*y*x + y*x*y + y*x : by { rw (_ : (y*x)*(x*y) = y*(x*x)*y), rw is_bool x, repeat {rw mul_assoc}, }, have h2 : x*y*x = y*x*y, { apply boolean_ring.eq_if_add_zero is_bool, have h21 := add_right_cancel h1, rw add_assoc at h21, have h22 : x*y + 0 = x * y + (x * y * x + y * x * y), { refine eq.trans _ h21, apply add_zero }, exact eq.symm (add_left_cancel h22) }, have h3 : x*y = x*y*x := calc x*y = (x*y)*(x*y) : eq.symm $ is_bool (x*y) ... = x*(y*x*y) : by { repeat { rw mul_assoc } } ... = x*(x*y*x) : congr_arg _ $ eq.symm h2 ... = (x*x)*y*x : by { repeat { rw mul_assoc } } ... = x*y*x : by { rw is_bool x }, have h4 : y*x = y*x*y := calc y*x = (y*x)*(y*x) : eq.symm $ is_bool (y*x) ... = y*(x*y*x) : by { repeat { rw mul_assoc } } ... = y*(x*y) : by { rw ← h3 } ... = y*x*y : by { rw mul_assoc }, rw [h3, h4], assumption end class boolean_ring (R) extends comm_ring (R) := (is_bool : is_boolean R) lemma is_bool {R'} [boolean_ring R'] : ∀ a : R', a*a = a := boolean_ring.is_bool R' def boolean_ring.mk2 (h : is_boolean R) : boolean_ring R := { mul_comm := boolean_ring.comm h, is_bool := h, .._inst_1 } open classical instance pset.ring (T) : boolean_ring (set T) := { boolean_ring . add := (Δ), mul := (∩), one := set.univ, zero := ∅, neg := id, add_assoc := λ A B C, @symm_diff_assoc T A B C (λ x, prop_decidable (A x)) (λ x, prop_decidable (B x)) (λ x, prop_decidable (C x)), add_comm := symm_diff_comm, mul_assoc := inter_assoc, mul_comm := inter_comm, zero_add := empty_symm_diff, add_zero := by { intro, rw symm_diff_comm, apply empty_symm_diff }, mul_one := inter_univ, one_mul := by { intro, rw (_ : set.inter set.univ a = a ∩ set.univ), apply inter_univ, rw inter_comm, refl }, add_left_neg := by { intro, simp, apply symm_diff_self }, left_distrib := left_distrib_inter_symm_diff, right_distrib := by { intros, rw (_ : set.inter (a Δ b) c = c ∩ (a Δ b)), rw (_ : set.inter a c = c ∩ a), rw (_ : set.inter b c = c ∩ b), apply left_distrib_inter_symm_diff, all_goals { rw inter_comm, refl } }, is_bool := by intros; apply inter_self } end @[reducible] noncomputable def sum_of {R : Type _} [comm_ring R] (h : finite R) (S : set R) : R := sum_over $ classical.some $ classical.some_spec $ classical.sets_of_finite_types_are_finite R h S lemma sum_of_unique {R : Type _} [comm_ring R] (h : finite R) (S : set R) : ∀ n (f : fin n → R), function.injective f → S = fun.im f → sum_of h S = sum_over f := begin intros n f f_i f_s, let h1 := classical.sets_of_finite_types_are_finite R h S, let n1 := classical.some h1, let h2 := classical.some_spec h1, let f1 : fin n1 → R := classical.some h2, let h3 := classical.some_spec h2, transitivity sum_over f1, refl, have : n1 = n, symmetry, apply one_way_to_be_finite S _ f _ f1 f_i f_s h3.left h3.right, suffices : (λ (s : Σ' (n : ℕ), (fin n → R)), sum_over s.snd) ⟨n1, f1⟩ = (λ (s : Σ' (n : ℕ), (fin n → R)), sum_over s.snd) ⟨n, f⟩, { exact this }, let f1' := eq.transport (λ (k : ℕ), fin k → R) this f1, have fheq : f1 == f1' := heq_transport (λ k, fin k → R) this f1, have : @psigma.mk nat (λ n, fin n → R) n1 f1 = @psigma.mk nat (λ n, fin n → R) n f1', { congr; assumption }, rw this, simp, apply sum_over_unique, have := @same_embedding_from_ims_eq (fin n) R, apply same_embedding_from_ims_eq f1' f, { apply inj_implies_transport_inj fin (λ _, R), exact h3.left }, { assumption }, rw ← f_s, rw h3.right, symmetry, congr; assumption end section local attribute [instance] classical.prop_decidable parameters {R : Type _} [boolean_ring R] (is_finite : finite R) instance pseudo_subset_order : partial_order R := { partial_order . le := λ x y, x*y = x, le_refl := by { intro, simp [(≤)], rw is_bool a }, le_trans := by { simp [(≤)], intros a b c hab hbc, exact calc a * c = (a * b) * c : by { rw hab } ... = a * (b * c) : mul_assoc _ _ _ ... = a * b : by { rw hbc } ... = a : hab }, le_antisymm := λ a b h1 h2, calc a = a * b : eq.symm h1 ... = b * a : mul_comm _ _ ... = b : h2 } def orthogonal (x y : R) := x * y = 0 def min_nonzero.set := { x : R | x ≠ 0 ∧ (∀ y, x ≤ y ∨ orthogonal x y) } lemma min_nonzero_def2 : min_nonzero.set = { x : R | x ≠ 0 ∧ (∀ y, y < x → y = 0) } := begin funext, apply propext, constructor, { intro h, cases h with h_ne_zero h_le_or_orthogonal, constructor, assumption, intros y hy, cases h_le_or_orthogonal y, { exfalso, apply hy.right, assumption }, { transitivity x * y, symmetry, cases hy, rw mul_comm, assumption' } }, { intro h, cases h with h_ne_zero h_minimal, apply and.intro h_ne_zero, intro y, have h1 : (x * y) ≤ x, { refine (_ : (x * y)*x = x * y), rw mul_comm (x*y) x, rw ← mul_assoc, rw is_bool }, by_cases (x ≤ (x * y)), { apply or.inl, apply le_antisymm; assumption }, { apply or.inr, apply h_minimal, constructor; assumption }, } end lemma min_nonzero_def3 : min_nonzero.set = minimal (λ x, x ≠ 0) := by { rw min_nonzero_def2, dsimp [minimal], funext x, apply congr_arg (λ P, x ≠ 0 ∧ P), apply propext, constructor; intros h y; specialize h y; (`[rw ← classical.dne (y = 0)] <|> `[rw classical.dne (y = 0)]), assumption' } def min_nonzero.type := subtype min_nonzero.set lemma min_nonzero.orthogonal : ∀ (x y : min_nonzero.type), x ≠ y → x.val * y.val = 0 := begin dsimp [min_nonzero.type, min_nonzero.set], intros x y hxy, cases (x.property.right y.val); cases (y.property.right x.val), { exfalso, apply hxy, apply subtype.eq, transitivity x.val * y.val, symmetry, assumption, rw mul_comm, assumption }, rw mul_comm, assumption' end lemma min_nonzero.orthogonal_contrapositive : ∀ {a b : min_nonzero.type}, ¬orthogonal a.val b.val → a = b := by { intros, apply classical.by_contradiction, intro, apply a_1, apply min_nonzero.orthogonal, assumption } section pset_embed noncomputable def min_nonzero.pset_embed : set min_nonzero.type → R := λ S, sum_of is_finite (subset_of_subtype_to_subset S) lemma pset_embed_eq_sum_over : ∀ (S : set min_nonzero.type) {n} (f : fin n → min_nonzero.type), function.injective f → S = fun.im f → min_nonzero.pset_embed S = sum_over (λ n, subtype.val $ f n) := begin intros S n f f_i f_s, dsimp [min_nonzero.pset_embed], apply @sum_of_unique, { intros x y hxy, apply f_i, apply subtype.eq, assumption }, { rw f_s, dsimp [subset_of_subtype_to_subset], funext x, apply propext, constructor; intro h; cases h, { cases h_h, existsi h_h_w, rw (_ : x = (subtype.mk x h_w).val), rw ← h_h_h, refl }, { rw ← h_h, simp, existsi (f h_w).property, existsi h_w, apply subtype.eq, refl } } end lemma min_nonzero_orthogonal_set : ∀ (S : set min_nonzero.type) (x0 : min_nonzero.type), x0 ∉ S → x0.val * min_nonzero.pset_embed S = 0 := begin intros S x0, have : set.finite S, { apply classical.sets_of_finite_types_are_finite, apply classical.subtypes_of_finite_types_are_finite, assumption }, cases this with size h, revert S, induction size; intros; cases h with f h; cases h with f_i f_s, all_goals { rw pset_embed_eq_sum_over S f f_i f_s, simp [sum_over] }, { rename a h', rename size_ih ih, rename size_n size, let xn := f ⟨size, nat.lt_succ_self size⟩, let f' := fin.restrict f, have : {x ∈ S | x ≠ xn} = fun.im f', { rw im_restrict _ _ f_i, funext x, apply propext, rw (_ : ({x ∈ S | x ≠ xn} x ↔ (fun.im f∖{f ⟨size, _⟩}) x) ↔ ((x ∈ S ∧ x ≠ xn) ↔ (fun.im f x ∧ x ∉ {f ⟨size, _⟩}))), tactic.swap, refl, rw [elem_singleton, ( _ : x ∉ {y : min_nonzero.type | y = f ⟨size, _⟩} ↔ x ≠ f ⟨size, _⟩)], tactic.swap, refl, rw ← f_s, constructor; intro h; cases h; constructor; assumption }, rw left_distrib, rw min_nonzero.orthogonal, specialize ih { x ∈ S | x ≠ xn } _ _ , rw (_ : fin.restrict (λ (n : fin (nat.succ size)), (f n).val) = (λ (n : fin size), (fin.restrict f n).val)), rw pset_embed_eq_sum_over { x ∈ S | x ≠ xn } f' at ih, rw [zero_add, ← ih], { apply restrict_inj_if_fun_inj f f_i }, { exact this }, refl, existsi f', { constructor, apply restrict_inj_if_fun_inj f f_i, exact this }, { intro h, apply h', exact h.left }, { intro h, have this' : f ⟨size, nat.lt_succ_self size⟩ ∈ fun.im f, existsi fin.mk size (nat.lt_succ_self size), refl, rw ← h at this', rw ← f_s at this', exact h' this' } } end lemma pset_embed_disj_union : ∀ A B, disjoint A B → min_nonzero.pset_embed (A ∪ B) = min_nonzero.pset_embed A + min_nonzero.pset_embed B := begin intros A B h, have : set.finite A, { apply classical.sets_of_finite_types_are_finite, apply classical.subtypes_of_finite_types_are_finite, assumption }, cases this with A_size hA, cases hA with f hA, cases hA with f_i f_s, have : set.finite B, { apply classical.sets_of_finite_types_are_finite, apply classical.subtypes_of_finite_types_are_finite, assumption }, cases this with B_size hB, cases hB with g hB, cases hB with g_i g_s, have := union_size' h f g f_i f_s g_i g_s, rw pset_embed_eq_sum_over (A ∪ B) (fin.glue f g) this.left this.right, rw (_ : (λ (n : fin (A_size + B_size)), (fin.glue f g n).val) = fin.glue (λ n : fin A_size, (f n).val) (λ n : fin B_size, (g n).val)), { rw sum_over_glue, apply congr, apply congr_arg, rw pset_embed_eq_sum_over A f f_i f_s, rw pset_embed_eq_sum_over B g g_i g_s }, { dunfold fin.glue, funext, by_cases h : n.val < A_size, rw [dif_pos _, dif_pos _]; assumption, rw [dif_neg _, dif_neg _]; assumption } end lemma pset_embed_minus_eq_minus : ∀ S S', S ⊆ S' → min_nonzero.pset_embed (S'∖S) = min_nonzero.pset_embed S' - min_nonzero.pset_embed S := begin intros S S' hsub, suffices : min_nonzero.pset_embed (S'∖S) + min_nonzero.pset_embed S = min_nonzero.pset_embed S', { exact calc min_nonzero.pset_embed (S'∖S) = min_nonzero.pset_embed (S'∖S) + min_nonzero.pset_embed S - min_nonzero.pset_embed S : eq.symm (add_sub_cancel _ _) ... = min_nonzero.pset_embed S' - min_nonzero.pset_embed S : by { rw this } }, have h1 : set.finite S', { apply classical.sets_of_finite_types_are_finite, apply classical.subtypes_of_finite_types_are_finite R is_finite }, have h2 : set.finite (S' ∖ S), { apply classical.subsets_of_finite_sets_are_finite (minus_is_subset _ _) h1 }, cases h2 with minus_size h2, cases h2 with f_minus h2, have h3 : set.finite S, { apply classical.subsets_of_finite_sets_are_finite hsub h1 }, cases h3 with sub_size h3, cases h3 with f_sub h3, have := union_size' (minus_disj _ _) f_minus f_sub h2.left h2.right h3.left h3.right, rw @minus_subset_union_subset _ _ _ (λ _, classical.prop_decidable _) hsub at this, cases this with f_i f_s, rw ← pset_embed_disj_union, { congr, apply minus_subset_union_subset, assumption }, apply minus_disj end lemma pset_embed_preserves_add : ∀ S S', min_nonzero.pset_embed (S + S') = min_nonzero.pset_embed S + min_nonzero.pset_embed S' := begin intros, rw (_ : S + S' = S Δ S'), { dsimp [(Δ)], rw pset_embed_minus_eq_minus, { rw (_ : min_nonzero.pset_embed S' = min_nonzero.pset_embed ((S'∖S) ∪ (S' ∩ S))), { rw pset_embed_disj_union (S'∖S), { rw ← add_assoc, rw ← pset_embed_disj_union, rw union_decomp_l, rw sub_eq_add_neg, congr, symmetry, rw inter_comm, apply boolean_ring.neg_eq_self is_bool, rw disjoint_symm, apply minus_disj }, { rw disjoint_symm, apply disjoint_implies_disjoint_subset , apply inter_subset_r, rw disjoint_symm, apply minus_disj } }, congr, exact decomp S' S }, exact (λ x hx, or.inl $ and.left hx) }, refl end lemma pset_embed_preserves_zero : min_nonzero.pset_embed 0 = 0 := begin apply add_group.homomorphism_preserves_zero, exact pset_embed_preserves_add end set_option trace.check true lemma pset_embed_preserves_mul : ∀ S S', min_nonzero.pset_embed (S * S') = min_nonzero.pset_embed S * min_nonzero.pset_embed S' := begin intros, cases (classical.sets_of_finite_types_are_finite _ (classical.subtypes_of_finite_types_are_finite _ is_finite _) S) with n hn, cases hn with f hn, cases hn with f_i f_s, cases (classical.sets_of_finite_types_are_finite _ (classical.subtypes_of_finite_types_are_finite _ is_finite _) S') with m hm, cases hm with g hm, cases hm with g_i g_s, rw pset_embed_eq_sum_over S f, any_goals { assumption }, rw pset_embed_eq_sum_over S' g, any_goals { assumption }, rw mul_sum_over_right, have h1 : ∀ i j, f i ∉ S' → (f i).val * (g j).val = 0, { intros, apply min_nonzero.orthogonal, intro h, apply a, rw [h, g_s], existsi j, refl }, have h1 : ∀ i, f i ∉ S' → (f i).val * sum_over (λ j, (g j).val) = 0, { intros, rw mul_sum_over_left, rw ← sum_over_eq_zero , congr, funext, apply h1, assumption }, have h2 : ∀ i, f i ∈ S' → ∃ j, (f i).val = (g j).val ∧ ∀ j' ≠ j, (f i).val ≠ (g j').val, { intros, rw g_s at a, cases a with j hj, existsi j, constructor, symmetry, congr, assumption, rw ← hj, intro j', apply mt, intro, apply g_i, symmetry, apply subtype.eq, assumption }, have h2 : ∀ i, f i ∈ S' → (f i).val * sum_over (λ j, (g j).val) = (f i).val, { rw g_s, intros i h, specialize h2 i (eq.substr g_s h), cases h2 with j h2, cases h2 with hij hneq, rw mul_sum_over_left, rw sum_over_nonzero _ (λ _ : fin 1, (f i).val), { simp [sum_over] }, { intros, apply g_i, transitivity (f i), rw mul_comm at a, apply min_nonzero.orthogonal_contrapositive a, have a' : (f i).val * (g y).val ≠ 0, rw ← a_1, assumption, apply min_nonzero.orthogonal_contrapositive a', }, { intros x y _, apply fin1.singleton }, { simp [fun.im], transitivity { y | (f i).val = y }, { funext, apply propext, constructor, { intro e, cases e, assumption }, { intro h, rw (_ : (f i).val = b), existsi fin.mk 0 nat.zero_lt_one, refl, assumption } }, { rw hij, funext, apply propext, constructor, { intro h, rw (_ : y = (g j).val), constructor, existsi j, apply is_bool, exact (g j).property.left, symmetry, assumption }, { intro h, cases h.left, rw ← h_1, have : (g j).val * (g w).val ≠ 0, rw ← h_1 at h, apply h.right, rw min_nonzero.orthogonal_contrapositive this, apply eq.symm, apply is_bool (g w).val } } } }, have h2' : ∀ i, f i ∉ S' → (f i).val * sum_over (λ j, (g j).val) = 0, { intros, rw mul_sum_over_left, rw ← sum_over_eq_zero, congr, funext, apply min_nonzero.orthogonal, intro h, apply a, rw h, rw g_s, existsi k, refl }, transitivity sum_over (λ (i : fin n), ite (f i ∈ (S * S')) (sum_over (λ (j : fin m), (f i).val * (g j).val)) 0), { cases (classical.sets_of_finite_types_are_finite _ (classical.subtypes_of_finite_types_are_finite _ is_finite _) (S*S')) with k hk, cases hk with in_p hk, cases hk with in_p_i in_p_s, rw pset_embed_eq_sum_over _ in_p in_p_i in_p_s, symmetry, apply sum_over_nonzero, { intros x y hnez_x hxy, apply f_i, apply subtype.eq, transitivity (ite (f x ∈ S * S') (sum_over (λ (j : fin m), (f x).val * (g j).val)) 0), { have mem1_x : f x ∈ S', { apply classical.by_contradiction, intro h, apply hnez_x, rw if_neg _, intro h', exact h h'.right, }, have mem2_x : f x ∈ S, { rw f_s, existsi x, refl }, have mem3_x : f x ∈ S * S' := ⟨mem2_x, mem1_x⟩, rw [if_pos _, ← mul_sum_over_left], symmetry, apply h2, exact mem1_x, exact mem3_x }, transitivity (ite (f y ∈ S * S') (sum_over (λ (j : fin m), (f y).val * (g j).val)) 0), assumption, { have hnez_y : ite (f y ∈ S * S') (sum_over (λ (j : fin m), (f y).val * (g j).val)) 0 ≠ 0 := hxy ▸ hnez_x, have mem1_y : f y ∈ S', { apply classical.by_contradiction, intro h, apply hnez_y, rw if_neg _, intro h', exact h h'.right, }, have mem2_y : f y ∈ S, { rw f_s, existsi y, refl }, have mem3_y : f y ∈ S * S' := ⟨mem2_y, mem1_y⟩, rw [if_pos _, ← mul_sum_over_left], apply h2, exact mem1_y, exact mem3_y }}, { intros x y hxy, apply in_p_i, apply subtype.eq, exact hxy }, { transitivity { v | ∃ y : min_nonzero.type, y ∈ fun.im in_p ∧ v = y.val }, { funext, apply propext, constructor; intro h; cases h, { existsi in_p h_w, constructor, existsi h_w, refl, symmetry, assumption }, { cases h_h, cases h_h_left, existsi h_h_left_w, rw [h_h_right, ← h_h_left_h] } }, transitivity { v | ∃ y : min_nonzero.type, y ∈ S * S' ∧ v = y.val }, { funext, apply propext, constructor; intro h; cases h; existsi h_w; refine and.intro _ h_h.right, { rw in_p_s, exact h_h.left }, { rw ← in_p_s, exact h_h.left } }, { funext, apply propext, constructor; intro h, { cases h, cases h_h, subst h_h_right, constructor, { have : h_w ∈ fun.im f := f_s ▸ h_h_left.left, cases this, existsi this_w, simp, subst this_h, rw if_pos h_h_left, rw ← mul_sum_over_left, apply h2, exact h_h_left.right }, exact h_w.property.left }, { cases h, cases h_left, subst h_left_h, simp at h_right, have : f h_left_w ∈ S * S', { apply classical.by_contradiction, intro h, rw if_neg _ at h_right, apply h_right rfl, assumption }, existsi f h_left_w, apply and.intro this, simp, rw if_pos _, rw ← mul_sum_over_left, apply h2, exact this.right, exact this } } } }, { congr, funext, by_cases (f i ∈ S * S'), { rw if_pos, rw mul_sum_over_left, exact h }, { rw if_neg, rw h2', { intro h', apply h, refine and.intro _ h', rw f_s, existsi i, refl }, exact h } } end lemma pset_embed_inj : function.injective min_nonzero.pset_embed := ker_trivial_imp_inj min_nonzero.pset_embed pset_embed_preserves_add $ λ S h, by { cases (classical.sets_of_finite_types_are_finite _ _ S), { revert S, induction w; intros, { apply has_size_zero_iff_empty _ h_1 }, { cases h_1 with f, cases h_1_h with f_i f_s, let x0 := f ⟨w_n, nat.lt_succ_self _⟩, rw pset_embed_eq_sum_over S f f_i f_s at h, rw (_ : sum_over (λ (n : fin (nat.succ w_n)), (f n).val) = sum_over (λ (n : fin w_n), (fin.restrict f n).val) + x0.val) at h, rw (_ : sum_over (λ (n : fin w_n), (fin.restrict f n).val) = min_nonzero.pset_embed (S ∖ { x0 })) at h, { have : x0.val * min_nonzero.pset_embed (S∖{x0}) + x0.val * x0.val = x0.val * 0, rw [← left_distrib, h], rw is_bool x0.val at this, rw mul_zero at this, rw min_nonzero_orthogonal_set (S∖{x0}) x0 at this, have h' := h, rw zero_add at this, rw this at h, rw add_zero at h, exfalso, apply x0.property.left, assumption, intro h, apply h.right, rw elem_singleton, exact rfl }, { rw pset_embed_eq_sum_over, { apply restrict_inj_if_fun_inj _ f_i }, { rw [f_s, im_restrict], assumption } }, refl } }, { apply classical.subtypes_of_finite_types_are_finite, assumption } } noncomputable def min_nonzero.proj : R → R := λ x, x * min_nonzero.pset_embed set.univ lemma min_nonzero_proj_def2 {n} (f : fin n → R) (x : R) : function.injective f → min_nonzero.set = fun.im f → min_nonzero.proj x = sum_over (λ j, x * f j) := begin intros f_i f_s, dsimp [min_nonzero.proj], rw ← mul_sum_over_left, congr, have : ∀ j, min_nonzero.set (f j), { rw f_s, intro, existsi j, refl }, rw pset_embed_eq_sum_over set.univ (λ j, ⟨f j, this j⟩), { intros i j h, apply f_i, rw ← subtype.mk.inj_eq, assumption }, { funext, transitivity true, refl, apply propext, rw true_iff, cases a, rw f_s at a_property, cases a_property, existsi a_property_w, apply subtype.eq, assumption } end lemma min_nonzero_proj_def3 : ∀ x, min_nonzero.proj x = min_nonzero.pset_embed {y : subtype min_nonzero.set | x * y.val ≠ 0} := begin intro x, have := classical.sets_of_finite_types_are_finite _ is_finite min_nonzero.set, destruct this, intros size h, cases h with f h, cases h with f_i f_s, rw min_nonzero_proj_def2 f x f_i f_s, { cases classical.subsets_of_finite_sets_are_finite (λ y (h : y ∈ min_nonzero.set ∧ x * y ≠ 0), h.left) this with size' h, cases h with g h, cases h with g_i g_s, rw sum_over_nonzero (λ j, x * f j) g, { have h1 : ∀ i, min_nonzero.set (g i), { have : ∀ i, fun.im g (g i) := λ i, ⟨i, rfl⟩, rw ← g_s at this, intro i, exact and.left (this i) }, have h2 : ∀ i, x * (g i) ≠ 0, { have : ∀ i, fun.im g (g i) := λ i, ⟨i, rfl⟩, rw ← g_s at this, intro i, exact and.right (this i) }, rw pset_embed_eq_sum_over _ (λ i, ⟨g i, h1 i⟩), { intros x y hxy, apply g_i, rw subtype.mk.inj_eq at hxy, assumption }, { funext, apply propext, constructor; intro h, { have : fun.im g y.val, rw ← g_s, constructor, apply y.property, assumption, cases this with k hk, existsi k, apply subtype.eq, exact hk }, { cases h, rw ← h_h, apply h2 } } }, { intros a b hnez hab, simp at hab ⊢, apply f_i, transitivity x * f a, { rw mul_comm, have hnez_a : f a * x ≠ 0, { rw mul_comm, exact hnez }, have : min_nonzero.set (f a), { rw f_s, existsi a, refl }, symmetry, refine or.resolve_right (this.right x) hnez_a }, transitivity x * f b, exact hab, { rw mul_comm, have hnez_b : f b * x ≠ 0, { rw mul_comm, rw ← hab, exact hnez }, have : min_nonzero.set (f b), { rw f_s, existsi b, refl }, refine or.resolve_right (this.right x) hnez_b } }, assumption, { rw ← g_s, transitivity { t ∈ fun.im f | t * x = t }, { funext, apply propext, constructor; rw ← f_s; intro h; apply and.intro h.left, { rw mul_comm at h, apply or.resolve_right (h.left.right x) h.right }, { rw mul_comm, rw h.right, exact h.left.left } }, { funext, apply propext, constructor; intro h, { cases h, destruct h_left, intros k hk, rw ← f_s at h_left, constructor, { existsi k, simp, rw hk, rw mul_comm, assumption }, { exact h_left.left } }, { cases h, cases h_left with k hk, simp at hk, have : f k = a, { rw ← hk, symmetry, rw mul_comm, have : min_nonzero.set (f k), { rw f_s, existsi k, refl }, apply or.resolve_right (this.right x), rw ← hk at h_right, rw mul_comm at h_right, exact h_right }, rw ← this at hk ⊢, constructor, { existsi k, refl }, rw mul_comm at hk, exact hk } } } } end lemma min_nonzero_proj_linear : ∀ x y, min_nonzero.proj (x + y) = min_nonzero.proj x + min_nonzero.proj y := begin intros, cases classical.sets_of_finite_types_are_finite _ is_finite min_nonzero.set with size h, cases h with f h, cases h with f_i f_s, repeat { rw min_nonzero_proj_def2 f _ f_i f_s }, rw ← sum_over_sum, congr, funext, apply right_distrib end lemma min_nonzero_proj_min_nonzero : ∀ x : min_nonzero.type, min_nonzero.proj x.val = x.val := begin intros, rw min_nonzero_proj_def3, rw (_ : {y : subtype min_nonzero.set | x.val * y.val ≠ 0} = { y | x = y }), rw pset_embed_eq_sum_over _ (λ j : fin 1, x), { simp [sum_over] }, { intros x y _, apply fin1.singleton }, { funext, apply propext, constructor; intro h, { existsi fin.mk 0 nat.zero_lt_one, assumption }, { cases h, exact h_h } }, { funext, apply propext, constructor; intro h, { apply min_nonzero.orthogonal_contrapositive, assumption }, { rw (_ : x = y), suffices : y.val * y.val ≠ 0, exact this, rw is_bool y.val, exact y.property.left, assumption } } end lemma min_nonzero_proj_eq : ∀ x, min_nonzero.proj x = x := have h1 : ∀ x y, orthogonal (x - x * y) y, from λ x y, calc (x - x * y) * y = x*y - (x*y)*y : mul_sub_right_distrib _ _ _ ... = x*y - x*(y*y) : by rw mul_assoc ... = x*y - x*y : by rw is_bool ... = 0 : sub_self _, have h2 : ∀ x y : R, x - x * y ≤ x, from λ x y, calc (x - x * y) * x = x*x - (x * y)*x : mul_sub_right_distrib _ _ _ ... = x*x - x * (x * y) : by rw mul_comm (x*y) ... = x*x - x*x*y : by rw mul_assoc ... = x - x*y : by rw is_bool, by { apply partial_order.induction, assumption', intros x ih, by_cases (x = 0), { rw h, rw min_nonzero_proj_def3, rw pset_embed_eq_sum_over _ fin.elim0, simp [sum_over], { intro a, exact a.elim0 }, { funext, transitivity false; apply propext, { rw iff_false, simp, apply not_false }, { rw false_iff, intro h, cases h, exact h_w.elim0 } } }, cases partial_order.ex_min is_finite (λ r, r ≠ 0) x h with x' h', specialize h1 x x', specialize h2 x x', have h3 : min_nonzero.set x', { rw min_nonzero_def2, cases h'.left, constructor, assumption, intro y, rw classical.dne (y = 0), apply right }, have h4 : x - x * x' < x, { apply lt_of_le_of_ne, assumption, intro h'', rw h'' at h1, apply h'.left.left, transitivity x' * x, symmetry, exact h'.right, rw mul_comm, exact h1 }, transitivity min_nonzero.proj (x - x * x' + x * x'), rw sub_add_cancel, rw min_nonzero_proj_linear, rw ih (x - x * x') h4, rw (_ : x * x' = x'), rw (_ : x' = (subtype.mk x' h3).val), rw min_nonzero_proj_min_nonzero, simp, rw mul_comm, exact h'.right } lemma pset_embed_surj : function.surjective min_nonzero.pset_embed := begin dsimp [function.surjective], apply partial_order.induction (λ r, ∃ S, min_nonzero.pset_embed S = r) is_finite, intros x ih, simp * at ih, existsi { y | x * subtype.val y ≠ 0 }, transitivity min_nonzero.proj x, { symmetry, apply min_nonzero_proj_def3 }, apply min_nonzero_proj_eq end lemma pset_embed_preserves_one : min_nonzero.pset_embed 1 = 1 := begin apply monoid.ident_unique, intro x, cases (pset_embed_surj 1), cases (pset_embed_surj x), rw [← h_1, ← pset_embed_preserves_mul, mul_one] end end pset_embed end
f9f5bfe63dd17a8b67e87f718556b6a22f944225
7bc35d4fbdda0c01e9b22a949940ee5cbb9800d0
/manifold/basis.lean
af3dcb21ba7661085093a5cf0b9ccac7aae950db
[]
no_license
truonghoangle/manifolds
e6c2534dd46579f56ba99a48e2eb7ce51640e7c0
dcf4815b29ad363ec9712fd00b7756c36cfa7c1c
refs/heads/main
1,638,501,090,139
1,636,918,550,000
1,636,918,550,000
185,779,631
0
0
null
null
null
null
UTF-8
Lean
false
false
4,952
lean
import manifold.field basis import linear_algebra.dual open topological_space set vector Euclidean noncomputable theory universe u variables {α : Type } {n : ℕ} variable [normed_field α] instance discrete: discrete_field α:= normed_field.to_discrete_field α structure euclidean (α : Type*) := (carrier : Type*) (dim : ℕ) (equiv : carrier ≃ (Π(i:fin dim),α )) namespace euclidean variable (E:euclidean α ) def to_vector (E:euclidean α): E.carrier ≃ vector α (E.dim) := equiv.trans (E.equiv) (@fun_vector α _ E.dim) instance : has_coe_to_sort (euclidean α) := ⟨_, @euclidean.carrier α⟩ instance to_topological_space (E : euclidean α ) : topological_space E := induced (to_vector E) (by apply_instance) def to_Top (E : euclidean α ) : Top :=⟨E, by apply_instance⟩ instance : has_coe (euclidean α) Top :=⟨to_Top⟩ def Euclidean_space (n : ℕ) : euclidean α :=⟨vector α n, n, (fun_vector n).symm ⟩ notation `α^` := Euclidean_space instance : add_comm_group (E:euclidean α) := equiv.add_comm_group E.equiv instance : has_scalar α E := @equiv.has_scalar _ _ α E.equiv Euclidean.has_scalar instance : mul_action α E:= equiv.mul_action E.equiv instance :distrib_mul_action α E:= { distrib_mul_action. smul_add := by {repeat{intro},simp[equiv.smul_def,equiv.add_def],by library_search }, smul_zero := by {repeat{intro},simp[equiv.smul_def,equiv.zero_def]}} instance : semimodule α E:= { semimodule. zero_smul := by{ repeat {intro},simp[equiv.smul_def], simp[equiv.zero_def]}, add_smul := by {repeat {intro},simp[equiv.smul_def, equiv.add_def, semimodule.add_smul]}} instance : module α E:={ .} instance : vector_space α E:={.} section dual lemma equiv_vec: E ≃ₗ[α] (Π (i: fin(E.dim)), α):= { add:= by{simp[equiv.add_def], repeat {intro}, have h:= equiv.apply_symm_apply E.equiv (E.equiv x + E.equiv y), by library_search }, smul:= by{simp[equiv.smul_def],repeat {intro}, have h:= equiv.apply_symm_apply E.equiv (c •(E.equiv) x), by library_search}, .. E.equiv} lemma dim_eq : vector_space.dim α E = E.dim:= by{ have h:= @dim_fun α (fin E.dim) _ _ α _ _, have h1:= @dim_of_field α _, rw[h1, mul_one,fintype.card_fin] at h, have H :=linear_equiv.dim_eq_lift (@equiv_vec α _ E), simp[h] at H, simp[H] } lemma dim_lt: vector_space.dim α E < cardinal.omega :=by { simp[dim_eq,cardinal.nat_lt_omega]} lemma dual_equiv :E ≃ₗ[α] module.dual α E:= begin have H:=classical.some_spec (exists_is_basis α E) , have Hy:=@is_basis.mk_eq_dim α E _ _ _ (classical.some(exists_is_basis α E)) H, have H1:=@dim_lt α _ E, rw[Hy.symm,cardinal.lt_omega_iff_finite] at H1, have Hyp:= @finite.fintype _ (classical.some(exists_is_basis α E)) H1, have h:=@is_basis.to_dual_equiv α E _ _ _ (classical.some(exists_is_basis α E)) H Hyp, apply h end def dual_equiv_std :module.dual α E ≃ₗ[α] (Π (i: fin(E.dim)), α) := begin have h:= @dual_equiv α _ E, have H:= @equiv_vec α _ E, have hy:=@linear_equiv.trans α (module.dual α E) E (Π (i: fin(E.dim)), α) _ _ _ _ _ _ _ h.symm H, apply hy end def dual:euclidean α := ⟨(E →ₗ[α] α), E.dim, (@dual_equiv_std α _ E).to_equiv ⟩ end dual def proj (E:euclidean α ) (i:fin (E.dim)) : E →ₗ[α] α := (linear_map.proj i).comp ((equiv_vec E).to_linear_map) def std_basis (E:euclidean α) (i:fin E.dim): E := E.equiv.inv_fun (@Euclidean.std_basis α E.dim _ i) instance has_norm : has_norm (E:euclidean α) :=⟨λ x, ∥E.equiv x∥⟩ instance : has_dist (E:euclidean α ) := ⟨ λ x y, @has_dist.dist _ _ (E.equiv x) (E.equiv y) ⟩ instance metric_space :metric_space (E:euclidean α ) := { metric_space. dist_self:= by {intro, simp[dist], have h:= (@Euclidean.normed_space α E.dim _).dist_self, have h1:=@h (E.equiv x),simp [dist] at h1, apply h1 }, dist_comm := by { simp[dist], repeat{intro}, have h:=(@Euclidean.normed_space α E.dim _).dist_comm, simp [dist] at h, apply h, }, dist_triangle:= by { simp[dist], repeat{intro}, have h:=(@Euclidean.normed_space α E.dim _).dist_triangle, simp [dist] at h, apply h,}, eq_of_dist_eq_zero:= by { simp[dist], intro, intro, have h:=(@Euclidean.normed_space α E.dim _).eq_of_dist_eq_zero, simp [dist] at h, intro, have heq:=@equiv.apply_eq_iff_eq _ _ E.equiv x y, rwa[iff.comm] at heq, rw [heq], apply h, apply a },} instance normed_group : normed_group (E:euclidean α) := {normed_group. dist_eq:= by {simp[norm,dist,equiv.add_def,equiv.neg_def], repeat{intro}, have h:= (@Euclidean.normed_space α E.dim _).dist_eq, simp[norm,dist] at h, apply h,},} instance :normed_space α (E:euclidean α):= {normed_space. norm_smul:= by {simp[norm,equiv.smul_def], repeat {intro}, have h:= (@Euclidean.normed_space α E.dim _).norm_smul, simp[norm,equiv.smul_def] at h, apply h,}} end euclidean
c4235f55fabdec8f8feb8bc2ecb9a037786f397a
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/system/io.lean
89415c83dc22ae7551d0dca54b973046058d6a94
[ "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
917
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch and Leonardo de Moura -/ constant {u} io : Type u → Type u constant io.functor : functor io constant io.monad : monad io attribute [instance] io.functor io.monad constant put_str : string → io unit constant put_nat : nat → io unit constant get_line : io string def put_str_ln {A} [has_to_string A] (s : A) : io unit := put_str $ #"\n" :: (to_string s) meta constant format.print_using : format → options → io unit meta definition format.print (fmt : format) : io unit := format.print_using fmt options.mk meta definition pp_using {α : Type} [has_to_format α] (a : α) (o : options) : io unit := format.print_using (to_fmt a) o meta definition pp {α : Type} [has_to_format α] (a : α) : io unit := format.print (to_fmt a)
7f8d0631123e7364baa49534d7146972b01ed996
a7602958ab456501ff85db8cf5553f7bcab201d7
/Notes/Theorem_Proving_in_Lean/Chapter2/2.9.lean
f385d173b47bd6b482b6edeaa64c5aada747ff06
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,482
lean
-- 2.8 Implicit Arguments -- Note: I do not indent everything inside the "namespace" one level in -- this file, just out of preference, since the entire file basically -- exists in the namespace. -- Assume we have an implementation of our list below: namespace hidden universe u constant list: Type u → Type u constant cons: Π α: Type u, α → list α → list α constant null: Π α: Type u, list α constant append: Π α: Type u, list α → list α → list α -- Given some type α, we can create lists and manipulate them. variables l1 l2: list Prop variable prop_var: Prop #check cons Prop prop_var l1 -- prop_var + l1 #check append Prop l1 l2 -- l1 + l2 #check cons Prop prop_var (append Prop l1 l2) -- prop_var + (l1 + l2) -- Note how in the last `#check` above, always passing Prop every time -- top each list function to denote the type of list you're dealing with -- is pretty redundant. This is because these functions ("constructors", -- as the book calls them), are polymorphic over types, so we have to -- repeatedly tell the function what type we're dealing with. -- From the third example above, ideally Lean would be able to infer the -- type "Prop" in both cases it appears: -- 1. Inference is possible in the first case, because the type -- prop_var is Prop, and we should only be "cons"ing variables of -- some type to a list of the same type -- 2. Inference is possible in the second case, because at this point -- in time, we're expecting a list of type Prop (context). -- "This is a central feature of dependent type theory: terms carry a -- lot of information, and often some of that information can be inferred -- from the context". #check cons _ prop_var l1 -- The "_" tells lean to infer the type. #check append _ l1 l2 #check cons _ prop_var (append _ l1 l2) -- This is still a pain in the arse. When we have a parameter that can -- generally be inferred, we can indicate to Lean that it should by -- default be left implicit, by wrapping it in braces: constant cons': Π {α: Type u}, α → list α → list α constant null': Π {α: Type u}, list α constant append': Π {α: Type u}, list α → list α → list α #check cons' prop_var l1 -- prop_var + l1 #check append' l1 l2 -- l1 + l2 #check cons' prop_var (append' l1 l2) -- prop_var + (l1 + l2) -- The above constants, and corresponding usages, are much cleaner. end hidden
d5ac29db1d232eacb276012d6c4eeabe4e4928aa
9dc8cecdf3c4634764a18254e94d43da07142918
/src/logic/nontrivial.lean
3a8c0541e54884cf6291039d28400223ca07ec4c
[ "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
10,914
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.prod.basic import data.subtype import logic.function.basic import logic.unique /-! # Nontrivial types A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings (where it is equivalent to the fact that zero is different from one) and for vector spaces (where it is equivalent to the fact that the dimension is positive). We introduce a typeclass `nontrivial` formalizing this property. -/ variables {α : Type*} {β : Type*} open_locale classical /-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings, this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/ class nontrivial (α : Type*) : Prop := (exists_pair_ne : ∃ (x y : α), x ≠ y) lemma nontrivial_iff : nontrivial α ↔ ∃ (x y : α), x ≠ y := ⟨λ h, h.exists_pair_ne, λ h, ⟨h⟩⟩ lemma exists_pair_ne (α : Type*) [nontrivial α] : ∃ (x y : α), x ≠ y := nontrivial.exists_pair_ne -- See Note [decidable namespace] protected lemma decidable.exists_ne [nontrivial α] [decidable_eq α] (x : α) : ∃ y, y ≠ x := begin rcases exists_pair_ne α with ⟨y, y', h⟩, by_cases hx : x = y, { rw ← hx at h, exact ⟨y', h.symm⟩ }, { exact ⟨y, ne.symm hx⟩ } end lemma exists_ne [nontrivial α] (x : α) : ∃ y, y ≠ x := by classical; exact decidable.exists_ne x -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. lemma nontrivial_of_ne (x y : α) (h : x ≠ y) : nontrivial α := ⟨⟨x, y, h⟩⟩ -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. lemma nontrivial_of_lt [preorder α] (x y : α) (h : x < y) : nontrivial α := ⟨⟨x, y, ne_of_lt h⟩⟩ lemma exists_pair_lt (α : Type*) [nontrivial α] [linear_order α] : ∃ (x y : α), x < y := begin rcases exists_pair_ne α with ⟨x, y, hxy⟩, cases lt_or_gt_of_ne hxy; exact ⟨_, _, h⟩ end lemma nontrivial_iff_lt [linear_order α] : nontrivial α ↔ ∃ (x y : α), x < y := ⟨λ h, @exists_pair_lt α h _, λ ⟨x, y, h⟩, nontrivial_of_lt x y h⟩ lemma nontrivial_iff_exists_ne (x : α) : nontrivial α ↔ ∃ y, y ≠ x := ⟨λ h, @exists_ne α h x, λ ⟨y, hy⟩, nontrivial_of_ne _ _ hy⟩ lemma subtype.nontrivial_iff_exists_ne (p : α → Prop) (x : subtype p) : nontrivial (subtype p) ↔ ∃ (y : α) (hy : p y), y ≠ x := by simp only [nontrivial_iff_exists_ne x, subtype.exists, ne.def, subtype.ext_iff, subtype.coe_mk] instance : nontrivial Prop := ⟨⟨true, false, true_ne_false⟩⟩ /-- See Note [lower instance priority] Note that since this and `nonempty_of_inhabited` are the most "obvious" way to find a nonempty instance if no direct instance can be found, we give this a higher priority than the usual `100`. -/ @[priority 500] instance nontrivial.to_nonempty [nontrivial α] : nonempty α := let ⟨x, _⟩ := exists_pair_ne α in ⟨x⟩ attribute [instance, priority 500] nonempty_of_inhabited /-- An inhabited type is either nontrivial, or has a unique element. -/ noncomputable def nontrivial_psum_unique (α : Type*) [inhabited α] : psum (nontrivial α) (unique α) := if h : nontrivial α then psum.inl h else psum.inr { default := default, uniq := λ (x : α), begin change x = default, contrapose! h, use [x, default] end } lemma subsingleton_iff : subsingleton α ↔ ∀ (x y : α), x = y := ⟨by { introsI h, exact subsingleton.elim }, λ h, ⟨h⟩⟩ lemma not_nontrivial_iff_subsingleton : ¬(nontrivial α) ↔ subsingleton α := by { rw [nontrivial_iff, subsingleton_iff], push_neg, refl } lemma not_nontrivial (α) [subsingleton α] : ¬nontrivial α := λ ⟨⟨x, y, h⟩⟩, h $ subsingleton.elim x y lemma not_subsingleton (α) [h : nontrivial α] : ¬subsingleton α := let ⟨⟨x, y, hxy⟩⟩ := h in λ ⟨h'⟩, hxy $ h' x y /-- A type is either a subsingleton or nontrivial. -/ lemma subsingleton_or_nontrivial (α : Type*) : subsingleton α ∨ nontrivial α := by { rw [← not_nontrivial_iff_subsingleton, or_comm], exact classical.em _ } lemma false_of_nontrivial_of_subsingleton (α : Type*) [nontrivial α] [subsingleton α] : false := let ⟨x, y, h⟩ := exists_pair_ne α in h $ subsingleton.elim x y instance option.nontrivial [nonempty α] : nontrivial (option α) := by { inhabit α, use [none, some default] } /-- Pushforward a `nontrivial` instance along an injective function. -/ protected lemma function.injective.nontrivial [nontrivial α] {f : α → β} (hf : function.injective f) : nontrivial β := let ⟨x, y, h⟩ := exists_pair_ne α in ⟨⟨f x, f y, hf.ne h⟩⟩ /-- Pullback a `nontrivial` instance along a surjective function. -/ protected lemma function.surjective.nontrivial [nontrivial β] {f : α → β} (hf : function.surjective f) : nontrivial α := begin rcases exists_pair_ne β with ⟨x, y, h⟩, rcases hf x with ⟨x', hx'⟩, rcases hf y with ⟨y', hy'⟩, have : x' ≠ y', by { contrapose! h, rw [← hx', ← hy', h] }, exact ⟨⟨x', y', this⟩⟩ end /-- An injective function from a nontrivial type has an argument at which it does not take a given value. -/ protected lemma function.injective.exists_ne [nontrivial α] {f : α → β} (hf : function.injective f) (y : β) : ∃ x, f x ≠ y := begin rcases exists_pair_ne α with ⟨x₁, x₂, hx⟩, by_cases h : f x₂ = y, { exact ⟨x₁, (hf.ne_iff' h).2 hx⟩ }, { exact ⟨x₂, h⟩ } end instance nontrivial_prod_right [nonempty α] [nontrivial β] : nontrivial (α × β) := prod.snd_surjective.nontrivial instance nontrivial_prod_left [nontrivial α] [nonempty β] : nontrivial (α × β) := prod.fst_surjective.nontrivial namespace pi variables {I : Type*} {f : I → Type*} /-- A pi type is nontrivial if it's nonempty everywhere and nontrivial somewhere. -/ lemma nontrivial_at (i' : I) [inst : Π i, nonempty (f i)] [nontrivial (f i')] : nontrivial (Π i : I, f i) := by classical; exact (function.update_injective (λ i, classical.choice (inst i)) i').nontrivial /-- As a convenience, provide an instance automatically if `(f default)` is nontrivial. If a different index has the non-trivial type, then use `haveI := nontrivial_at that_index`. -/ instance nontrivial [inhabited I] [inst : Π i, nonempty (f i)] [nontrivial (f default)] : nontrivial (Π i : I, f i) := nontrivial_at default end pi instance function.nontrivial [h : nonempty α] [nontrivial β] : nontrivial (α → β) := h.elim $ λ a, pi.nontrivial_at a mk_simp_attribute nontriviality "Simp lemmas for `nontriviality` tactic" protected lemma subsingleton.le [preorder α] [subsingleton α] (x y : α) : x ≤ y := le_of_eq (subsingleton.elim x y) attribute [nontriviality] eq_iff_true_of_subsingleton subsingleton.le namespace tactic /-- Tries to generate a `nontrivial α` instance by performing case analysis on `subsingleton_or_nontrivial α`, attempting to discharge the subsingleton branch using lemmas with `@[nontriviality]` attribute, including `subsingleton.le` and `eq_iff_true_of_subsingleton`. -/ meta def nontriviality_by_elim (α : expr) (lems : interactive.parse simp_arg_list) : tactic unit := do alternative ← to_expr ``(subsingleton_or_nontrivial %%α), n ← get_unused_name "_inst", tactic.cases alternative [n, n], (solve1 $ do reset_instance_cache, apply_instance <|> interactive.simp none none ff lems [`nontriviality] (interactive.loc.ns [none])) <|> fail format!"Could not prove goal assuming `subsingleton {α}`", reset_instance_cache /-- Tries to generate a `nontrivial α` instance using `nontrivial_of_ne` or `nontrivial_of_lt` and local hypotheses. -/ meta def nontriviality_by_assumption (α : expr) : tactic unit := do n ← get_unused_name "_inst", to_expr ``(nontrivial %%α) >>= assert n, apply_instance <|> `[solve_by_elim [nontrivial_of_ne, nontrivial_of_lt]], reset_instance_cache end tactic namespace tactic.interactive open tactic setup_tactic_parser /-- Attempts to generate a `nontrivial α` hypothesis. The tactic first looks for an instance using `apply_instance`. If the goal is an (in)equality, the type `α` is inferred from the goal. Otherwise, the type needs to be specified in the tactic invocation, as `nontriviality α`. The `nontriviality` tactic will first look for strict inequalities amongst the hypotheses, and use these to derive the `nontrivial` instance directly. Otherwise, it will perform a case split on `subsingleton α ∨ nontrivial α`, and attempt to discharge the `subsingleton` goal using `simp [lemmas] with nontriviality`, where `[lemmas]` is a list of additional `simp` lemmas that can be passed to `nontriviality` using the syntax `nontriviality α using [lemmas]`. ``` example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : 0 < a := begin nontriviality, -- There is now a `nontrivial R` hypothesis available. assumption, end ``` ``` example {R : Type} [comm_ring R] {r s : R} : r * s = s * r := begin nontriviality, -- There is now a `nontrivial R` hypothesis available. apply mul_comm, end ``` ``` example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : (2 : ℕ) ∣ 4 := begin nontriviality R, -- there is now a `nontrivial R` hypothesis available. dec_trivial end ``` ``` def myeq {α : Type} (a b : α) : Prop := a = b example {α : Type} (a b : α) (h : a = b) : myeq a b := begin success_if_fail { nontriviality α }, -- Fails nontriviality α using [myeq], -- There is now a `nontrivial α` hypothesis available assumption end ``` -/ meta def nontriviality (t : parse texpr?) (lems : parse (tk "using" *> simp_arg_list <|> pure [])) : tactic unit := do α ← match t with | some α := to_expr α | none := (do t ← mk_mvar, e ← to_expr ``(@eq %%t _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@has_le.le %%t _ _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@ne %%t _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@has_lt.lt %%t _ _ _), target >>= unify e, return t) <|> fail "The goal is not an (in)equality, so you'll need to specify the desired `nontrivial α` instance by invoking `nontriviality α`." end, nontriviality_by_assumption α <|> nontriviality_by_elim α lems add_tactic_doc { name := "nontriviality", category := doc_category.tactic, decl_names := [`tactic.interactive.nontriviality], tags := ["logic", "type class"] } end tactic.interactive namespace bool instance : nontrivial bool := ⟨⟨tt,ff, tt_eq_ff_eq_false⟩⟩ end bool
007ac43b9ecc8407f8305e2af08681be1ca6c924
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/control/traversable/instances.lean
ac851d89fb3fc32c066fa1adc3c59bc235b3f67f
[ "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
5,605
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Instances of `traversable` for types from the core library -/ import data.list.forall2 import data.set.lattice import control.traversable.lemmas universes u v section option open functor variables {F G : Type u → Type u} variables [applicative F] [applicative G] variables [is_lawful_applicative F] [is_lawful_applicative G] lemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x := by cases x; refl lemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) : option.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (option.traverse f <$> option.traverse g x) := by cases x; simp! with functor_norm; refl lemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) : traverse (id.mk ∘ f) x = id.mk (f <$> x) := by cases x; refl variable (η : applicative_transformation F G) lemma option.naturality {α β} (f : α → F β) (x : option α) : η (option.traverse f x) = option.traverse (@η _ ∘ f) x := by cases x with x; simp! [*] with functor_norm end option instance : is_lawful_traversable option := { id_traverse := @option.id_traverse, comp_traverse := @option.comp_traverse, traverse_eq_map_id := @option.traverse_eq_map_id, naturality := @option.naturality, .. option.is_lawful_monad } namespace list variables {F G : Type u → Type u} variables [applicative F] [applicative G] section variables [is_lawful_applicative F] [is_lawful_applicative G] open applicative functor open list (cons) protected lemma id_traverse {α} (xs : list α) : list.traverse id.mk xs = xs := by induction xs; simp! * with functor_norm; refl protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) : list.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (list.traverse f <$> list.traverse g x) := by induction x; simp! * with functor_norm; refl protected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) : list.traverse (id.mk ∘ f) x = id.mk (f <$> x) := by induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β} (f : α → F β) (x : list α) : η (list.traverse f x) = list.traverse (@η _ ∘ f) x := by induction x; simp! * with functor_norm open nat instance : is_lawful_traversable.{u} list := { id_traverse := @list.id_traverse, comp_traverse := @list.comp_traverse, traverse_eq_map_id := @list.traverse_eq_map_id, naturality := @list.naturality, .. list.is_lawful_monad } end section traverse variables {α' β' : Type u} (f : α' → F β') @[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl @[simp] lemma traverse_cons (a : α') (l : list α') : traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl variables [is_lawful_applicative F] @[simp] lemma traverse_append : ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs | [] bs := have has_append.append ([] : list β') = id, by funext; refl, by simp [this] with functor_norm | (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr lemma mem_traverse {f : α' → set β'} : ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l | [] [] := by simp | (a::as) [] := by simp; exact assume h, match h with end | [] (b::bs) := by simp | (a::as) (b::bs) := suffices (b :: bs : list β') ∈ traverse f (a :: as) ↔ b ∈ f a ∧ bs ∈ traverse f as, by simpa [mem_traverse as bs], iff.intro (assume ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩, ⟨hb, hl⟩) (assume ⟨hb, hl⟩, ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩) end traverse end list namespace sum section traverse variables {σ : Type u} variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) variables [is_lawful_applicative F] [is_lawful_applicative G] protected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x := by cases x; refl protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) : sum.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (sum.traverse f <$> sum.traverse g x) := by cases x; simp! [sum.traverse,map_id] with functor_norm; refl protected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) : sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) := by induction x; simp! * with functor_norm; refl protected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) : (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x := by cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl protected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) : sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x := by cases x; simp [sum.traverse, id_map] with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) : η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x := by cases x; simp! [sum.traverse] with functor_norm end traverse instance {σ : Type u} : is_lawful_traversable.{u} (sum σ) := { id_traverse := @sum.id_traverse σ, comp_traverse := @sum.comp_traverse σ, traverse_eq_map_id := @sum.traverse_eq_map_id σ, naturality := @sum.naturality σ, .. sum.is_lawful_monad } end sum