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
32c0fa8a6de911eeb674c9985e75d31d2570a06b
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/smt/smt_tactic.lean
c64c24edeb05ca3a4545345c43c268789f7b3e84
[ "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
15,126
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.control import init.meta.simp_tactic import init.meta.smt.congruence_closure import init.meta.smt.ematch universe u run_cmd mk_simp_attr `pre_smt run_cmd mk_hinst_lemma_attr_set `ematch [] [`ematch_lhs] /-- Configuration for the smt tactic preprocessor. The preprocessor is applied whenever a new hypothesis is introduced. - simp_attr: is the attribute name for the simplification lemmas that are used during the preprocessing step. - max_steps: it is the maximum number of steps performed by the simplifier. - zeta: if tt, then zeta reduction (i.e., unfolding let-expressions) is used during preprocessing. -/ structure smt_pre_config := (simp_attr : name := `pre_smt) (max_steps : nat := 1000000) (zeta : bool := ff) /-- Configuration for the smt_state object. - em_attr: is the attribute name for the hinst_lemmas that are used for ematching -/ structure smt_config := (cc_cfg : cc_config := {}) (em_cfg : ematch_config := {}) (pre_cfg : smt_pre_config := {}) (em_attr : name := `ematch) meta def smt_config.set_classical (c : smt_config) (b : bool) : smt_config := { cc_cfg := { em := b, ..c.cc_cfg }, ..c } meta constant smt_goal : Type meta def smt_state := list smt_goal meta constant smt_state.mk : smt_config → tactic smt_state meta constant smt_state.to_format : smt_state → tactic_state → format /-- Return tt iff classical excluded middle was enabled at smt_state.mk -/ meta constant smt_state.classical : smt_state → bool meta def smt_tactic := state_t smt_state tactic meta instance : has_append smt_state := list.has_append section local attribute [reducible] smt_tactic meta instance : monad smt_tactic := by apply_instance meta instance : alternative smt_tactic := by apply_instance meta instance : monad_state smt_state smt_tactic := by apply_instance end /- We don't use the default state_t lift operation because only tactics that do not change hypotheses can be automatically lifted to smt_tactic. -/ meta constant tactic_to_smt_tactic (α : Type) : tactic α → smt_tactic α meta instance : has_monad_lift tactic smt_tactic := ⟨tactic_to_smt_tactic⟩ meta instance (α : Type) : has_coe (tactic α) (smt_tactic α) := ⟨monad_lift⟩ meta instance : monad_fail smt_tactic := { fail := λ α s, (tactic.fail (to_fmt s) : smt_tactic α), ..smt_tactic.monad } namespace smt_tactic open tactic (transparency) meta constant intros : smt_tactic unit meta constant intron : nat → smt_tactic unit meta constant intro_lst : list name → smt_tactic unit /-- Try to close main goal by using equalities implied by the congruence closure module. -/ meta constant close : smt_tactic unit /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from lemmas in the main goal with terms in the main goal. The set of lemmas is populated with theorems tagged with the attribute specified at smt_config.em_attr, and lemmas added using tactics such as `smt_tactic.add_lemmas`. The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`. Remark: the given predicate is applied to every new instance. The instance is only added to the state if the predicate returns tt. -/ meta constant ematch_core : (expr → bool) → smt_tactic unit /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from the given lemmas with terms in the main goal. -/ meta constant ematch_using : hinst_lemmas → smt_tactic unit meta constant mk_ematch_eqn_lemmas_for_core : transparency → name → smt_tactic hinst_lemmas meta constant to_cc_state : smt_tactic cc_state meta constant to_em_state : smt_tactic ematch_state meta constant get_config : smt_tactic smt_config /-- Preprocess the given term using the same simplifications rules used when we introduce a new hypothesis. The result is pair containing the resulting term and a proof that it is equal to the given one. -/ meta constant preprocess : expr → smt_tactic (expr × expr) meta constant get_lemmas : smt_tactic hinst_lemmas meta constant set_lemmas : hinst_lemmas → smt_tactic unit meta constant add_lemmas : hinst_lemmas → smt_tactic unit meta def add_ematch_lemma_core (md : transparency) (as_simp : bool) (e : expr) : smt_tactic unit := do h ← hinst_lemma.mk_core md e as_simp, add_lemmas (mk_hinst_singleton h) meta def add_ematch_lemma_from_decl_core (md : transparency) (as_simp : bool) (n : name) : smt_tactic unit := do h ← hinst_lemma.mk_from_decl_core md n as_simp, add_lemmas (mk_hinst_singleton h) meta def add_ematch_eqn_lemmas_for_core (md : transparency) (n : name) : smt_tactic unit := do hs ← mk_ematch_eqn_lemmas_for_core md n, add_lemmas hs meta def ematch : smt_tactic unit := ematch_core (λ _, tt) meta def failed {α} : smt_tactic α := tactic.failed meta def fail {α : Type} {β : Type u} [has_to_format β] (msg : β) : smt_tactic α := tactic.fail msg meta def try {α : Type} (t : smt_tactic α) : smt_tactic unit := ⟨λ ss ts, result.cases_on (t.run ss ts) (λ ⟨a, new_ss⟩, result.success ((), new_ss)) (λ e ref s', result.success ((), ss) ts)⟩ /-- `iterate_at_most n t`: repeat the given tactic at most n times or until t fails -/ meta def iterate_at_most : nat → smt_tactic unit → smt_tactic unit | 0 t := return () | (n+1) t := (do t, iterate_at_most n t) <|> return () /-- `iterate_exactly n t` : execute t n times -/ meta def iterate_exactly : nat → smt_tactic unit → smt_tactic unit | 0 t := return () | (n+1) t := do t, iterate_exactly n t meta def iterate : smt_tactic unit → smt_tactic unit := iterate_at_most 100000 meta def eblast : smt_tactic unit := iterate (ematch >> try close) open tactic protected meta def read : smt_tactic (smt_state × tactic_state) := do s₁ ← get, s₂ ← tactic.read, return (s₁, s₂) protected meta def write : smt_state × tactic_state → smt_tactic unit := λ ⟨ss, ts⟩, ⟨λ _ _, result.success ((), ss) ts⟩ private meta def mk_smt_goals_for (cfg : smt_config) : list expr → list smt_goal → list expr → tactic (list smt_goal × list expr) | [] sr tr := return (sr.reverse, tr.reverse) | (tg::tgs) sr tr := do tactic.set_goals [tg], [new_sg] ← smt_state.mk cfg | tactic.failed, [new_tg] ← get_goals | tactic.failed, mk_smt_goals_for tgs (new_sg::sr) (new_tg::tr) /-- See slift -/ meta def slift_aux {α : Type} (t : tactic α) (cfg : smt_config) : smt_tactic α := ⟨λ ss, do _::sgs ← return ss | tactic.fail "slift tactic failed, there no smt goals to be solved", tg::tgs ← tactic.get_goals | tactic.failed, tactic.set_goals [tg], a ← t, new_tgs ← tactic.get_goals, (new_sgs, new_tgs) ← mk_smt_goals_for cfg new_tgs [] [], tactic.set_goals (new_tgs ++ tgs), return (a, new_sgs ++ sgs)⟩ /-- This lift operation will restart the SMT state. It is useful for using tactics that change the set of hypotheses. -/ meta def slift {α : Type} (t : tactic α) : smt_tactic α := get_config >>= slift_aux t meta def trace_state : smt_tactic unit := do (s₁, s₂) ← smt_tactic.read, trace (smt_state.to_format s₁ s₂) meta def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic unit := tactic.trace a meta def to_expr (q : pexpr) (allow_mvars := tt) : smt_tactic expr := tactic.to_expr q allow_mvars meta def classical : smt_tactic bool := do s ← get, return s.classical meta def num_goals : smt_tactic nat := list.length <$> get /- Low level primitives for managing set of goals -/ meta def get_goals : smt_tactic (list smt_goal × list expr) := do (g₁, _) ← smt_tactic.read, g₂ ← tactic.get_goals, return (g₁, g₂) meta def set_goals : list smt_goal → list expr → smt_tactic unit := λ g₁ g₂, ⟨λ ss, tactic.set_goals g₂ >> return ((), g₁)⟩ private meta def all_goals_core (tac : smt_tactic unit) : list smt_goal → list expr → list smt_goal → list expr → smt_tactic unit | [] ts acs act := set_goals acs (ts ++ act) | (s :: ss) [] acs act := fail "ill-formed smt_state" | (s :: ss) (t :: ts) acs act := do set_goals [s] [t], tac, (new_ss, new_ts) ← get_goals, all_goals_core ss ts (acs ++ new_ss) (act ++ new_ts) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : smt_tactic unit) : smt_tactic unit := do (ss, ts) ← get_goals, all_goals_core tac ss ts [] [] /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : smt_tactic unit) (tac2 : smt_tactic unit) : smt_tactic unit := do (s::ss, t::ts) ← get_goals, set_goals [s] [t], tac1, all_goals tac2, (new_ss, new_ts) ← get_goals, set_goals (new_ss ++ ss) (new_ts ++ ts) meta instance : has_andthen (smt_tactic unit) (smt_tactic unit) (smt_tactic unit) := ⟨seq⟩ meta def focus1 {α} (tac : smt_tactic α) : smt_tactic α := do (s::ss, t::ts) ← get_goals, match ss with | [] := tac | _ := do set_goals [s] [t], a ← tac, (ss', ts') ← get_goals, set_goals (ss' ++ ss) (ts' ++ ts), return a end meta def solve1 (tac : smt_tactic unit) : smt_tactic unit := do (ss, gs) ← get_goals, match ss, gs with | [], _ := fail "solve1 tactic failed, there isn't any goal left to focus" | _, [] := fail "solve1 tactic failed, there isn't any smt goal left to focus" | s::ss, g::gs := do set_goals [s] [g], tac, (ss', gs') ← get_goals, match ss', gs' with | [], [] := set_goals ss gs | _, _ := fail "solve1 tactic failed, focused goal has not been solved" end end meta def swap : smt_tactic unit := do (ss, ts) ← get_goals, match ss, ts with | (s₁ :: s₂ :: ss), (t₁ :: t₂ :: ts) := set_goals (s₂ :: s₁ :: ss) (t₂ :: t₁ :: ts) | _, _ := failed end /-- Add a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : smt_tactic unit := tactic.assert_core h t >> swap >> intros >> swap >> try close /-- Add the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : smt_tactic unit := tactic.assertv_core h t v >> intros >> return () /-- Add a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : smt_tactic unit := tactic.define_core h t >> swap >> intros >> swap >> try close /-- Add the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : smt_tactic unit := tactic.definev_core h t v >> intros >> return () /-- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : smt_tactic unit := match t with | none := do t ← infer_type pr, definev h t pr | some t := definev h t pr end /-- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (h : name) (t : option expr := none) (pr : expr) : smt_tactic unit := match t with | none := do t ← infer_type pr, assertv h t pr | some t := assertv h t pr end meta def destruct (e : expr) : smt_tactic unit := smt_tactic.seq (tactic.destruct e) smt_tactic.intros meta def by_cases (e : expr) : smt_tactic unit := do c ← classical, if c then destruct (expr.app (expr.const `classical.em []) e) else do dec_e ← (mk_app `decidable [e] <|> fail "by_cases smt_tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases smt_tactic failed, type of given expression is not decidable"), em ← mk_app `decidable.em [e, inst], destruct em meta def by_contradiction : smt_tactic unit := do t ← target, c ← classical, if t.is_false then skip else if c then do apply (expr.app (expr.const `classical.by_contradiction []) t), intros else do dec_t ← (mk_app `decidable [t] <|> fail "by_contradiction smt_tactic failed, target is not a proposition"), inst ← (mk_instance dec_t <|> fail "by_contradiction smt_tactic failed, target is not decidable"), a ← mk_mapp `decidable.by_contradiction [some t, some inst], apply a, intros /-- Return a proof for e, if 'e' is a known fact in the main goal. -/ meta def proof_for (e : expr) : smt_tactic expr := do cc ← to_cc_state, cc.proof_for e /-- Return a refutation for e (i.e., a proof for (not e)), if 'e' has been refuted in the main goal. -/ meta def refutation_for (e : expr) : smt_tactic expr := do cc ← to_cc_state, cc.refutation_for e meta def get_facts : smt_tactic (list expr) := do cc ← to_cc_state, return $ cc.eqc_of expr.mk_true meta def get_refuted_facts : smt_tactic (list expr) := do cc ← to_cc_state, return $ cc.eqc_of expr.mk_false meta def add_ematch_lemma : expr → smt_tactic unit := add_ematch_lemma_core reducible ff meta def add_ematch_lhs_lemma : expr → smt_tactic unit := add_ematch_lemma_core reducible tt meta def add_ematch_lemma_from_decl : name → smt_tactic unit := add_ematch_lemma_from_decl_core reducible ff meta def add_ematch_lhs_lemma_from_decl : name → smt_tactic unit := add_ematch_lemma_from_decl_core reducible ff meta def add_ematch_eqn_lemmas_for : name → smt_tactic unit := add_ematch_eqn_lemmas_for_core reducible meta def add_lemmas_from_facts_core : list expr → smt_tactic unit | [] := return () | (f::fs) := do try (is_prop f >> guard (f.is_pi && bnot (f.is_arrow)) >> proof_for f >>= add_ematch_lemma_core reducible ff), add_lemmas_from_facts_core fs meta def add_lemmas_from_facts : smt_tactic unit := get_facts >>= add_lemmas_from_facts_core meta def induction (e : expr) (ids : list name := []) (rec : option name := none) : smt_tactic unit := slift (tactic.induction e ids rec >> return ()) -- pass on the information? meta def when (c : Prop) [decidable c] (tac : smt_tactic unit) : smt_tactic unit := if c then tac else skip meta def when_tracing (n : name) (tac : smt_tactic unit) : smt_tactic unit := when (is_trace_enabled_for n = tt) tac end smt_tactic open smt_tactic meta def using_smt {α} (t : smt_tactic α) (cfg : smt_config := {}) : tactic α := do ss ← smt_state.mk cfg, (a, _) ← (do a ← t, iterate close, return a).run ss, return a meta def using_smt_with {α} (cfg : smt_config) (t : smt_tactic α) : tactic α := using_smt t cfg
3f25532d62729cb72ce7b08cbc13417dc88e15b0
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/common/cairo_secp/ec_spec.lean
e0d3dd146de16b4b3445d869d3c75e86ef091546
[]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
65,519
lean
/- Specifications file for ec_spec.cairo Do not modify the constant definitions, structure definitions, or automatic specifications. Do not change the name or arguments of the user specifications and soundness theorems. You may freely move the definitions around in the file. You may add definitions and theorems wherever you wish in this file. -/ import starkware.cairo.lean.semantics.soundness.prelude import starkware.cairo.common.cairo_secp.bigint_spec import starkware.cairo.common.cairo_secp.field_spec import starkware.cairo.common.cairo_secp.constants_spec -- JDA: Additional import. import starkware.cairo.common.cairo_secp.elliptic_curves open starkware.cairo.common.cairo_secp.bigint open starkware.cairo.common.cairo_secp.field open starkware.cairo.common.cairo_secp.constants namespace starkware.cairo.common.cairo_secp.ec variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F] -- End of automatically generated prelude. -- Main scope definitions. @[ext] structure EcPoint (F : Type) := ( x : BigInt3 F ) ( y : BigInt3 F ) @[ext] structure π_EcPoint (F : Type) := ( σ_ptr : F ) ( x : BigInt3 F ) ( y : BigInt3 F ) @[reducible] def φ_EcPoint.x := 0 @[reducible] def φ_EcPoint.y := 3 @[reducible] def φ_EcPoint.SIZE := 6 @[reducible] def cast_EcPoint (mem : F → F) (p : F) : EcPoint F := { x := cast_BigInt3 mem (p + φ_EcPoint.x), y := cast_BigInt3 mem (p + φ_EcPoint.y) } @[reducible] def cast_π_EcPoint (mem : F → F) (p : F) : π_EcPoint F := { σ_ptr := mem p, x := cast_BigInt3 mem ((mem p) + φ_EcPoint.x), y := cast_BigInt3 mem ((mem p) + φ_EcPoint.y) } instance π_EcPoint_to_F : has_coe (π_EcPoint F) F := ⟨λ s, s.σ_ptr⟩ -- End of main scope definitions. /- -- Data for writing the specifications. -/ structure BddECPointData (secpF : Type*) [field secpF] (pt : EcPoint F) := (ix iy : bigint3) (ixbdd : ix.bounded (3 * BASE - 1)) (iybdd : iy.bounded (3 * BASE - 1)) (ptxeq : pt.x = ix.toBigInt3) (ptyeq : pt.y = iy.toBigInt3) (onEC : pt.x = ⟨0, 0, 0⟩ ∨ (iy.val : secpF)^2 = (ix.val : secpF)^3 + 7) theorem BddECPointData.onEC' {secpF : Type*} [field secpF] {pt : EcPoint F} (h : BddECPointData secpF pt) (h' : pt.x ≠ ⟨0, 0, 0⟩) : (h.iy.val : secpF)^2 = (h.ix.val : secpF)^3 + 7 := or.resolve_left h.onEC h' section secpF variables {secpF : Type} -- in practice, zmod SECP_PRIME [field secpF] -- in practice, @zmod.field _ ⟨prime_secp⟩ [char_p secpF SECP_PRIME] [decidable_eq secpF] def BddECPointData.toECPoint {pt : EcPoint F} (h : BddECPointData secpF pt) : ECPoint secpF := if h' : pt.x = ⟨0, 0, 0⟩ then ECPoint.ZeroPoint else ECPoint.AffinePoint ⟨h.ix.val, h.iy.val, h.onEC' h'⟩ def BddECPointData.zero : BddECPointData secpF (⟨⟨0, 0, 0⟩, ⟨0, 0, 0⟩⟩ : EcPoint F) := { ix := ⟨0, 0, 0⟩, iy := ⟨0, 0, 0⟩, ixbdd := by simp [bigint3.bounded]; norm_num1, iybdd := by simp [bigint3.bounded]; norm_num1, ptxeq := by simp [bigint3.toBigInt3], ptyeq := by simp [bigint3.toBigInt3], onEC := or.inl rfl } end secpF def SECP_LOG2_BOUND := 100 class secp_field (secpF : Type*) extends ec_field secpF, char_p secpF SECP_PRIME := (seven_not_square : ∀ y : secpF, y^2 ≠ 7) (neg_seven_not_cube : ∀ x : secpF, x^3 ≠ -7) (order_large : ∀ {pt : ECPoint secpF}, pt ≠ 0 → ∀ {n : ℕ}, n < 2^SECP_LOG2_BOUND → ¬ (n • pt = 0 ∨ n • pt = pt ∨ n • pt = -pt)) theorem secp_field.y_ne_zero_of_on_ec {secpF : Type*} [secp_field secpF] {x y : secpF} (h : on_ec (x, y)) : y ≠ 0 := by { contrapose! h, simp [on_ec, h, ←sub_eq_iff_eq_add], apply ne.symm, apply secp_field.neg_seven_not_cube } theorem secp_field.x_ne_zero_of_on_ec {secpF : Type*} [secp_field secpF] {x y : secpF} (h : on_ec (x, y)) : x ≠ 0 := by { contrapose! h, simp [on_ec, h, secp_field.seven_not_square] } theorem secp_field.eq_zero_of_double_eq_zero {secpF : Type*} [secp_field secpF] {x : ECPoint secpF} (h : 2 • x = 0) : x = 0 := begin cases x, { refl }, simp [two_smul, ECPoint.add_def, ECPoint.add] at h, have : x.y ≠ -x.y, { intro h', have h_on_ec := x.h, dsimp [on_ec] at h_on_ec, have : 2 * x.y = 0, { rwa [two_mul, ←eq_neg_iff_add_eq_zero] }, rw mul_eq_zero at this, simp [or.resolve_left this ec_field.two_ne_zero] at h_on_ec, apply secp_field.neg_seven_not_cube x.x, exact eq_neg_iff_add_eq_zero.mpr h_on_ec.symm }, rw dif_neg this at h, contradiction end namespace BddECPointData theorem toECPoint_zero (secpF : Type) [secp_field secpF] : (BddECPointData.zero : BddECPointData secpF (⟨⟨0, 0, 0⟩, ⟨0, 0, 0⟩⟩ : EcPoint F)).toECPoint = 0 := by { simp [toECPoint], refl } theorem pt_zero_iff' {secpF : Type} [secp_field secpF] {pt : EcPoint F} (h : BddECPointData secpF pt) : pt.x = ⟨0, 0, 0⟩ ↔ h.ix.val = 0 := begin split, { rw [h.ptxeq], intro heq, rw toBigInt3_eq_zero_of_bounded_3BASE heq h.ixbdd, simp [bigint3.val] }, intro heq, cases h.onEC with h1 h1, { exact h1 }, exfalso, have : on_ec ((h.ix.val : secpF), (h.iy.val : secpF)):= h1, apply secp_field.x_ne_zero_of_on_ec this, simp [heq] end theorem pt_zero_iff {secpF : Type} [secp_field secpF] {pt : EcPoint F} (h : BddECPointData secpF pt) : pt.x = ⟨0, 0, 0⟩ ↔ (h.ix.val : secpF) = 0 := begin split, { rw [h.ptxeq], intro heq, rw toBigInt3_eq_zero_of_bounded_3BASE heq h.ixbdd, simp [bigint3.val] }, intro heq, cases h.onEC with h1 h1, { exact h1 }, exfalso, have : on_ec ((h.ix.val : secpF), (h.iy.val : secpF)):= h1, apply secp_field.x_ne_zero_of_on_ec this, simp [heq] end theorem toECPoint_eq_zero_iff {secpF : Type} [secp_field secpF] {pt : EcPoint F} (h : BddECPointData secpF pt) : h.toECPoint = 0 ↔ pt.x = ⟨0, 0, 0⟩ := by { by_cases h : pt.x = ⟨0, 0, 0⟩; simp [BddECPointData.toECPoint, h, ECPoint.zero_def] } theorem toECPoint_eq_of_eq_of_ne {secpF : Type} [secp_field secpF] {pt0 pt1 : EcPoint F} {h0 : BddECPointData secpF pt0} {h1 : BddECPointData secpF pt1} (hxeq : (h0.ix.val : secpF) = (h1.ix.val : secpF)) (hyne : (h0.iy.val : secpF) ≠ -(h1.iy.val : secpF)) : h0.toECPoint = h1.toECPoint := begin have aux: pt0.x = ⟨0, 0, 0⟩ ↔ pt1.x = ⟨0, 0, 0⟩, { rw [h1.pt_zero_iff, ←hxeq, ←h0.pt_zero_iff] }, by_cases h: pt0.x = ⟨0, 0, 0⟩, { have : pt1.x = ⟨0, 0, 0⟩, by rwa ←aux, rw [h0.toECPoint_eq_zero_iff.mpr h, h1.toECPoint_eq_zero_iff.mpr this] }, have : ¬ (pt1.x = ⟨0, 0, 0⟩), by rwa ←aux, rw [BddECPointData.toECPoint, BddECPointData.toECPoint, dif_neg h, dif_neg this], congr' 1, ext, { exact hxeq }, dsimp, have : (h0.iy.val : secpF)^2 = (h1.iy.val : secpF)^2, { rw [h0.onEC' h, h1.onEC' this, hxeq] }, have := eq_or_eq_neg_of_sq_eq_sq _ _ this, exact or.resolve_right this hyne end end BddECPointData theorem double_Affine {secpF : Type} [secp_field secpF] {x1 y1 x2 y2 : secpF} (h1 : on_ec (x1, y1)) (h2 : on_ec (x2, y2)) (heq : ec_double (x1, y1) = (x2, y2)) : 2 • ECPoint.AffinePoint ⟨x1, y1, h1⟩ = ECPoint.AffinePoint ⟨x2, y2, h2⟩ := begin have : y1 ≠ -y1, { intro heq, apply secp_field.y_ne_zero_of_on_ec h1, have : 2 * y1 = 0, { rwa [two_mul, add_eq_zero_iff_eq_neg] }, rw mul_eq_zero at this, exact this.resolve_left ec_field.two_ne_zero }, rw two_smul, simp [ECPoint.add_def, ECPoint.add], dsimp, rw [dif_neg this], congr; simp [heq] end theorem Affine_add_Affine {secpF : Type} [secp_field secpF] {x1 y1 x2 y2 x3 y3 : secpF} (h1 : on_ec (x1, y1)) (h2 : on_ec (x2, y2)) (h3 : on_ec (x3, y3)) (hne : x1 ≠ x2) (heq : ec_add (x1, y1) (x2, y2) = (x3, y3)) : ECPoint.AffinePoint ⟨x1, y1, h1⟩ + ECPoint.AffinePoint ⟨x2, y2, h2⟩ = ECPoint.AffinePoint ⟨x3, y3, h3⟩ := begin simp [ECPoint.add_def, ECPoint.add], dsimp, rw [dif_neg hne], congr; simp [heq] end /- -- Function: ec_negate -/ /- ec_negate autogenerated specification -/ -- Do not change this definition. def auto_spec_ec_negate (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_point : EcPoint F) : Prop := ∃ (κ₁ : ℕ) (range_check_ptr₁ : F) (minus_y : BigInt3 F), spec_nondet_bigint3 mem κ₁ range_check_ptr range_check_ptr₁ minus_y ∧ ∃ (κ₂ : ℕ) (range_check_ptr₂ : F), spec_verify_zero mem κ₂ range_check_ptr₁ { d0 := minus_y.d0 + point.y.d0, d1 := minus_y.d1 + point.y.d1, d2 := minus_y.d2 + point.y.d2 } range_check_ptr₂ ∧ κ₁ + κ₂ + 14 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr₂ ∧ ρ_point = { x := point.x, y := minus_y } -- You may change anything in this definition except the name and arguments. def spec_ec_negate (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_point : EcPoint F) : Prop := ∀ ix iy : bigint3, ix.bounded (3 * BASE - 1) → iy.bounded (3 * BASE - 1) → point.x = ix.toBigInt3 → point.y = iy.toBigInt3 → ∃ ineg_y : bigint3, ineg_y.bounded (3 * (BASE - 1)) ∧ ρ_point = { x := ix.toBigInt3, y := ineg_y.toBigInt3 } ∧ ineg_y.val ≡ - iy.val [ZMOD SECP_PRIME] /- ec_negate soundness theorem -/ -- Do not change the statement of this theorem. You may change the proof. theorem sound_ec_negate {mem : F → F} (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_point : EcPoint F) (h_auto : auto_spec_ec_negate mem κ range_check_ptr point ρ_range_check_ptr ρ_point) : spec_ec_negate mem κ range_check_ptr point ρ_range_check_ptr ρ_point := begin intros ix iy ixbdd iybdd ptxeq ptyeq, rcases h_auto with ⟨_, _, neg_y, hneg_y, _, _, hverify_zero, _, _, ρ_point_eq⟩, rcases nondet_bigint3_corr hneg_y with ⟨ineg_y, neg_y_eq, ineg_y_bdd⟩, use [ineg_y, ineg_y_bdd], split, { rw [ρ_point_eq, ptxeq, neg_y_eq] }, rw [int.modeq_iff_sub_mod_eq_zero, sub_neg_eq_add, ←bigint3.add_val], apply hverify_zero, { simp [ptyeq, neg_y_eq, bigint3.add, bigint3.toUnreducedBigInt3, bigint3.toBigInt3] }, apply bigint3.bounded_of_bounded_of_le, apply bigint3.bounded_add ineg_y_bdd iybdd, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 end /- Better specification. -/ def spec_ec_negate' ( pt : EcPoint F ) ( ret : EcPoint F ) (secpF : Type) [secp_field secpF] : Prop := ∀ h : BddECPointData secpF pt, ∃ hret : BddECPointData secpF ret, hret.toECPoint = -h.toECPoint theorem spec_ec_negate'_of_spec_ec_negate {mem : F → F} {κ : ℕ} {range_check_ptr : F} {pt : EcPoint F} {ret0 : F} {ret : EcPoint F} (h : spec_ec_negate mem κ range_check_ptr pt ret0 ret) (secpF : Type) [secp_field secpF] : spec_ec_negate' pt ret secpF := begin intro hpt, rcases h hpt.ix hpt.iy hpt.ixbdd hpt.iybdd hpt.ptxeq hpt.ptyeq with ⟨ineg_y, ineg_y_bdd, reteq, hineg_y⟩, have inegyvaleq : (ineg_y.val : secpF) = - (hpt.iy.val : secpF), { rw [←int.cast_neg, char_p.int_coe_eq_int_coe_iff secpF SECP_PRIME], exact hineg_y }, rw EcPoint.ext_iff at reteq, have retx_eq_ptx : ret.x = pt.x := reteq.1.trans (hpt.ptxeq.symm), let hret : BddECPointData secpF ret := { ix := hpt.ix, iy := ineg_y, ixbdd := hpt.ixbdd, iybdd := bigint3.bounded_of_bounded_of_le ineg_y_bdd bound_slack, ptxeq := reteq.1, ptyeq := reteq.2, onEC := begin cases hpt.onEC with h' h', { exact or.inl (retx_eq_ptx.trans h') }, right, rw [inegyvaleq, neg_sq, h'] end }, use hret, simp [BddECPointData.toECPoint], by_cases h' : pt.x = ⟨0, 0, 0⟩, { rw [dif_pos h', dif_pos (retx_eq_ptx.trans h')], refl }, rw [dif_neg h', dif_neg (ne_of_eq_of_ne retx_eq_ptx h')], simp [ECPoint.neg_def, ECPoint.neg, inegyvaleq] end /- -- Function: compute_doubling_slope -/ /- compute_doubling_slope autogenerated specification -/ -- Do not change this definition. def auto_spec_compute_doubling_slope (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_slope : BigInt3 F) : Prop := ∃ (κ₁ : ℕ) (range_check_ptr₁ : F) (slope : BigInt3 F), spec_nondet_bigint3 mem κ₁ range_check_ptr range_check_ptr₁ slope ∧ ∃ (κ₂ : ℕ) (x_sqr : UnreducedBigInt3 F), spec_unreduced_sqr mem κ₂ point.x x_sqr ∧ ∃ (κ₃ : ℕ) (slope_y : UnreducedBigInt3 F), spec_unreduced_mul mem κ₃ slope point.y slope_y ∧ ∃ (κ₄ : ℕ) (range_check_ptr₂ : F), spec_verify_zero mem κ₄ range_check_ptr₁ { d0 := 3 * x_sqr.d0 - 2 * slope_y.d0, d1 := 3 * x_sqr.d1 - 2 * slope_y.d1, d2 := 3 * x_sqr.d2 - 2 * slope_y.d2 } range_check_ptr₂ ∧ κ₁ + κ₂ + κ₃ + κ₄ + 34 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr₂ ∧ ρ_slope = slope -- You may change anything in this definition except the name and arguments. def spec_compute_doubling_slope (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_slope : BigInt3 F) : Prop := ∀ ix iy : bigint3, ix.bounded (3 * BASE - 1) → iy.bounded (3 * BASE - 1) → point.x = ix.toBigInt3 → point.y = iy.toBigInt3 → ∃ is : bigint3, is.bounded (3 * (BASE - 1)) ∧ ρ_slope = is.toBigInt3 ∧ 3 * ix.val^2 ≡ 2 * iy.val * is.val [ZMOD SECP_PRIME] /- compute_doubling_slope soundness theorem -/ -- Do not change the statement of this theorem. You may change the proof. theorem sound_compute_doubling_slope {mem : F → F} (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_slope : BigInt3 F) (h_auto : auto_spec_compute_doubling_slope mem κ range_check_ptr point ρ_range_check_ptr ρ_slope) : spec_compute_doubling_slope mem κ range_check_ptr point ρ_range_check_ptr ρ_slope := begin rcases h_auto with ⟨_, _, slope, valid_slope, _, x_sqr, hx, _, slope_y, hslope_y, _, _, vz, _, _, ret1eq⟩, rcases nondet_bigint3_corr valid_slope with ⟨is, slopeeq, isbdd⟩, intros ix iy ixbdd iybdd ptxeq ptyeq, have x_sqr_eq := hx _ ptxeq, have slope_y_eq := hslope_y _ _ slopeeq ptyeq, refine ⟨_, isbdd, ret1eq.trans slopeeq, _⟩, set diff : bigint3 := (ix.sqr.cmul 3).sub ((iy.mul is).cmul 2) with diff_eq, have diff_bdd : diff.bounded (5 * ((3 * BASE - 1)^2 * (8 * SECP_REM + 1))), { rw [diff_eq, (show (5 : ℤ) = 3 + 2, by norm_num), add_mul], apply bigint3.bounded_sub, apply bigint3.bounded_cmul' (show (0 : ℤ) ≤ 3, by norm_num1), apply bigint3.bounded_sqr ixbdd, apply bigint3.bounded_cmul' (show (0 : ℤ) ≤ 2, by norm_num1), apply bigint3.bounded_mul iybdd, apply bigint3.bounded_of_bounded_of_le isbdd bound_slack }, have : diff.val % SECP_PRIME = 0, { apply vz, { simp only [diff_eq, x_sqr_eq, slope_y_eq], dsimp [bigint3.toUnreducedBigInt3, bigint3.sqr, bigint3.mul, bigint3.cmul, bigint3.sub], simp_int_casts, split, ring, split, ring, ring }, apply bigint3.bounded_of_bounded_of_le diff_bdd, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 }, symmetry, rw [int.modeq_iff_dvd, int.dvd_iff_mod_eq_zero, ←this, diff_eq, bigint3.sub_val, bigint3.cmul_val, bigint3.cmul_val], apply int.modeq.sub, apply int.modeq.mul_left, apply int.modeq.symm, apply bigint3.sqr_val, rw mul_assoc, apply int.modeq.mul_left, apply int.modeq.symm, apply bigint3.mul_val end /- -- Function: compute_slope -/ /- compute_slope autogenerated specification -/ -- Do not change this definition. def auto_spec_compute_slope (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_slope : BigInt3 F) : Prop := ∃ (κ₁ : ℕ) (range_check_ptr₁ : F) (slope : BigInt3 F), spec_nondet_bigint3 mem κ₁ range_check_ptr range_check_ptr₁ slope ∧ ∃ x_diff : BigInt3 F, x_diff = { d0 := point0.x.d0 - point1.x.d0, d1 := point0.x.d1 - point1.x.d1, d2 := point0.x.d2 - point1.x.d2 } ∧ ∃ (κ₂ : ℕ) (x_diff_slope : UnreducedBigInt3 F), spec_unreduced_mul mem κ₂ x_diff slope x_diff_slope ∧ ∃ (κ₃ : ℕ) (range_check_ptr₂ : F), spec_verify_zero mem κ₃ range_check_ptr₁ { d0 := x_diff_slope.d0 - point0.y.d0 + point1.y.d0, d1 := x_diff_slope.d1 - point0.y.d1 + point1.y.d1, d2 := x_diff_slope.d2 - point0.y.d2 + point1.y.d2 } range_check_ptr₂ ∧ κ₁ + κ₂ + κ₃ + 21 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr₂ ∧ ρ_slope = slope -- You may change anything in this definition except the name and arguments. def spec_compute_slope (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_slope : BigInt3 F) : Prop := ∀ ix0 iy0 ix1 iy1 : bigint3, ix0.bounded (3 * BASE - 1) → iy0.bounded (3 * BASE - 1) → ix1.bounded (3 * BASE - 1) → iy1.bounded (3 * BASE - 1) → point0.x = ix0.toBigInt3 → point0.y = iy0.toBigInt3 → point1.x = ix1.toBigInt3 → point1.y = iy1.toBigInt3 → ∃ is : bigint3, is.bounded (3 * (BASE - 1)) ∧ ρ_slope = is.toBigInt3 ∧ (ix0.val - ix1.val) * is.val ≡ (iy0.val - iy1.val) [ZMOD SECP_PRIME] /- compute_slope soundness theorem -/ -- Do not change the statement of this theorem. You may change the proof. theorem sound_compute_slope {mem : F → F} (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_slope : BigInt3 F) (h_auto : auto_spec_compute_slope mem κ range_check_ptr point0 point1 ρ_range_check_ptr ρ_slope) : spec_compute_slope mem κ range_check_ptr point0 point1 ρ_range_check_ptr ρ_slope := begin rcases h_auto with ⟨_, _, slope, valid_slope, x_diff, x_diff_eq, _, x_diff_slope, h_x_diff_slope, _, _, vz, _, _, ret1eq⟩, rcases nondet_bigint3_corr valid_slope with ⟨is, slope_eq, isbdd⟩, intros ix0 iy0 ix1 iy1 ix0bdd iy0bdd ix1bdd iy1bdd pt0xeq pt0yeq pt1xeq pt1yeq, set ix_diff := ix0.sub ix1 with ix_diff_eq, have x_diff_eq' : x_diff = ix_diff.toBigInt3, { rw [ix_diff_eq, x_diff_eq, bigint3.toBigInt3_sub, BigInt3.sub, pt0xeq, pt1xeq] }, have x_diff_slope_eq := h_x_diff_slope _ _ x_diff_eq' slope_eq, refine ⟨_, isbdd, ret1eq.trans slope_eq, _⟩, set diff : bigint3 := (ix_diff.mul is).sub (iy0.sub iy1) with diff_eq, have diff_bdd : diff.bounded (((3 * BASE - 1) + (3 * BASE - 1))^2 * (8 * SECP_REM + 1) + ((3 * BASE - 1) + (3 * BASE - 1))), { rw [diff_eq], apply bigint3.bounded_sub, apply bigint3.bounded_mul, apply bigint3.bounded_sub ix0bdd ix1bdd, apply bigint3.bounded_of_bounded_of_le isbdd, unfold BASE, simp_int_casts, norm_num1, apply bigint3.bounded_sub iy0bdd iy1bdd }, have : diff.val % SECP_PRIME = 0, { apply vz, { simp only [diff_eq, x_diff_slope_eq, ix_diff_eq, pt0xeq, pt1xeq, pt0yeq, pt1yeq], dsimp [bigint3.toUnreducedBigInt3, bigint3.toBigInt3, bigint3.mul, bigint3.sub], simp [←sub_add] }, apply bigint3.bounded_of_bounded_of_le diff_bdd, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 }, symmetry, rw [int.modeq_iff_dvd, int.dvd_iff_mod_eq_zero, ←this, diff_eq, bigint3.sub_val, bigint3.sub_val], apply int.modeq.sub, apply int.modeq.symm, apply int.modeq.trans, apply bigint3.mul_val, apply int.modeq.mul_right, rw [ix_diff_eq, bigint3.sub_val], apply int.modeq.refl end /- -- Function: ec_double -/ /- ec_double autogenerated specification -/ -- Do not change this definition. def auto_spec_ec_double_block5 (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ∃ (κ₁ : ℕ) (range_check_ptr₁ : F) (slope : BigInt3 F), spec_compute_doubling_slope mem κ₁ range_check_ptr point range_check_ptr₁ slope ∧ ∃ (κ₂ : ℕ) (slope_sqr : UnreducedBigInt3 F), spec_unreduced_sqr mem κ₂ slope slope_sqr ∧ ∃ (κ₃ : ℕ) (range_check_ptr₂ : F) (new_x : BigInt3 F), spec_nondet_bigint3 mem κ₃ range_check_ptr₁ range_check_ptr₂ new_x ∧ ∃ (κ₄ : ℕ) (range_check_ptr₃ : F) (new_y : BigInt3 F), spec_nondet_bigint3 mem κ₄ range_check_ptr₂ range_check_ptr₃ new_y ∧ ∃ (κ₅ : ℕ) (range_check_ptr₄ : F), spec_verify_zero mem κ₅ range_check_ptr₃ { d0 := slope_sqr.d0 - new_x.d0 - 2 * point.x.d0, d1 := slope_sqr.d1 - new_x.d1 - 2 * point.x.d1, d2 := slope_sqr.d2 - new_x.d2 - 2 * point.x.d2 } range_check_ptr₄ ∧ ∃ (κ₆ : ℕ) (x_diff_slope : UnreducedBigInt3 F), spec_unreduced_mul mem κ₆ { d0 := point.x.d0 - new_x.d0, d1 := point.x.d1 - new_x.d1, d2 := point.x.d2 - new_x.d2 } slope x_diff_slope ∧ ∃ (κ₇ : ℕ) (range_check_ptr₅ : F), spec_verify_zero mem κ₇ range_check_ptr₄ { d0 := x_diff_slope.d0 - point.y.d0 - new_y.d0, d1 := x_diff_slope.d1 - point.y.d1 - new_y.d1, d2 := x_diff_slope.d2 - point.y.d2 - new_y.d2 } range_check_ptr₅ ∧ κ₁ + κ₂ + κ₃ + κ₄ + κ₅ + κ₆ + κ₇ + 49 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr₅ ∧ ρ_res = { x := new_x, y := new_y } def auto_spec_ec_double (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ((point.x.d0 = 0 ∧ ((point.x.d1 = 0 ∧ ((point.x.d2 = 0 ∧ 11 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr ∧ ρ_res = point) ∨ (point.x.d2 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_ec_double_block5 mem κ₁ range_check_ptr point ρ_range_check_ptr ρ_res ∧ κ₁ + 3 ≤ κ))) ∨ (point.x.d1 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_ec_double_block5 mem κ₁ range_check_ptr point ρ_range_check_ptr ρ_res ∧ κ₁ + 2 ≤ κ))) ∨ (point.x.d0 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_ec_double_block5 mem κ₁ range_check_ptr point ρ_range_check_ptr ρ_res ∧ κ₁ + 1 ≤ κ)) -- Added manually theorem auto_spec_ec_double_better {mem : F → F} {κ : ℕ}{range_check_ptr : F} {point : EcPoint F} {ρ_range_check_ptr : F} {ρ_res : EcPoint F} (h : auto_spec_ec_double mem κ range_check_ptr point ρ_range_check_ptr ρ_res ) : (point.x.d0 = 0 ∧ point.x.d1 = 0 ∧ point.x.d2 = 0 ∧ ρ_range_check_ptr = range_check_ptr ∧ ρ_res = point) ∨ ((point.x.d2 ≠ 0 ∨ point.x.d1 ≠ 0 ∨ point.x.d0 ≠ 0) ∧ ∃ (κ₁ : ℕ), auto_spec_ec_double_block5 mem κ₁ range_check_ptr point ρ_range_check_ptr ρ_res) := begin rcases h with (⟨ptx0z, (⟨ptx1z, ⟨ptx2z, h2⟩ | ⟨ptx2nz, ⟨h31, h32, _⟩⟩⟩ | ⟨ptx1nz, ⟨h41, h42, _⟩⟩)⟩ | ⟨ptx0nz, ⟨h51, h52, _⟩⟩), { left, use [ptx0z, ptx1z, ptx2z, h2.2] }, { right, split, left, assumption, exact ⟨h31, h32⟩ }, { right, split, right, left, assumption, exact ⟨h41, h42⟩ }, right, split, right, right, assumption, exact ⟨h51, h52⟩, end -- You may change anything in this definition except the name and arguments. def spec_ec_double (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := (point.x = ⟨0, 0, 0⟩ ∧ ρ_res = point) ∨ (point.x ≠ ⟨0, 0, 0⟩ ∧ ∀ ix iy : bigint3, ix.bounded (3 * BASE - 1) → iy.bounded (3 * BASE - 1) → point.x = ix.toBigInt3 → point.y = iy.toBigInt3 → ∃ is inew_x inew_y : bigint3, is.bounded (3 * (BASE - 1)) ∧ inew_x.bounded (3 * (BASE - 1)) ∧ inew_y.bounded (3 * (↑BASE - 1)) ∧ ρ_res = { x := inew_x.toBigInt3, y := inew_y.toBigInt3 } ∧ 3 * ix.val^2 ≡ 2 * iy.val * is.val [ZMOD SECP_PRIME] ∧ inew_x.val ≡ is.val^2 - 2 * ix.val [ZMOD SECP_PRIME] ∧ inew_y.val ≡ (ix.val - inew_x.val) * is.val - iy.val [ZMOD SECP_PRIME]) /- ec_double soundness theorem -/ -- Do not change the statement of this theorem. You may change the proof. theorem sound_ec_double {mem : F → F} (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) (h_auto : auto_spec_ec_double mem κ range_check_ptr point ρ_range_check_ptr ρ_res) : spec_ec_double mem κ range_check_ptr point ρ_range_check_ptr ρ_res := begin rcases auto_spec_ec_double_better h_auto with ⟨ptx0z, ptx1z, ptx2z, _, reseq⟩ | ⟨nz, _, main_case⟩, { left, simp [BigInt3.ext_iff, ptx0z, ptx1z, ptx2z, reseq] }, rcases main_case with ⟨_, _, slope, h_doubling_slope, _, islope_sqr, h_slope_square, _, _, new_x, vv_new_x, _, _, new_y, vv_new_y, _, _, vz, _, x_diff_slope, h_x_diff_slope, _, _, vz', _, _, ret1_eq⟩, right, split, { simp [BigInt3.ext_iff], tauto }, intros ix iy ixbdd iybdd ptxeq ptyeq, rcases h_doubling_slope ix iy ixbdd iybdd ptxeq ptyeq with ⟨is, isbdd, slope_eq, slope_congr⟩, have islope_sqr_eq := h_slope_square _ slope_eq, rcases nondet_bigint3_corr vv_new_x with ⟨inew_x, inew_x_eq, inew_x_bdd⟩, rcases nondet_bigint3_corr vv_new_y with ⟨inew_y, inew_y_eq, inew_y_bdd⟩, set diff1 := ((is.mul is).sub inew_x).sub (ix.cmul 2) with diff1_eq, have diff1_bdd : diff1.bounded ((3 * (BASE - 1))^2 * (8 * SECP_REM + 1) + 3 * (BASE - 1) + 2 * (3 * BASE - 1)), { rw [diff1_eq], apply bigint3.bounded_sub, apply bigint3.bounded_sub _ inew_x_bdd, apply bigint3.bounded_mul isbdd isbdd, apply bigint3.bounded_cmul ixbdd }, have diff1_equiv : diff1.val % SECP_PRIME = 0, { apply vz, { simp only [diff1_eq, islope_sqr_eq, ptxeq, inew_x_eq], dsimp [bigint3.toUnreducedBigInt3, bigint3.toBigInt3, bigint3.mul, bigint3.sub, bigint3.cmul, bigint3.sqr], simp only [int.cast_sub, int.cast_mul 2], simp_int_casts, split, refl, split, refl, refl }, apply bigint3.bounded_of_bounded_of_le diff1_bdd, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 }, have : (ix.sub inew_x).toBigInt3 = { d0 := point.x.d0 - new_x.d0, d1 := point.x.d1 - new_x.d1, d2 := point.x.d2 - new_x.d2 }, { rw [bigint3.toBigInt3_sub, ←ptxeq, ←inew_x_eq], refl }, have x_diff_slope_eq := h_x_diff_slope _ _ this.symm slope_eq, set diff2 := (((ix.sub inew_x).mul is).sub iy).sub inew_y with diff2_eq, have diff2_bdd : diff2.bounded (((3 * BASE - 1) + (3 * (BASE - 1)))^2 * (8 * SECP_REM + 1) + (3 * BASE - 1) + 3 * (BASE - 1)), { rw [diff2_eq], apply bigint3.bounded_sub _ inew_y_bdd, apply bigint3.bounded_sub _ iybdd, apply bigint3.bounded_mul, apply bigint3.bounded_sub ixbdd inew_x_bdd, apply bigint3.bounded_of_bounded_of_le isbdd, apply le_add_of_nonneg_left, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 }, have diff2_equiv : diff2.val % SECP_PRIME = 0, { apply vz', { simp only [diff2_eq, x_diff_slope_eq, inew_y_eq, bigint3.toBigInt3, bigint3.toUnreducedBigInt3, bigint3.mul, bigint3.sub, ptyeq, int.cast_sub], split, refl, split, refl, split }, apply bigint3.bounded_of_bounded_of_le diff2_bdd, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 }, use [is, inew_x, inew_y, isbdd, inew_x_bdd, inew_y_bdd], split, rw [ret1_eq, inew_x_eq, inew_y_eq], use slope_congr, split, { rw [int.modeq_iff_dvd, int.dvd_iff_mod_eq_zero, ←diff1_equiv, diff1_eq, bigint3.sub_val, bigint3.sub_val, bigint3.cmul_val, sub_sub, add_comm, ←sub_sub, pow_two], apply int.modeq.sub_right, apply int.modeq.sub_right, symmetry, apply bigint3.mul_val }, rw [int.modeq_iff_dvd, int.dvd_iff_mod_eq_zero, ←diff2_equiv, diff2_eq, bigint3.sub_val, bigint3.sub_val], apply int.modeq.sub_right, apply int.modeq.sub_right, symmetry, transitivity, apply bigint3.mul_val, rw [bigint3.sub_val] end /- Better specification -/ def spec_ec_double' ( pt : EcPoint F ) ( ret1 : EcPoint F ) (secpF : Type) [secp_field secpF] : Prop := ∀ h : BddECPointData secpF pt, ∃ hret : BddECPointData secpF ret1, hret.toECPoint = 2 • h.toECPoint theorem spec_ec_double'_of_spec_ec_double {mem : F → F} {κ : ℕ} {range_check_ptr : F} {pt : EcPoint F} {ret0 : F} {ret1 : EcPoint F} (h : spec_ec_double mem κ range_check_ptr pt ret0 ret1) (secpF : Type) [secp_field secpF] : spec_ec_double' pt ret1 secpF := begin intros hpt, rcases h with ⟨ptx0, reteq⟩ | ⟨ptxnz, h⟩, { rw reteq, use hpt, rw [hpt.toECPoint_eq_zero_iff.mpr ptx0, smul_zero] }, rcases h hpt.ix hpt.iy hpt.ixbdd hpt.iybdd hpt.ptxeq hpt.ptyeq with ⟨is, inew_x, inew_y, is_bdd, inew_x_bdd, inew_y_bdd, ret1eq, mod1eq, mod2eq, mod3eq⟩, have onec_pt := hpt.onEC' ptxnz, have hptynez : (hpt.iy.val : secpF) ≠ 0 := secp_field.y_ne_zero_of_on_ec onec_pt, have eq1 : 3 * (hpt.ix.val : secpF)^2 = 2 * hpt.iy.val * is.val, { norm_cast, rw @eq_iff_modeq_int secpF _ SECP_PRIME, apply mod1eq }, have eq2 : (inew_x.val : secpF) = is.val ^ 2 - 2 * hpt.ix.val, { norm_cast, rw @eq_iff_modeq_int secpF _ SECP_PRIME, apply mod2eq }, have eq3: (inew_y.val : secpF) = (hpt.ix.val - inew_x.val) * is.val - hpt.iy.val, { norm_cast, rw @eq_iff_modeq_int secpF _ SECP_PRIME, apply mod3eq }, have eq1a : (is.val : secpF) = 3 * (hpt.ix.val : secpF)^2 / (2 * hpt.iy.val), { field_simp [ec_field.two_ne_zero], rw [mul_comm, eq1] }, have ecdoubleeq : ec_double ((hpt.ix.val : secpF), hpt.iy.val) = (inew_x.val, inew_y.val), { simp [ec_double, ec_double_slope], split, rw [eq2, eq1a, div_pow], rw [eq3, eq1a], congr, rw [eq2, eq1a, div_pow] }, have onec_new: on_ec (↑(inew_x.val), ↑(inew_y.val)), { have := @on_ec_ec_double secpF _ (↑(hpt.ix.val), ↑(hpt.iy.val)) onec_pt hptynez, rw ecdoubleeq at this, exact this }, have hhret: ¬ (inew_x.i0 = 0 ∧ inew_x.i1 = 0 ∧ inew_x.i2 = 0), { contrapose! onec_new, rw [on_ec], dsimp, conv { congr, to_rhs, simp [bigint3.val, onec_new.1, onec_new.2.1, onec_new.2.2] }, apply secp_field.seven_not_square }, let hret : BddECPointData secpF ret1 := { ix := inew_x, iy := inew_y, ixbdd := by apply bigint3.bounded_of_bounded_of_le inew_x_bdd; norm_num [BASE], iybdd := by apply bigint3.bounded_of_bounded_of_le inew_y_bdd; norm_num [BASE], ptxeq := by { rw ret1eq }, ptyeq := by { rw ret1eq }, onEC := or.inr onec_new }, use hret, have : ret1.x ≠ ⟨0, 0, 0⟩, { rw [ret1eq], dsimp, have h' := secp_field.x_ne_zero_of_on_ec onec_new, contrapose! h', have : inew_x = ⟨0, 0, 0⟩ := toBigInt3_eq_zero_of_bounded_3BASE h' (bigint3.bounded_of_bounded_of_le inew_x_bdd bound_slack), simp [this, bigint3.val] }, dsimp [BddECPointData.toECPoint], simp [dif_neg ptxnz, dif_neg this], symmetry, apply double_Affine _ _ ecdoubleeq end /- -- Function: fast_ec_add -/ /- fast_ec_add autogenerated specification -/ -- Do not change this definition. def auto_spec_fast_ec_add_block9 (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ∃ (κ₁ : ℕ) (range_check_ptr₁ : F) (slope : BigInt3 F), spec_compute_slope mem κ₁ range_check_ptr point0 point1 range_check_ptr₁ slope ∧ ∃ (κ₂ : ℕ) (slope_sqr : UnreducedBigInt3 F), spec_unreduced_sqr mem κ₂ slope slope_sqr ∧ ∃ (κ₃ : ℕ) (range_check_ptr₂ : F) (new_x : BigInt3 F), spec_nondet_bigint3 mem κ₃ range_check_ptr₁ range_check_ptr₂ new_x ∧ ∃ (κ₄ : ℕ) (range_check_ptr₃ : F) (new_y : BigInt3 F), spec_nondet_bigint3 mem κ₄ range_check_ptr₂ range_check_ptr₃ new_y ∧ ∃ (κ₅ : ℕ) (range_check_ptr₄ : F), spec_verify_zero mem κ₅ range_check_ptr₃ { d0 := slope_sqr.d0 - new_x.d0 - point0.x.d0 - point1.x.d0, d1 := slope_sqr.d1 - new_x.d1 - point0.x.d1 - point1.x.d1, d2 := slope_sqr.d2 - new_x.d2 - point0.x.d2 - point1.x.d2 } range_check_ptr₄ ∧ ∃ (κ₆ : ℕ) (x_diff_slope : UnreducedBigInt3 F), spec_unreduced_mul mem κ₆ { d0 := point0.x.d0 - new_x.d0, d1 := point0.x.d1 - new_x.d1, d2 := point0.x.d2 - new_x.d2 } slope x_diff_slope ∧ ∃ (κ₇ : ℕ) (range_check_ptr₅ : F), spec_verify_zero mem κ₇ range_check_ptr₄ { d0 := x_diff_slope.d0 - point0.y.d0 - new_y.d0, d1 := x_diff_slope.d1 - point0.y.d1 - new_y.d1, d2 := x_diff_slope.d2 - point0.y.d2 - new_y.d2 } range_check_ptr₅ ∧ κ₁ + κ₂ + κ₃ + κ₄ + κ₅ + κ₆ + κ₇ + 52 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr₅ ∧ ρ_res = { x := new_x, y := new_y } def auto_spec_fast_ec_add_block5 (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ((point1.x.d0 = 0 ∧ ((point1.x.d1 = 0 ∧ ((point1.x.d2 = 0 ∧ 11 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr ∧ ρ_res = point0) ∨ (point1.x.d2 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_fast_ec_add_block9 mem κ₁ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res ∧ κ₁ + 3 ≤ κ))) ∨ (point1.x.d1 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_fast_ec_add_block9 mem κ₁ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res ∧ κ₁ + 2 ≤ κ))) ∨ (point1.x.d0 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_fast_ec_add_block9 mem κ₁ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res ∧ κ₁ + 1 ≤ κ)) def auto_spec_fast_ec_add (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ((point0.x.d0 = 0 ∧ ((point0.x.d1 = 0 ∧ ((point0.x.d2 = 0 ∧ 11 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr ∧ ρ_res = point1) ∨ (point0.x.d2 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_fast_ec_add_block5 mem κ₁ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res ∧ κ₁ + 3 ≤ κ))) ∨ (point0.x.d1 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_fast_ec_add_block5 mem κ₁ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res ∧ κ₁ + 2 ≤ κ))) ∨ (point0.x.d0 ≠ 0 ∧ ∃ (κ₁ : ℕ), auto_spec_fast_ec_add_block5 mem κ₁ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res ∧ κ₁ + 1 ≤ κ)) -- You may change anything in this definition except the name and arguments. def spec_fast_ec_add (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ∀ ix0 iy0 ix1 iy1 : bigint3, ix0.bounded (3 * BASE - 1) → iy0.bounded (3 * BASE - 1) → ix1.bounded (3 * BASE - 1) → iy1.bounded (3 * BASE - 1) → point0.x = ix0.toBigInt3 → point0.y = iy0.toBigInt3 → point1.x = ix1.toBigInt3 → point1.y = iy1.toBigInt3 → (point0.x.d0 = 0 ∧ point0.x.d1 = 0 ∧ point0.x.d2 = 0 ∧ ρ_res = point1) ∨ (point1.x.d0 = 0 ∧ point1.x.d1 = 0 ∧ point1.x.d2 = 0 ∧ ρ_res = point0) ∨ ¬ (point0.x.d0 = 0 ∧ point0.x.d1 = 0 ∧ point0.x.d2 = 0) ∧ ¬ (point1.x.d0 = 0 ∧ point1.x.d1 = 0 ∧ point1.x.d2 = 0) ∧ ∃ is inew_x inew_y : bigint3, is.bounded (3 * (BASE - 1)) ∧ inew_x.bounded (3 * (BASE - 1)) ∧ inew_y.bounded (3 * (BASE - 1)) ∧ ρ_res = { x := inew_x.toBigInt3, y := inew_y.toBigInt3 } ∧ (ix0.val - ix1.val) * is.val ≡ (iy0.val - iy1.val) [ZMOD SECP_PRIME] ∧ inew_x.val ≡ is.val^2 - ix0.val - ix1.val [ZMOD SECP_PRIME] ∧ inew_y.val ≡ (ix0.val - inew_x.val) * is.val - iy0.val [ZMOD SECP_PRIME] /- fast_ec_add soundness theorem -/ theorem fast_ec_add_block5_spec_better {mem : F → F} {κ : ℕ}{range_check_ptr : F} {pt0 pt1 : EcPoint F} {ret0 : F} {ret1 : EcPoint F} (h_auto : auto_spec_fast_ec_add_block5 mem κ range_check_ptr pt0 pt1 ret0 ret1) : (pt1.x.d0 = 0 ∧ pt1.x.d1 = 0 ∧ pt1.x.d2 = 0 ∧ ret0 = range_check_ptr ∧ ret1 = pt0) ∨ (¬ (pt1.x.d0 = 0 ∧ pt1.x.d1 = 0 ∧ pt1.x.d2 = 0) ∧ ∃ κ₁, auto_spec_fast_ec_add_block9 mem κ₁ range_check_ptr pt0 pt1 ret0 ret1) := begin rcases h_auto with ⟨pt1x0z, ⟨pt1x1z, ⟨pt1x2z, ⟨_, ret0, ret1⟩⟩ | ⟨pt1x2nz, ⟨κ₁, hblock9⟩⟩⟩ | ⟨pt1x1nz, ⟨κ₁, hblock9⟩⟩⟩ | ⟨pt1x0nz, ⟨κ₁, hblock9⟩⟩, { left, use [pt1x0z, pt1x1z, pt1x2z, ret0, ret1] }, { right, split, intro h, apply pt1x2nz h.2.2, exact ⟨κ₁, hblock9.1⟩ }, { right, split, intro h, apply pt1x1nz h.2.1, exact ⟨κ₁, hblock9.1⟩ }, { right, split, intro h, apply pt1x0nz h.1, exact ⟨κ₁, hblock9.1⟩ } end theorem ec_add_mainb_spec_better {mem : F → F} {κ : ℕ} {range_check_ptr : F} {pt0 pt1 : EcPoint F} {ret0 : F} {ret1 : EcPoint F} (h_auto : auto_spec_fast_ec_add mem κ range_check_ptr pt0 pt1 ret0 ret1) : (pt0.x.d0 = 0 ∧ pt0.x.d1 = 0 ∧ pt0.x.d2 = 0 ∧ ret0 = range_check_ptr ∧ ret1 = pt1) ∨ (pt1.x.d0 = 0 ∧ pt1.x.d1 = 0 ∧ pt1.x.d2 = 0 ∧ ret0 = range_check_ptr ∧ ret1 = pt0) ∨ (¬(pt0.x.d0 = 0 ∧ pt0.x.d1 = 0 ∧ pt0.x.d2 = 0) ∧ ¬ (pt1.x.d0 = 0 ∧ pt1.x.d1 = 0 ∧ pt1.x.d2 = 0) ∧ ∃ κ₁, auto_spec_fast_ec_add_block9 mem κ₁ range_check_ptr pt0 pt1 ret0 ret1) := begin rcases h_auto with ⟨pt1x0z, ⟨pt1x1z, ⟨pt1x2z, ⟨_, ret0, ret1⟩⟩ | ⟨pt1x2nz, κ₁, hblock9⟩⟩ | ⟨pt1x1nz, κ₁, hblock9⟩⟩ | ⟨pt1x0nz, κ₁, hblock9⟩, { left, use [pt1x0z, pt1x1z, pt1x2z, ret0, ret1] }, { right, cases fast_ec_add_block5_spec_better hblock9.1 with h' h', { left, exact h' }, right, split, { intro h, exact pt1x2nz h.2.2 }, exact h' }, { right, cases fast_ec_add_block5_spec_better hblock9.1 with h' h', { left, exact h' }, right, split, { intro h, exact pt1x1nz h.2.1 }, exact h' }, { right, cases fast_ec_add_block5_spec_better hblock9.1 with h' h', { left, exact h' }, right, split, { intro h, exact pt1x0nz h.1 }, exact h' }, end -- Do not change the statement of this theorem. You may change the proof. theorem sound_fast_ec_add {mem : F → F} (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) (h_auto : auto_spec_fast_ec_add mem κ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res) : spec_fast_ec_add mem κ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res := begin intros ix0 iy0 ix1 iy1 ix0bdd iy0bdd ix1bdd iy1bdd pt0xeq pt0yeq pt1xeq pt1yeq, rcases ec_add_mainb_spec_better h_auto with ⟨pt0x0z, pt0x1z, pt0x2z, _, ret1eq⟩ | ⟨pt1x0z, pt1x1z, pt1x2z, _, ret1eq⟩ | ⟨pt0nz, pt1nz, _, _, _, slope, h_compute_slope, _, islope_sqr, h_slope_sqr, _, _, new_x, vv_new_x, _, _, new_y, vv_new_y, _, _, vz, _, x_diff_slope, h_x_diff_slope, _, _, vz', _, _, ret1_eq⟩, { left, use [pt0x0z, pt0x1z, pt0x2z, ret1eq] }, { right, left, use [pt1x0z, pt1x1z, pt1x2z, ret1eq] }, rcases h_compute_slope ix0 iy0 ix1 iy1 ix0bdd iy0bdd ix1bdd iy1bdd pt0xeq pt0yeq pt1xeq pt1yeq with ⟨is, isbdd, slope_eq, slope_congr⟩, have islope_sqr_eq := h_slope_sqr _ slope_eq, rcases nondet_bigint3_corr vv_new_x with ⟨inew_x, inew_x_eq, inew_x_bdd⟩, rcases nondet_bigint3_corr vv_new_y with ⟨inew_y, inew_y_eq, inew_y_bdd⟩, set diff1 := (((is.mul is).sub inew_x).sub ix0).sub ix1 with diff1_eq, have diff1_bdd : diff1.bounded ((3 * (BASE - 1))^2 * (8 * SECP_REM + 1) + 3 * (BASE - 1) + (3 * BASE - 1) + (3 * BASE - 1)), { rw [diff1_eq], apply bigint3.bounded_sub _ ix1bdd, apply bigint3.bounded_sub _ ix0bdd, apply bigint3.bounded_sub _ inew_x_bdd, apply bigint3.bounded_mul isbdd isbdd }, have diff1_equiv : diff1.val % SECP_PRIME = 0, { apply vz, { simp only [diff1_eq, islope_sqr_eq, pt0xeq, pt1xeq, inew_x_eq], dsimp [bigint3.toBigInt3, bigint3.toUnreducedBigInt3, bigint3.mul, bigint3.sub, bigint3.cmul, bigint3.sqr], simp only [int.cast_sub, int.cast_mul 2], simp_int_casts, split, refl, split, refl, refl }, apply bigint3.bounded_of_bounded_of_le diff1_bdd, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 }, have : (ix0.sub inew_x).toBigInt3 = { d0 := point0.x.d0 - new_x.d0, d1 := point0.x.d1 - new_x.d1, d2 := point0.x.d2 - new_x.d2 }, { rw [bigint3.toBigInt3_sub, ←pt0xeq, ←inew_x_eq], refl }, have x_diff_slope_eq := h_x_diff_slope _ _ this.symm slope_eq, set diff2 := (((ix0.sub inew_x).mul is).sub iy0).sub inew_y with diff2_eq, have diff2_bdd : diff2.bounded (((3 * BASE - 1) + (3 * (BASE - 1)))^2 * (8 * SECP_REM + 1) + (3 * BASE - 1) + 3 * (BASE - 1)), { rw [diff2_eq], apply bigint3.bounded_sub _ inew_y_bdd, apply bigint3.bounded_sub _ iy0bdd, apply bigint3.bounded_mul, apply bigint3.bounded_sub ix0bdd inew_x_bdd, apply bigint3.bounded_of_bounded_of_le isbdd, apply le_add_of_nonneg_left, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 }, have diff2_equiv : diff2.val % SECP_PRIME = 0, { apply vz', { simp only [diff2_eq, x_diff_slope_eq, inew_y_eq, bigint3.toBigInt3, bigint3.toUnreducedBigInt3, bigint3.mul, bigint3.sub, pt0yeq, int.cast_sub], split, refl, split, refl, split }, apply bigint3.bounded_of_bounded_of_le diff2_bdd, dsimp only [BASE, SECP_REM], simp_int_casts, norm_num1 }, right, right, use [pt0nz, pt1nz, is, inew_x, inew_y, isbdd, inew_x_bdd, inew_y_bdd], split, rw [ret1_eq, inew_x_eq, inew_y_eq], use slope_congr, split, { rw [int.modeq_iff_dvd, int.dvd_iff_mod_eq_zero, ←diff1_equiv, diff1_eq, bigint3.sub_val, bigint3.sub_val, bigint3.sub_val, sub_sub, sub_sub, pow_two, ←add_assoc, add_comm _ inew_x.val, sub_sub, ←sub_sub], apply int.modeq.sub_right, apply int.modeq.sub_right, symmetry, apply bigint3.mul_val }, rw [int.modeq_iff_dvd, int.dvd_iff_mod_eq_zero, ←diff2_equiv, diff2_eq, bigint3.sub_val, bigint3.sub_val], apply int.modeq.sub_right, apply int.modeq.sub_right, symmetry, transitivity, apply bigint3.mul_val, rw [bigint3.sub_val] end /- Better specification of fast_ec_add -/ def spec_fast_ec_add' ( pt0 pt1 : EcPoint F ) ( ret1 : EcPoint F ) (secpF : Type) [secp_field secpF] : Prop := ∀ h0 : BddECPointData secpF pt0, ∀ h1 : BddECPointData secpF pt1, (↑(h0.ix.val) : secpF) ≠ ↑(h1.ix.val) → ∃ hret : BddECPointData secpF ret1, hret.toECPoint = h0.toECPoint + h1.toECPoint theorem spec_fast_ec_add'_of_spec_ec_add {mem : F → F} {κ : ℕ} {range_check_ptr : F} {pt0 pt1 : EcPoint F} {ret0 : F} {ret1 : EcPoint F} (h : spec_fast_ec_add mem κ range_check_ptr pt0 pt1 ret0 ret1) (secpF : Type) [secp_field secpF] : spec_fast_ec_add' pt0 pt1 ret1 secpF := begin intros h0 h1 hne, rcases h h0.ix h0.iy h1.ix h1.iy h0.ixbdd h0.iybdd h1.ixbdd h1.iybdd h0.ptxeq h0.ptyeq h1.ptxeq h1.ptyeq with h' | h' | h', { rcases h' with ⟨pt0x0eq, pt0x1eq, pt0x2eq, rfl⟩, have pt0xz : pt0.x = ⟨0, 0, 0⟩, { simp [BigInt3.ext_iff, pt0x0eq, pt0x1eq, pt0x2eq] }, use h1, have pt0xeq := h0.ptxeq, simp [BigInt3.ext_iff, bigint3.toBigInt3] at pt0xeq, have ix0i0z: h0.ix.i0 = 0, { apply @PRIME.int_coe_inj F, rw [←pt0xeq.1, pt0x0eq, int.cast_zero], simp, apply lt_of_le_of_lt h0.ixbdd.1, apply bound_lt_prime }, have ix0i1z: h0.ix.i1 = 0, { apply @PRIME.int_coe_inj F, rw [←pt0xeq.2.1, pt0x1eq, int.cast_zero], simp, apply lt_of_le_of_lt h0.ixbdd.2.1, apply bound_lt_prime }, have ix0i2z: h0.ix.i2 = 0, { apply @PRIME.int_coe_inj F, rw [←pt0xeq.2.2, pt0x2eq, int.cast_zero], simp, apply lt_of_le_of_lt h0.ixbdd.2.2, apply bound_lt_prime }, simp [BddECPointData.toECPoint, pt0xz], refl }, { rcases h' with ⟨pt1x0eq, pt1x1eq, pt1x2eq, rfl⟩, have pt1xz : pt1.x = ⟨0, 0, 0⟩, { simp [BigInt3.ext_iff, pt1x0eq, pt1x1eq, pt1x2eq] }, use h0, have pt1xeq := h1.ptxeq, simp [BigInt3.ext_iff, bigint3.toBigInt3] at pt1xeq, have ix0i0z: h1.ix.i0 = 0, { apply @PRIME.int_coe_inj F, rw [←pt1xeq.1, pt1x0eq, int.cast_zero], simp, apply lt_of_le_of_lt h1.ixbdd.1, apply bound_lt_prime }, have ix0i1z: h1.ix.i1 = 0, { apply @PRIME.int_coe_inj F, rw [←pt1xeq.2.1, pt1x1eq, int.cast_zero], simp, apply lt_of_le_of_lt h1.ixbdd.2.1, apply bound_lt_prime }, have ix0i2z: h1.ix.i2 = 0, { apply @PRIME.int_coe_inj F, rw [←pt1xeq.2.2, pt1x2eq, int.cast_zero], simp, apply lt_of_le_of_lt h1.ixbdd.2.2, apply bound_lt_prime }, simp [BddECPointData.toECPoint, pt1xz], refl }, rcases h' with ⟨pt0nz, pt1nz, is, inew_x, inew_y, is_bdd, inew_x_bdd, inew_y_bdd, ret1eq, mod1eq, mod2eq, mod3eq⟩, have eq1 : ((h0.ix.val : secpF) - h1.ix.val) * is.val = h0.iy.val - h1.iy.val, { norm_cast, rw @eq_iff_modeq_int secpF _ SECP_PRIME, apply mod1eq }, have eq2 : (inew_x.val : secpF) = is.val ^ 2 - h0.ix.val - h1.ix.val, { norm_cast, rw @eq_iff_modeq_int secpF _ SECP_PRIME, apply mod2eq }, have eq3: (inew_y.val : secpF) = (h0.ix.val - inew_x.val) * is.val - h0.iy.val, { norm_cast, rw @eq_iff_modeq_int secpF _ SECP_PRIME, apply mod3eq }, have nez : (h1.ix.val : secpF) - h0.ix.val ≠ 0, { contrapose! hne, symmetry, apply eq_of_sub_eq_zero hne }, have eq1a : (is.val : secpF) = (h1.iy.val - h0.iy.val) / (h1.ix.val - h0.ix.val), { field_simp [nez], rw [←neg_sub, mul_neg, mul_comm, eq1, neg_sub] }, have ecaddeq : ec_add ((h0.ix.val : secpF), h0.iy.val) ((h1.ix.val : secpF), h1.iy.val) = (inew_x.val, inew_y.val), { simp [ec_add, ec_add_slope], split, rw [eq2, eq1a, div_pow, sub_sub], rw [eq3], congr, rw [eq2, eq1a, div_pow, sub_sub], rw [eq1a] }, have pt0nz' : pt0.x ≠ ⟨0, 0, 0⟩, { rw [ne, BigInt3.ext_iff], exact pt0nz }, have pt1nz' : pt1.x ≠ ⟨0, 0, 0⟩, { rw [ne, BigInt3.ext_iff], exact pt1nz }, have onec_new: on_ec (↑(inew_x.val), ↑(inew_y.val)), { have := @on_ec_ec_add secpF _ (↑(h0.ix.val), ↑(h0.iy.val)) (↑(h1.ix.val), ↑(h1.iy.val)) (h0.onEC' pt0nz') (h1.onEC' pt1nz') hne, rw ecaddeq at this, exact this }, let hret : BddECPointData secpF ret1 := { ix := inew_x, iy := inew_y, ixbdd := by apply bigint3.bounded_of_bounded_of_le inew_x_bdd; norm_num [BASE], iybdd := by apply bigint3.bounded_of_bounded_of_le inew_y_bdd; norm_num [BASE], ptxeq := by { rw ret1eq }, ptyeq := by { rw ret1eq }, onEC := or.inr onec_new }, have hhret : ¬ (ret1.x = ⟨0, 0, 0⟩), { simp [ret1eq], intro h', apply secp_field.x_ne_zero_of_on_ec onec_new, suffices : inew_x = ⟨0, 0, 0⟩, { rw bigint3.ext_iff at this, simp [this, bigint3.val] }, apply toBigInt3_eq_zero_of_bounded_3BASE h', apply bigint3.bounded_of_bounded_of_le inew_x_bdd; norm_num [BASE] }, use hret, dsimp [BddECPointData.toECPoint], simp [dif_neg pt0nz', dif_neg pt1nz', dif_neg hhret], symmetry, apply Affine_add_Affine _ _ _ hne, rw [ecaddeq] end /- -- Function: ec_add -/ /- ec_add autogenerated specification -/ -- Do not change this definition. def auto_spec_ec_add (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ∃ x_diff : BigInt3 F, x_diff = { d0 := point0.x.d0 - point1.x.d0, d1 := point0.x.d1 - point1.x.d1, d2 := point0.x.d2 - point1.x.d2 } ∧ ∃ (κ₁ : ℕ) (range_check_ptr₁ same_x : F), spec_is_zero mem κ₁ range_check_ptr x_diff range_check_ptr₁ same_x ∧ ((same_x = 0 ∧ ∃ (κ₂ : ℕ), spec_fast_ec_add mem κ₂ range_check_ptr₁ point0 point1 ρ_range_check_ptr ρ_res ∧ κ₁ + κ₂ + 21 ≤ κ) ∨ (same_x ≠ 0 ∧ ∃ y_sum : BigInt3 F, y_sum = { d0 := point0.y.d0 + point1.y.d0, d1 := point0.y.d1 + point1.y.d1, d2 := point0.y.d2 + point1.y.d2 } ∧ ∃ (κ₂ : ℕ) (range_check_ptr₂ opposite_y : F), spec_is_zero mem κ₂ range_check_ptr₁ y_sum range_check_ptr₂ opposite_y ∧ ((opposite_y ≠ 0 ∧ ∃ ZERO_POINT : EcPoint F, ZERO_POINT = { x := { d0 := 0, d1 := 0, d2 := 0 }, y := { d0 := 0, d1 := 0, d2 := 0 } } ∧ κ₁ + κ₂ + 20 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr₂ ∧ ρ_res = ZERO_POINT) ∨ (opposite_y = 0 ∧ ∃ (κ₃ : ℕ), spec_ec_double mem κ₃ range_check_ptr₂ point0 ρ_range_check_ptr ρ_res ∧ κ₁ + κ₂ + κ₃ + 21 ≤ κ)))) -- You may change anything in this definition except the name and arguments. def spec_ec_add (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ∀ (secpF : Type) [secp_field secpF], by exactI ∀ h0 : BddECPointData secpF point0, ∀ h1 : BddECPointData secpF point1, ∃ hret : BddECPointData secpF ρ_res, hret.toECPoint = h0.toECPoint + h1.toECPoint /- ec_add soundness theorem -/ -- Do not change the statement of this theorem. You may change the proof. theorem sound_ec_add {mem : F → F} (κ : ℕ) (range_check_ptr : F) (point0 point1 : EcPoint F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) (h_auto : auto_spec_ec_add mem κ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res) : spec_ec_add mem κ range_check_ptr point0 point1 ρ_range_check_ptr ρ_res := begin intros secpF _, resetI, intros h0 h1, rcases h_auto with ⟨x_diff, x_diff_eq, _, _, same_x, h_x_diff, h'⟩, let ix_diff := h0.ix.sub h1.ix, have h2: x_diff = ix_diff.toBigInt3, { dsimp [ix_diff], rw [x_diff_eq, bigint3.toBigInt3_sub, ←h0.ptxeq, ←h1.ptxeq], refl }, have h3: ix_diff.bounded (2^107), { rw (show (2^107 : ℤ) = 2^106 + 2^106, by norm_num), apply bigint3.bounded_sub, apply bigint3.bounded_of_bounded_of_le h0.ixbdd, rw BASE, simp_int_casts, norm_num, apply bigint3.bounded_of_bounded_of_le h1.ixbdd, rw BASE, simp_int_casts, norm_num }, rcases h' with ⟨same_x_z, _, h'⟩ | ⟨same_x_nz, h'⟩, { have := h_x_diff _ h2 h3, have : ix_diff.val % ↑SECP_PRIME ≠ 0, { rcases this with ⟨_, rfl⟩ | ⟨_, _⟩, norm_num at same_x_z, assumption }, apply spec_fast_ec_add'_of_spec_ec_add h'.1, contrapose! this, dsimp [ix_diff], rw [bigint3.sub_val, ←int.modeq_iff_sub_mod_eq_zero, ←char_p.int_coe_eq_int_coe_iff secpF], exact this }, have := h_x_diff _ h2 h3, have : ix_diff.val % ↑SECP_PRIME = 0, { rcases this with ⟨_, rfl⟩ | ⟨_, _⟩, assumption, norm_num at same_x_nz }, have h0eqh1: (h0.ix.val : secpF) = h1.ix.val, { rw [bigint3.sub_val, ←int.modeq_iff_sub_mod_eq_zero, ←char_p.int_coe_eq_int_coe_iff secpF] at this, exact this }, have ptx0iff : point0.x = ⟨0, 0, 0⟩ ↔ point1.x = ⟨0, 0, 0⟩, { rw [h1.pt_zero_iff, ←h0eqh1, ←h0.pt_zero_iff] }, rcases h' with ⟨y_sum, y_sum_eq, _, _, opposite_y, h_opposite_y, h'⟩, let iy_sum := h0.iy.add h1.iy, have h2: y_sum = iy_sum.toBigInt3, { dsimp [iy_sum], rw [y_sum_eq, bigint3.toBigInt3_add, ←h0.ptyeq, ←h1.ptyeq], refl }, have h3: iy_sum.bounded (2^107), { rw (show (2^107 : ℤ) = 2^106 + 2^106, by norm_num), apply bigint3.bounded_add, apply bigint3.bounded_of_bounded_of_le h0.iybdd, rw BASE, simp_int_casts, norm_num, apply bigint3.bounded_of_bounded_of_le h1.iybdd, rw BASE, simp_int_casts, norm_num }, rcases h' with ⟨opposite_y_nz, h'⟩ | ⟨opposite_y_z, _, h'⟩, { rcases h' with ⟨_, rfl, _, _, rfl⟩, use BddECPointData.zero, rw BddECPointData.toECPoint_zero, by_cases hx0: point0.x = ⟨0, 0, 0⟩, { have hx1: point1.x = ⟨0, 0, 0⟩ := ptx0iff.mp hx0, rw [BddECPointData.toECPoint, dif_pos hx0], rw [BddECPointData.toECPoint, dif_pos hx1], apply (add_zero _).symm }, have hx1: point1.x ≠ ⟨0, 0, 0⟩, { rwa ptx0iff at hx0 }, rw [BddECPointData.toECPoint, dif_neg hx0], rw [BddECPointData.toECPoint, dif_neg hx1], symmetry, rw [← eq_neg_iff_add_eq_zero, ECPoint.neg_def, ECPoint.neg], dsimp, congr, exact h0eqh1, have := h_opposite_y _ h2 h3, have : iy_sum.val % ↑SECP_PRIME = 0, { rcases this with ⟨_, _⟩ | ⟨_, hh⟩, assumption, contradiction }, rw [bigint3.add_val, ←sub_neg_eq_add, ←int.modeq_iff_sub_mod_eq_zero, ←char_p.int_coe_eq_int_coe_iff secpF, int.cast_neg] at this, exact this }, have := h_opposite_y _ h2 h3, have h0iyneh1iy : iy_sum.val % ↑SECP_PRIME ≠ 0, { rcases this with ⟨_, rfl⟩ | ⟨_, _⟩, norm_num at opposite_y_z, assumption }, rw [ne, bigint3.add_val, ←sub_neg_eq_add, ←int.modeq_iff_sub_mod_eq_zero, ←char_p.int_coe_eq_int_coe_iff secpF, int.cast_neg] at h0iyneh1iy, have : h0.toECPoint = h1.toECPoint := BddECPointData.toECPoint_eq_of_eq_of_ne h0eqh1 h0iyneh1iy, have : h0.toECPoint + h1.toECPoint = 2 • h0.toECPoint, { rw [this, two_smul] }, rw this, exact spec_ec_double'_of_spec_ec_double h'.1 secpF h0 end -- You may change anything in this definition except the name and arguments. def spec_ec_mul_inner (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (scalar m ρ_range_check_ptr : F) (ρ_pow2 ρ_res : EcPoint F) : Prop := ∀ (secpF : Type) [hsecp : secp_field secpF], by exactI point.x ≠ ⟨0, 0, 0⟩ → ∀ hpt : BddECPointData secpF point, ∃ nn : ℕ, m = ↑nn ∧ nn < ring_char F ∧ (nn ≤ SECP_LOG2_BOUND → ∃ scalarn : ℕ, scalar = ↑scalarn ∧ scalarn < 2^nn ∧ ∃ hpow2 : BddECPointData secpF ρ_pow2, ρ_pow2.x ≠ ⟨0, 0, 0⟩ ∧ hpow2.toECPoint = 2^nn • hpt.toECPoint ∧ ∃ hres : BddECPointData secpF ρ_res, hres.toECPoint = scalarn • hpt.toECPoint) /- -- Function: ec_mul_inner -/ /- ec_mul_inner autogenerated specification -/ -- Do not change this definition. def auto_spec_ec_mul_inner (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (scalar m ρ_range_check_ptr : F) (ρ_pow2 ρ_res : EcPoint F) : Prop := ((m = 0 ∧ scalar = 0 ∧ ∃ ZERO_POINT : EcPoint F, ZERO_POINT = { x := { d0 := 0, d1 := 0, d2 := 0 }, y := { d0 := 0, d1 := 0, d2 := 0 } } ∧ 16 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr ∧ ρ_pow2 = point ∧ ρ_res = ZERO_POINT) ∨ (m ≠ 0 ∧ ∃ (κ₁ : ℕ) (range_check_ptr₁ : F) (double_point : EcPoint F), spec_ec_double mem κ₁ range_check_ptr point range_check_ptr₁ double_point ∧ ∃ anon_cond : F, ((anon_cond = 0 ∧ ∃ (κ₂ : ℕ), spec_ec_mul_inner mem κ₂ range_check_ptr₁ double_point (scalar / (2 : ℤ)) (m - 1) ρ_range_check_ptr ρ_pow2 ρ_res ∧ κ₁ + κ₂ + 22 ≤ κ) ∨ (anon_cond ≠ 0 ∧ ∃ (κ₂ : ℕ) (range_check_ptr₂ : F) (inner_pow2 inner_res : EcPoint F), spec_ec_mul_inner mem κ₂ range_check_ptr₁ double_point ((scalar - 1) / (2 : ℤ)) (m - 1) range_check_ptr₂ inner_pow2 inner_res ∧ ∃ (κ₃ : ℕ) (range_check_ptr₃ : F) (res : EcPoint F), spec_fast_ec_add mem κ₃ range_check_ptr₂ point inner_res range_check_ptr₃ res ∧ κ₁ + κ₂ + κ₃ + 56 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr₃ ∧ ρ_pow2 = inner_pow2 ∧ ρ_res = res)))) /- ec_mul_inner soundness theorem -/ lemma ec_mul_inner_aux {secpF : Type} [secp_field secpF] {pt0 pt1 : EcPoint F} (h0 : BddECPointData secpF pt0) (h1 : BddECPointData secpF pt1) (hpt0xnz : pt0.x ≠ ⟨0, 0, 0⟩) (hxeq : (↑h0.ix.val : secpF) = h1.ix.val) : h1.toECPoint = 0 ∨ h1.toECPoint = h0.toECPoint ∨ h1.toECPoint = - h0.toECPoint := begin by_cases h1xz : pt1.x = ⟨0, 0, 0⟩, { left, simp [BddECPointData.toECPoint, h1xz], refl }, right, simp [BddECPointData.toECPoint, h1xz, hpt0xnz, ECPoint.neg_def, ECPoint.neg, hxeq], have := h0.onEC, simp [hxeq, hpt0xnz, ←(h1.onEC' h1xz)] at this, exact eq_or_eq_neg_of_sq_eq_sq _ _ this.symm end -- Do not change the statement of this theorem. You may change the proof. theorem sound_ec_mul_inner {mem : F → F} (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (scalar m ρ_range_check_ptr : F) (ρ_pow2 ρ_res : EcPoint F) (h_auto : auto_spec_ec_mul_inner mem κ range_check_ptr point scalar m ρ_range_check_ptr ρ_pow2 ρ_res) : spec_ec_mul_inner mem κ range_check_ptr point scalar m ρ_range_check_ptr ρ_pow2 ρ_res := begin intros secpF _ ptxnez hpt, resetI, rcases h_auto with ⟨neq, scalareq, _, rfl, _, _, ret1eq, ret2eq⟩ | ⟨nnz, _, _, double_pt, hdouble_pt, _, heven_or_odd⟩, { use 0, split, { rw [neq, nat.cast_zero] }, split, { rw PRIME.char_eq, apply PRIME_pos }, intro _, use 0, split, { rw [scalareq, nat.cast_zero] }, split, { norm_num }, rw [ret1eq, ret2eq], dsimp, use [hpt, ptxnez], simp, use BddECPointData.zero, simp [BddECPointData.toECPoint], refl }, rcases spec_ec_double'_of_spec_ec_double hdouble_pt secpF hpt with ⟨hdouble, hdouble_eq⟩, have double_ne : double_pt.x ≠ ⟨0, 0, 0⟩, { rw [ne, ←hdouble.toECPoint_eq_zero_iff], contrapose! ptxnez, rw ptxnez at hdouble_eq, rw [←hpt.toECPoint_eq_zero_iff], exact secp_field.eq_zero_of_double_eq_zero hdouble_eq.symm }, rcases heven_or_odd with ⟨_, _, heven, _⟩ | ⟨_, _, hodd⟩, { rcases heven secpF double_ne hdouble with ⟨nn', nn'eq, nn'le, haux⟩, use nn' + 1, split, { rw [nat.cast_add, nat.cast_one, ←sub_eq_iff_eq_add, nn'eq] }, split, { apply nat.succ_le_of_lt, apply lt_of_le_of_ne (nat.succ_le_of_lt nn'le), contrapose! nnz, rw [eq_add_of_sub_eq nn'eq], transitivity (↑(nn'.succ) : F), { simp }, rw [nnz, ring_char.spec] }, intro nn'le, have nn'le' : nn' ≤ SECP_LOG2_BOUND := le_trans (le_of_lt (nat.lt_succ_self _)) nn'le, rcases haux nn'le' with ⟨nscalar, nscalareq, nscalarlt, hdoublepow2, hdoublepow2ne, hdoublepow2eq, hdoubleres, hdoublereseq⟩, use 2 * nscalar, split, { rw [nat.cast_mul, ←nscalareq], symmetry, norm_cast, apply mul_div_cancel', apply PRIME.two_ne_zero }, split, { rw [pow_succ], apply nat.mul_lt_mul_of_pos_left nscalarlt, norm_num }, use [hdoublepow2, hdoublepow2ne], split, { rw [pow_succ', ←smul_smul, hdoublepow2eq, hdouble_eq] }, use hdoubleres, rw [mul_comm 2, ←smul_smul, hdoublereseq, hdouble_eq] }, rcases hodd with ⟨_, inner_pow2, inner_res, hodd1, _, _, res, hodd2, _, _, ret1eq, ret2eq⟩, rcases hodd1 secpF double_ne hdouble with ⟨nn', nn'eq, nn'le, haux⟩, use nn' + 1, split, { rw [nat.cast_add, nat.cast_one, ←sub_eq_iff_eq_add, nn'eq] }, split, { apply nat.succ_le_of_lt, apply lt_of_le_of_ne (nat.succ_le_of_lt nn'le), contrapose! nnz, rw [eq_add_of_sub_eq nn'eq], transitivity (↑(nn'.succ) : F), { simp }, rw [nnz, ring_char.spec] }, intro nn'le, have nn'le' : nn' ≤ SECP_LOG2_BOUND := le_trans (le_of_lt (nat.lt_succ_self _)) nn'le, rcases haux nn'le' with ⟨nscalar, nscalareq, nscalarlt, hinnerpow2, hinnerpow2ne, hinnerpow2eq, hinnerres, hinnerreseq⟩, have : (↑(hpt.ix.val) : secpF) ≠ ↑(hinnerres.ix.val), { intro h, have := ec_mul_inner_aux hpt hinnerres ptxnez h, rw [hinnerreseq, hdouble_eq, smul_smul] at this, revert this, apply secp_field.order_large, { rw [ne, BddECPointData.toECPoint_eq_zero_iff], exact ptxnez }, refine lt_of_lt_of_le (nat.mul_lt_mul_of_pos_right nscalarlt (by norm_num)) _, rw ←pow_succ', exact nat.pow_le_pow_of_le_right (by norm_num) nn'le }, rcases spec_fast_ec_add'_of_spec_ec_add hodd2 secpF hpt hinnerres this with ⟨hret, hreteq⟩, use 2 * nscalar + 1, split, { rw [nat.cast_add, nat.cast_mul, ←nscalareq], symmetry, simp, rw mul_div_cancel' (scalar - 1) (PRIME.two_ne_zero F), simp }, rw [ret1eq, ret2eq], split, { rw [pow_succ, two_mul, add_assoc, two_mul], apply add_lt_add_of_lt_of_le nscalarlt, apply nat.succ_le_of_lt nscalarlt }, use [hinnerpow2, hinnerpow2ne], split, { rw [pow_succ', ←smul_smul, hinnerpow2eq, hdouble_eq] }, use hret, rw [add_comm, add_smul, one_smul, mul_comm 2, ←smul_smul, hreteq, hinnerreseq, hdouble_eq] end /- -- Function: ec_mul -/ /- ec_mul autogenerated specification -/ -- Do not change this definition. def auto_spec_ec_mul (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (scalar : BigInt3 F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ∃ (κ₁ : ℕ) (range_check_ptr₁ : F) (pow2_0 res0 : EcPoint F), spec_ec_mul_inner mem κ₁ range_check_ptr point scalar.d0 86 range_check_ptr₁ pow2_0 res0 ∧ ∃ (κ₂ : ℕ) (range_check_ptr₂ : F) (pow2_1 res1 : EcPoint F), spec_ec_mul_inner mem κ₂ range_check_ptr₁ pow2_0 scalar.d1 86 range_check_ptr₂ pow2_1 res1 ∧ ∃ (κ₃ : ℕ) (range_check_ptr₃ : F) (ret2_0 res2 : EcPoint F), spec_ec_mul_inner mem κ₃ range_check_ptr₂ pow2_1 scalar.d2 84 range_check_ptr₃ ret2_0 res2 ∧ ∃ (κ₄ : ℕ) (range_check_ptr₄ : F) (res : EcPoint F), spec_ec_add mem κ₄ range_check_ptr₃ res0 res1 range_check_ptr₄ res ∧ ∃ (κ₅ : ℕ) (range_check_ptr₅ : F) (res₁ : EcPoint F), spec_ec_add mem κ₅ range_check_ptr₄ res res2 range_check_ptr₅ res₁ ∧ κ₁ + κ₂ + κ₃ + κ₄ + κ₅ + 71 ≤ κ ∧ ρ_range_check_ptr = range_check_ptr₅ ∧ ρ_res = res₁ -- You may change anything in this definition except the name and arguments. def spec_ec_mul (mem : F → F) (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (scalar : BigInt3 F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) : Prop := ∀ (secpF : Type) [secp_field secpF], by exactI point.x ≠ ⟨0, 0, 0⟩ → ∀ hpt : BddECPointData secpF point, ∃ n0 < 2^86, scalar.d0 = ↑n0 ∧ ∃ n1 < 2^86, scalar.d1 = ↑n1 ∧ ∃ n2 < 2^84, scalar.d2 = ↑n2 ∧ ∃ hres : BddECPointData secpF ρ_res, hres.toECPoint = (2^172 * n2 + 2^86 * n1 + n0) • hpt.toECPoint /- ec_mul soundness theorem -/ -- Do not change the statement of this theorem. You may change the proof. theorem sound_ec_mul {mem : F → F} (κ : ℕ) (range_check_ptr : F) (point : EcPoint F) (scalar : BigInt3 F) (ρ_range_check_ptr : F) (ρ_res : EcPoint F) (h_auto : auto_spec_ec_mul mem κ range_check_ptr point scalar ρ_range_check_ptr ρ_res) : spec_ec_mul mem κ range_check_ptr point scalar ρ_range_check_ptr ρ_res := begin intros secpF secp_field ptxnez hpt, resetI, rcases h_auto with ⟨_, _, pow2_0, res0, h0, _, _, pow2_1, res1, h1, _, _, ret2_0, res_2, h2, _, _, res, h3, _, _, res₁, h4, _, _, ret1eq⟩, rcases h0 secpF ptxnez hpt with ⟨nb0, nb0eq, nb0lt, h0aux⟩, have nb0eq' : nb0 = 86, { apply nat.cast_inj_of_lt_char nb0lt, { rw [PRIME.char_eq, PRIME], norm_num1 }, rw ←nb0eq, simp }, have nb0le : nb0 ≤ SECP_LOG2_BOUND, by { rw [nb0eq', SECP_LOG2_BOUND], norm_num1 }, rcases h0aux nb0le with ⟨n0, n0eq, n0lt, hpow20, hpow20ne, hpow20eq, hres0, hres0eq⟩, rcases h1 secpF hpow20ne hpow20 with ⟨nb1, nb1eq, nb1lt, h1aux⟩, have nb1eq' : nb1 = 86, { apply nat.cast_inj_of_lt_char nb1lt, { rw [PRIME.char_eq, PRIME], norm_num1 }, rw ←nb1eq, simp }, have nb1le : nb1 ≤ SECP_LOG2_BOUND, by { rw [nb1eq', SECP_LOG2_BOUND], norm_num1 }, rcases h1aux nb1le with ⟨n1, n1eq, n1lt, hpow21, hpow21ne, hpow21eq, hres1, hres1eq⟩, rcases h2 secpF hpow21ne hpow21 with ⟨nb2, nb2eq, nb2lt, h2aux⟩, have nb2eq' : nb2 = 84, { apply nat.cast_inj_of_lt_char nb2lt, { rw [PRIME.char_eq, PRIME], norm_num1 }, rw ←nb2eq, simp }, have nb2le : nb2 ≤ SECP_LOG2_BOUND, by { rw [nb2eq', SECP_LOG2_BOUND], norm_num1 }, rcases h2aux nb2le with ⟨n2, n2eq, n2lt, hpow22, hpow22ne, hpow22eq, hres2, hres2eq⟩, rcases h3 secpF hres0 hres1 with ⟨hres, hreseq⟩, rcases h4 secpF hres hres2 with ⟨hres2, hreseq2⟩, use n0, split, { rw ←nb0eq', exact n0lt }, use n0eq, use n1, split, { rw ←nb1eq', exact n1lt }, use n1eq, use n2, split, { rw ←nb2eq', exact n2lt }, use n2eq, rw ret1eq, use hres2, rw [hreseq2, hres2eq, hpow21eq, hpow20eq, hreseq, hres1eq, hres0eq, hpow20eq], simp only [smul_smul, ←add_smul, nb0eq', nb1eq', nb2eq', BASE, pow_two], norm_num1, congr' 1, ring end theorem ec_mul_bound {n0 n1 n2 : ℕ} (n0lt : n0 < 2^86) (n1lt : n1 < 2^86) (n2lt : n2 < 2^84) : 2^172 * n2 + 2^86 * n1 + n0 < 2^256 := begin apply @lt_of_lt_of_le _ _ _ ((2^86)^2 * (2^84 - 1) + 2^86 * (2^86 - 1) + 2^86), apply add_lt_add_of_le_of_lt _ n0lt, apply add_le_add, apply nat.mul_le_mul, norm_num, apply le_tsub_of_add_le_right, apply nat.succ_le_of_lt n2lt, apply nat.mul_le_mul_left, apply le_tsub_of_add_le_right, apply nat.succ_le_of_lt n1lt, norm_num end end starkware.cairo.common.cairo_secp.ec
294733b87c293f610aaee7c4e22dc1febd17f0d4
3f1a1d97c03bb24b55a1b9969bb4b3c619491d5a
/library/init/data/ordering/lemmas.lean
e4edd646cf4dfcbcd1f852c63640ea3424598771
[ "Apache-2.0" ]
permissive
praveenmunagapati/lean
00c3b4496cef8e758396005013b9776bb82c4f56
fc760f57d20e0a486d14bc8a08d89147b60f530c
refs/heads/master
1,630,692,342,183
1,515,626,222,000
1,515,626,222,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,114
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.ordering.basic init.meta init.algebra.classes init.ite_simp set_option default_priority 100 universes u namespace ordering /- Delete the following simp lemmas as soon as we improve the simplifier. -/ @[simp] lemma lt_ne_eq : ordering.lt ≠ ordering.eq := by contradiction @[simp] lemma lt_ne_gt : ordering.lt ≠ ordering.gt := by contradiction @[simp] lemma eq_ne_lt : ordering.eq ≠ ordering.lt := by contradiction @[simp] lemma eq_ne_gt : ordering.eq ≠ ordering.gt := by contradiction @[simp] lemma gt_ne_lt : ordering.gt ≠ ordering.lt := by contradiction @[simp] lemma gt_ne_eq : ordering.gt ≠ ordering.eq := by contradiction @[simp] theorem ite_eq_lt_distrib (c : Prop) [decidable c] (a b : ordering) : ((if c then a else b) = ordering.lt) = (if c then a = ordering.lt else b = ordering.lt) := by by_cases c; simp [*] @[simp] theorem ite_eq_eq_distrib (c : Prop) [decidable c] (a b : ordering) : ((if c then a else b) = ordering.eq) = (if c then a = ordering.eq else b = ordering.eq) := by by_cases c; simp [*] @[simp] theorem ite_eq_gt_distrib (c : Prop) [decidable c] (a b : ordering) : ((if c then a else b) = ordering.gt) = (if c then a = ordering.gt else b = ordering.gt) := by by_cases c; simp [*] /- ------------------------------------------------------------------ -/ end ordering section variables {α : Type u} {lt : α → α → Prop} [decidable_rel lt] local attribute [simp] cmp_using @[simp] lemma cmp_using_eq_lt (a b : α) : (cmp_using lt a b = ordering.lt) = lt a b := by simp @[simp] lemma cmp_using_eq_gt [is_strict_order α lt] (a b : α) : (cmp_using lt a b = ordering.gt) = lt b a := begin simp, apply propext, apply iff.intro, { exact λ h, h.2 }, { intro hba, split, { intro hab, exact absurd (trans hab hba) (irrefl a) }, { assumption } } end @[simp] lemma cmp_using_eq_eq (a b : α) : (cmp_using lt a b = ordering.eq) = (¬ lt a b ∧ ¬ lt b a) := by simp end
0763cc88e068231e0b6963db1bc60ffe044d4ff9
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world8/level13.lean
53240f5ba9046f9d053858396b7f9afcd8d285b4
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
585
lean
import game.world8.level12 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 13: `ne_succ_self` The last level in Advanced Addition World is the statement that $n\not=\operatorname{succ}(n)$. When you've done this you've completed Advanced Addition World and can move on to Advanced Multiplication World (after first doing Multiplication World, if you didn't do it already). -/ /- Lemma For any natural number $n$, we have $$ n \neq \operatorname{succ}(n). $$ -/ lemma ne_succ_self (n : mynat) : n ≠ succ n := begin [nat_num_game] end end mynat -- hide
9f048aa4597cb4987741d47e60e7d9db72032509
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Init/Data/ByteArray/Basic.lean
46f5c4411ceed3deb17da9ee7893e527bf5f3af7
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
7,389
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.Array.Basic import Init.Data.Array.Subarray import Init.Data.UInt import Init.Data.Option.Basic universe u structure ByteArray where data : Array UInt8 attribute [extern "lean_byte_array_mk"] ByteArray.mk attribute [extern "lean_byte_array_data"] ByteArray.data namespace ByteArray @[extern "lean_mk_empty_byte_array"] def mkEmpty (c : @& Nat) : ByteArray := { data := #[] } def empty : ByteArray := mkEmpty 0 instance : Inhabited ByteArray where default := empty instance : EmptyCollection ByteArray where emptyCollection := ByteArray.empty @[extern "lean_byte_array_push"] def push : ByteArray → UInt8 → ByteArray | ⟨bs⟩, b => ⟨bs.push b⟩ @[extern "lean_byte_array_size"] def size : (@& ByteArray) → Nat | ⟨bs⟩ => bs.size @[extern "lean_byte_array_uget"] def uget : (a : @& ByteArray) → (i : USize) → i.toNat < a.size → UInt8 | ⟨bs⟩, i, h => bs[i] @[extern "lean_byte_array_get"] def get! : (@& ByteArray) → (@& Nat) → UInt8 | ⟨bs⟩, i => bs.get! i @[extern "lean_byte_array_fget"] def get : (a : @& ByteArray) → (@& Fin a.size) → UInt8 | ⟨bs⟩, i => bs.get i instance : GetElem ByteArray Nat UInt8 fun xs i => i < xs.size where getElem xs i h := xs.get ⟨i, h⟩ instance : GetElem ByteArray USize UInt8 fun xs i => i.val < xs.size where getElem xs i h := xs.uget i h @[extern "lean_byte_array_set"] def set! : ByteArray → (@& Nat) → UInt8 → ByteArray | ⟨bs⟩, i, b => ⟨bs.set! i b⟩ @[extern "lean_byte_array_fset"] def set : (a : ByteArray) → (@& Fin a.size) → UInt8 → ByteArray | ⟨bs⟩, i, b => ⟨bs.set i b⟩ @[extern "lean_byte_array_uset"] def uset : (a : ByteArray) → (i : USize) → UInt8 → i.toNat < a.size → ByteArray | ⟨bs⟩, i, v, h => ⟨bs.uset i v h⟩ def isEmpty (s : ByteArray) : Bool := s.size == 0 /-- Copy the slice at `[srcOff, srcOff + len)` in `src` to `[destOff, destOff + len)` in `dest`, growing `dest` if necessary. If `exact` is `false`, the capacity will be doubled when grown. -/ @[extern "lean_byte_array_copy_slice"] def copySlice (src : @& ByteArray) (srcOff : Nat) (dest : ByteArray) (destOff len : Nat) (exact : Bool := true) : ByteArray := ⟨dest.data.extract 0 destOff ++ src.data.extract srcOff (srcOff + len) ++ dest.data.extract (destOff + len) dest.data.size⟩ def extract (a : ByteArray) (b e : Nat) : ByteArray := a.copySlice b empty 0 (e - b) protected def append (a : ByteArray) (b : ByteArray) : ByteArray := -- we assume that `append`s may be repeated, so use asymptotic growing; use `copySlice` directly to customize b.copySlice 0 a a.size b.size false instance : Append ByteArray := ⟨ByteArray.append⟩ partial def toList (bs : ByteArray) : List UInt8 := let rec loop (i : Nat) (r : List UInt8) := if i < bs.size then loop (i+1) (bs.get! i :: r) else r.reverse loop 0 [] @[inline] partial def findIdx? (a : ByteArray) (p : UInt8 → Bool) (start := 0) : Option Nat := let rec @[specialize] loop (i : Nat) := if i < a.size then if p (a.get! i) then some i else loop (i+1) else none loop start /-- We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime. This is similar to the `Array` version. TODO: avoid code duplication in the future after we improve the compiler. -/ @[inline] unsafe def forInUnsafe {β : Type v} {m : Type v → Type w} [Monad m] (as : ByteArray) (b : β) (f : UInt8 → β → m (ForInStep β)) : m β := let sz := USize.ofNat as.size let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop 0 b /-- Reference implementation for `forIn` -/ @[implemented_by ByteArray.forInUnsafe] protected def forIn {β : Type v} {m : Type v → Type w} [Monad m] (as : ByteArray) (b : β) (f : UInt8 → β → m (ForInStep β)) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => have h' : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self i) h have : as.size - 1 < as.size := Nat.sub_lt (Nat.zero_lt_of_lt h') (by decide) have : as.size - 1 - i < as.size := Nat.lt_of_le_of_lt (Nat.sub_le (as.size - 1) i) this match (← f (as.get ⟨as.size - 1 - i, this⟩) b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.le_of_lt h') b loop as.size (Nat.le_refl _) b instance : ForIn m ByteArray UInt8 where forIn := ByteArray.forIn /-- See comment at `forInUnsafe` -/ -- TODO: avoid code duplication. @[inline] unsafe def foldlMUnsafe {β : Type v} {m : Type v → Type w} [Monad m] (f : β → UInt8 → m β) (init : β) (as : ByteArray) (start := 0) (stop := as.size) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i+1) stop (← f b (as.uget i lcProof)) if start < stop then if stop ≤ as.size then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else pure init /-- Reference implementation for `foldlM` -/ @[implemented_by foldlMUnsafe] def foldlM {β : Type v} {m : Type v → Type w} [Monad m] (f : β → UInt8 → m β) (init : β) (as : ByteArray) (start := 0) (stop := as.size) : m β := let fold (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) (b : β) : m β := do if hlt : j < stop then match i with | 0 => pure b | i'+1 => loop i' (j+1) (← f b (as.get ⟨j, Nat.lt_of_lt_of_le hlt h⟩)) else pure b loop (stop - start) start init if h : stop ≤ as.size then fold stop h else fold as.size (Nat.le_refl _) @[inline] def foldl {β : Type v} (f : β → UInt8 → β) (init : β) (as : ByteArray) (start := 0) (stop := as.size) : β := Id.run <| as.foldlM f init start stop end ByteArray def List.toByteArray (bs : List UInt8) : ByteArray := let rec loop | [], r => r | b::bs, r => loop bs (r.push b) loop bs ByteArray.empty instance : ToString ByteArray := ⟨fun bs => bs.toList.toString⟩ /-- Interpret a `ByteArray` of size 8 as a little-endian `UInt64`. -/ def ByteArray.toUInt64LE! (bs : ByteArray) : UInt64 := assert! bs.size == 8 (bs.get! 0).toUInt64 <<< 0x38 ||| (bs.get! 1).toUInt64 <<< 0x30 ||| (bs.get! 2).toUInt64 <<< 0x28 ||| (bs.get! 3).toUInt64 <<< 0x20 ||| (bs.get! 4).toUInt64 <<< 0x18 ||| (bs.get! 5).toUInt64 <<< 0x10 ||| (bs.get! 6).toUInt64 <<< 0x8 ||| (bs.get! 7).toUInt64 /-- Interpret a `ByteArray` of size 8 as a big-endian `UInt64`. -/ def ByteArray.toUInt64BE! (bs : ByteArray) : UInt64 := assert! bs.size == 8 (bs.get! 7).toUInt64 <<< 0x38 ||| (bs.get! 6).toUInt64 <<< 0x30 ||| (bs.get! 5).toUInt64 <<< 0x28 ||| (bs.get! 4).toUInt64 <<< 0x20 ||| (bs.get! 3).toUInt64 <<< 0x18 ||| (bs.get! 2).toUInt64 <<< 0x10 ||| (bs.get! 1).toUInt64 <<< 0x8 ||| (bs.get! 0).toUInt64
b55ecbbd4f72126c66fdfab29dfbffe5e02347e0
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/AuxRecursor.lean
de557215e9e39d0a1997db96c313dc83d674f819
[ "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
1,961
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.Environment namespace Lean def casesOnSuffix := "casesOn" def recOnSuffix := "recOn" def brecOnSuffix := "brecOn" def binductionOnSuffix := "binductionOn" def belowSuffix := "below" def mkCasesOnName (indDeclName : Name) : Name := Name.mkStr indDeclName casesOnSuffix def mkRecOnName (indDeclName : Name) : Name := Name.mkStr indDeclName recOnSuffix def mkBRecOnName (indDeclName : Name) : Name := Name.mkStr indDeclName brecOnSuffix def mkBInductionOnName (indDeclName : Name) : Name := Name.mkStr indDeclName binductionOnSuffix def mkBelowName (indDeclName : Name) : Name := Name.mkStr indDeclName belowSuffix builtin_initialize auxRecExt : TagDeclarationExtension ← mkTagDeclarationExtension `auxRec @[export lean_mark_aux_recursor] def markAuxRecursor (env : Environment) (declName : Name) : Environment := auxRecExt.tag env declName @[export lean_is_aux_recursor] def isAuxRecursor (env : Environment) (declName : Name) : Bool := auxRecExt.isTagged env declName -- TODO: use `markAuxRecursor` when they are defined -- An attribute is not a good solution since we don't want users to control what is tagged as an auxiliary recursor. || declName == ``Eq.ndrec || declName == ``Eq.ndrecOn def isCasesOnRecursor (env : Environment) (declName : Name) : Bool := match declName with | Name.str _ s _ => s == casesOnSuffix && isAuxRecursor env declName | _ => false builtin_initialize noConfusionExt : TagDeclarationExtension ← mkTagDeclarationExtension `noConf @[export lean_mark_no_confusion] def markNoConfusion (env : Environment) (n : Name) : Environment := noConfusionExt.tag env n @[export lean_is_no_confusion] def isNoConfusion (env : Environment) (n : Name) : Bool := noConfusionExt.isTagged env n end Lean
b1815b9c050323a97274b6513dea8d6aacc0d905
5c5878e769950eabe897ad08485b3ba1a619cea9
/examples/universes.lean
2a510cac0033339e4df1bc8d6b071bc1ab72e9f1
[ "Apache-2.0" ]
permissive
semorrison/lean-category-theory-pr
39dc2077fcb41b438e61be1685e4cbca298767ed
7adc8d91835e883db0fe75aa33661bc1480dbe55
refs/heads/master
1,583,748,682,010
1,535,111,040,000
1,535,111,040,000
128,731,071
1
2
Apache-2.0
1,528,069,880,000
1,523,258,452,000
Lean
UTF-8
Lean
false
false
2,748
lean
universes u₁ v₁ u₂ v₂ structure Category := (Obj : Type u₁) (Hom : Obj → Obj → Type v₁) (identity : Π X : Obj, Hom X X) (compose : Π {X Y Z : Obj}, Hom X Y → Hom Y Z → Hom X Z) (left_identity : ∀ {X Y : Obj} (f : Hom X Y), compose (identity X) f = f) (right_identity : ∀ {X Y : Obj} (f : Hom X Y), compose f (identity Y) = f) (associativity : ∀ {W X Y Z : Obj} (f : Hom W X) (g : Hom X Y) (h : Hom Y Z), compose (compose f g) h = compose f (compose g h)) structure Functor (C : Category.{u₁ v₁}) (D : Category.{u₂ v₂}) := (onObjects : C.Obj → D.Obj) (onMorphisms : Π {X Y : C.Obj}, (C.Hom X Y) → (D.Hom (onObjects X) (onObjects Y))) (identities : ∀ (X : C.Obj), onMorphisms (C.identity X) = D.identity (onObjects X)) (functoriality : ∀ {X Y Z : C.Obj} (f : C.Hom X Y) (g : C.Hom Y Z), onMorphisms (C.compose f g) = D.compose (onMorphisms f) (onMorphisms g)) structure NaturalTransformation {C : Category.{u₁ v₁}} {D : Category.{u₂ v₂}} (F G : Functor C D) := (components: Π X : C.Obj, D.Hom (F.onObjects X) (G.onObjects X)) (naturality: ∀ {X Y : C.Obj} (f : C.Hom X Y), D.compose (F.onMorphisms f) (components Y) = D.compose (components X) (G.onMorphisms f)) #print Category -- Type (max (u₁+1) (v₁+1)) #print Functor -- Type (max u₁ u₂ v₁ v₂) #print NaturalTransformation -- Type (max u₁ v₂) def FunctorCategory (C : Category.{u₁ v₁}) (D : Category.{u₂ v₂}) : Category := by refine { Obj := Functor C D, Hom := λ F G, NaturalTransformation F G, .. } ; sorry set_option pp.universes true #print FunctorCategory -- Category.{(max u₁ u₂ v₁ v₂) (max u₁ v₂)} /- Summarising, we have: Category : Type (max (u₁+1) (v₁+1)) C : Category.{u₁ v₁} D : Category.{u₂ v₂} Functor C D : Type (max u₁ u₂ v₁ v₂) NaturalTransformation : Type (max u₁ v₂) FunctorCategory : Category.{(max u₁ u₂ v₁ v₂) (max u₁ v₂)} If uᵢ=vᵢ+1, we then have: Category : Type (v₁+2) C : Category.{v₁+1 v₁} D : Category.{v₂+1 v₂} Functor C D : Type (max v₁+1 v₂+1) NaturalTransformation : Type (max (v₁+1) v₂) FunctorCategory C D : Category.{(max (v₁+1) (v₂+1)) (max (v₁+1) v₂)} If moreover v₂=v₁, then FunctorCategory C D : Category.{(v₁+1) (v₁+1)} That is, the FunctorCategory is a whole level up (but small...) If C is a small category, so u₁=v₁, and D has u₂=v₂+1, we then have: Functor C D : Type (max v₁ v₂+1) FunctorCategory C D : Category.{(mav v₁ (v₂+1)) (max v₁ v₂)} If moreover v₂=v₁, then FunctorCategory C D : Category.{(v₁+1) v₁} That is, FunctorCategory is a large category at the same level as we started. -/
577837287b92c3884ac42f1eee776dd15bbcb29a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/doc_string2.lean
d0d96a074cf78af0d27e392b50b8711a797181c2
[ "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
257
lean
/-- Documentation for inductive foo -/ inductive foo | val1 | val2 namespace foo /-- Documentation for x -/ def x := 10 end foo open tactic run_cmd do trace "--------", doc_string `foo >>= trace, trace "--------", doc_string `foo.x >>= trace
f720c498dd5edbe594e1aad8efa8fe1ab2d2adc3
82e44445c70db0f03e30d7be725775f122d72f3e
/src/number_theory/dioph.lean
9517b606612c4987abfb69d8c18d13c499a99424
[ "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
35,392
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import number_theory.pell import data.pfun import data.fin2 /-! # Diophantine functions and Matiyasevic's theorem Hilbert's tenth problem asked whether there exists an algorithm which for a given integer polynomial determines whether this polynomial has integer solutions. It was answered in the negative in 1970, the final step being completed by Matiyasevic who showed that the power function is Diophantine. Here a function is called Diophantine if its graph is Diophantine as a set. A subset `S ⊆ ℕ ^ α` in turn is called Diophantine if there exists an integer polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. ## Main definitions * `is_poly`: a predicate stating that a function is a multivariate integer polynomial. * `poly`: the type of multivariate integer polynomial functions. * `dioph`: a predicate stating that a set `S ⊆ ℕ^α` is Diophantine, i.e. that * `dioph_fn`: a predicate on a function stating that it is Diophantine in the sense that its graph is Diophantine as a set. ## Main statements * `pell_dioph` states that solutions to Pell's equation form a Diophantine set. * `pow_dioph` states that the power function is Diophantine, a version of Matiyasevic's theorem. ## References * [M. Carneiro, _A Lean formalization of Matiyasevic's theorem_][carneiro2018matiyasevic] * [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916] ## Tags Matiyasevic's theorem, Hilbert's tenth problem ## TODO * Finish the solution of Hilbert's tenth problem. * Connect `poly` to `mv_polynomial` -/ universe u open nat function namespace int lemma eq_nat_abs_iff_mul (x n) : nat_abs x = n ↔ (x - n) * (x + n) = 0 := begin refine iff.trans _ mul_eq_zero.symm, refine iff.trans _ (or_congr sub_eq_zero add_eq_zero_iff_eq_neg).symm, exact ⟨λe, by rw ← e; apply nat_abs_eq, λo, by cases o; subst x; simp [nat_abs_of_nat]⟩ end end int open fin2 /-- Alternate definition of `vector` based on `fin2`. -/ def vector3 (α : Type u) (n : ℕ) : Type u := fin2 n → α namespace vector3 /-- The empty vector -/ @[pattern] def nil {α} : vector3 α 0. /-- The vector cons operation -/ @[pattern] def cons {α} {n} (a : α) (v : vector3 α n) : vector3 α (succ n) := λi, by {refine i.cases' _ _, exact a, exact v} /- We do not want to make the following notation global, because then these expressions will be overloaded, and only the expected type will be able to disambiguate the meaning. Worse: Lean will try to insert a coercion from `vector3 α _` to `list α`, if a list is expected. -/ localized "notation `[` l:(foldr `, ` (h t, vector3.cons h t) nil `]`) := l" in vector3 notation a :: b := cons a b @[simp] theorem cons_fz {α} {n} (a : α) (v : vector3 α n) : (a :: v) fz = a := rfl @[simp] theorem cons_fs {α} {n} (a : α) (v : vector3 α n) (i) : (a :: v) (fs i) = v i := rfl /-- Get the `i`th element of a vector -/ @[reducible] def nth {α} {n} (i : fin2 n) (v : vector3 α n) : α := v i /-- Construct a vector from a function on `fin2`. -/ @[reducible] def of_fn {α} {n} (f : fin2 n → α) : vector3 α n := f /-- Get the head of a nonempty vector. -/ def head {α} {n} (v : vector3 α (succ n)) : α := v fz /-- Get the tail of a nonempty vector. -/ def tail {α} {n} (v : vector3 α (succ n)) : vector3 α n := λi, v (fs i) theorem eq_nil {α} (v : vector3 α 0) : v = [] := funext $ λi, match i with end theorem cons_head_tail {α} {n} (v : vector3 α (succ n)) : head v :: tail v = v := funext $ λi, fin2.cases' rfl (λ_, rfl) i def nil_elim {α} {C : vector3 α 0 → Sort u} (H : C []) (v : vector3 α 0) : C v := by rw eq_nil v; apply H def cons_elim {α n} {C : vector3 α (succ n) → Sort u} (H : Π (a : α) (t : vector3 α n), C (a :: t)) (v : vector3 α (succ n)) : C v := by rw ← (cons_head_tail v); apply H @[simp] theorem cons_elim_cons {α n C H a t} : @cons_elim α n C H (a :: t) = H a t := rfl @[elab_as_eliminator] protected def rec_on {α} {C : Π {n}, vector3 α n → Sort u} {n} (v : vector3 α n) (H0 : C []) (Hs : Π {n} (a) (w : vector3 α n), C w → C (a :: w)) : C v := nat.rec_on n (λv, v.nil_elim H0) (λn IH v, v.cons_elim (λa t, Hs _ _ (IH _))) v @[simp] theorem rec_on_nil {α C H0 Hs} : @vector3.rec_on α @C 0 [] H0 @Hs = H0 := rfl @[simp] theorem rec_on_cons {α C H0 Hs n a v} : @vector3.rec_on α @C (succ n) (a :: v) H0 @Hs = Hs a v (@vector3.rec_on α @C n v H0 @Hs) := rfl /-- Append two vectors -/ def append {α} {m} (v : vector3 α m) {n} (w : vector3 α n) : vector3 α (n+m) := nat.rec_on m (λ_, w) (λm IH v, v.cons_elim $ λa t, @fin2.cases' (n+m) (λ_, α) a (IH t)) v local infix ` +-+ `:65 := vector3.append @[simp] theorem append_nil {α} {n} (w : vector3 α n) : [] +-+ w = w := rfl @[simp] theorem append_cons {α} (a : α) {m} (v : vector3 α m) {n} (w : vector3 α n) : (a::v) +-+ w = a :: (v +-+ w) := rfl @[simp] theorem append_left {α} : ∀ {m} (i : fin2 m) (v : vector3 α m) {n} (w : vector3 α n), (v +-+ w) (left n i) = v i | ._ (@fz m) v n w := v.cons_elim (λa t, by simp [*, left]) | ._ (@fs m i) v n w := v.cons_elim (λa t, by simp [*, left]) @[simp] theorem append_add {α} : ∀ {m} (v : vector3 α m) {n} (w : vector3 α n) (i : fin2 n), (v +-+ w) (add i m) = w i | 0 v n w i := rfl | (succ m) v n w i := v.cons_elim (λa t, by simp [*, add]) /-- Insert `a` into `v` at index `i`. -/ def insert {α} (a : α) {n} (v : vector3 α n) (i : fin2 (succ n)) : vector3 α (succ n) := λj, (a :: v) (insert_perm i j) @[simp] theorem insert_fz {α} (a : α) {n} (v : vector3 α n) : insert a v fz = a :: v := by refine funext (λj, j.cases' _ _); intros; refl @[simp] theorem insert_fs {α} (a : α) {n} (b : α) (v : vector3 α n) (i : fin2 (succ n)) : insert a (b :: v) (fs i) = b :: insert a v i := funext $ λj, by { refine j.cases' _ (λj, _); simp [insert, insert_perm], refine fin2.cases' _ _ (insert_perm i j); simp [insert_perm] } theorem append_insert {α} (a : α) {k} (t : vector3 α k) {n} (v : vector3 α n) (i : fin2 (succ n)) (e : succ n + k = succ (n + k)) : insert a (t +-+ v) (eq.rec_on e (i.add k)) = eq.rec_on e (t +-+ insert a v i) := begin refine vector3.rec_on t (λe, _) (λk b t IH e, _) e, refl, have e' := succ_add n k, change insert a (b :: (t +-+ v)) (eq.rec_on (congr_arg succ e') (fs (add i k))) = eq.rec_on (congr_arg succ e') (b :: (t +-+ insert a v i)), rw ← (eq.drec_on e' rfl : fs (eq.rec_on e' (i.add k) : fin2 (succ (n + k))) = eq.rec_on (congr_arg succ e') (fs (i.add k))), simp, rw IH, exact eq.drec_on e' rfl end end vector3 section vector3 open vector3 open_locale vector3 /-- "Curried" exists, i.e. ∃ x1 ... xn, f [x1, ..., xn] -/ def vector_ex {α} : Π k, (vector3 α k → Prop) → Prop | 0 f := f [] | (succ k) f := ∃x : α, vector_ex k (λv, f (x :: v)) /-- "Curried" forall, i.e. ∀ x1 ... xn, f [x1, ..., xn] -/ def vector_all {α} : Π k, (vector3 α k → Prop) → Prop | 0 f := f [] | (succ k) f := ∀x : α, vector_all k (λv, f (x :: v)) theorem exists_vector_zero {α} (f : vector3 α 0 → Prop) : Exists f ↔ f [] := ⟨λ⟨v, fv⟩, by rw ← (eq_nil v); exact fv, λf0, ⟨[], f0⟩⟩ theorem exists_vector_succ {α n} (f : vector3 α (succ n) → Prop) : Exists f ↔ ∃x v, f (x :: v) := ⟨λ⟨v, fv⟩, ⟨_, _, by rw cons_head_tail v; exact fv⟩, λ⟨x, v, fxv⟩, ⟨_, fxv⟩⟩ theorem vector_ex_iff_exists {α} : ∀ {n} (f : vector3 α n → Prop), vector_ex n f ↔ Exists f | 0 f := (exists_vector_zero f).symm | (succ n) f := iff.trans (exists_congr (λx, vector_ex_iff_exists _)) (exists_vector_succ f).symm theorem vector_all_iff_forall {α} : ∀ {n} (f : vector3 α n → Prop), vector_all n f ↔ ∀ v, f v | 0 f := ⟨λf0 v, v.nil_elim f0, λal, al []⟩ | (succ n) f := (forall_congr (λx, vector_all_iff_forall (λv, f (x :: v)))).trans ⟨λal v, v.cons_elim al, λal x v, al (x::v)⟩ /-- `vector_allp p v` is equivalent to `∀ i, p (v i)`, but unfolds directly to a conjunction, i.e. `vector_allp p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ def vector_allp {α} (p : α → Prop) {n} (v : vector3 α n) : Prop := vector3.rec_on v true (λn a v IH, @vector3.rec_on _ (λn v, Prop) _ v (p a) (λn b v' _, p a ∧ IH)) @[simp] theorem vector_allp_nil {α} (p : α → Prop) : vector_allp p [] = true := rfl @[simp] theorem vector_allp_singleton {α} (p : α → Prop) (x : α) : vector_allp p [x] = p x := rfl @[simp] theorem vector_allp_cons {α} (p : α → Prop) {n} (x : α) (v : vector3 α n) : vector_allp p (x :: v) ↔ p x ∧ vector_allp p v := vector3.rec_on v (and_true _).symm (λn a v IH, iff.rfl) theorem vector_allp_iff_forall {α} (p : α → Prop) {n} (v : vector3 α n) : vector_allp p v ↔ ∀ i, p (v i) := begin refine v.rec_on _ _, { exact ⟨λ_, fin2.elim0, λ_, trivial⟩ }, { simp, refine λn a v IH, (and_congr_right (λ_, IH)).trans ⟨λ⟨pa, h⟩ i, by {refine i.cases' _ _, exacts [pa, h]}, λh, ⟨_, λi, _⟩⟩, { have h0 := h fz, simp at h0, exact h0 }, { have hs := h (fs i), simp at hs, exact hs } } end theorem vector_allp.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) {n} {v : vector3 α n} (al : vector_allp p v) : vector_allp q v := (vector_allp_iff_forall _ _).2 (λi, h _ $ (vector_allp_iff_forall _ _).1 al _) end vector3 /-- `list_all p l` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `list_all p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def list_all {α} (p : α → Prop) : list α → Prop | [] := true | (x :: []) := p x | (x :: l) := p x ∧ list_all l @[simp] theorem list_all_cons {α} (p : α → Prop) (x : α) : ∀ (l : list α), list_all p (x :: l) ↔ p x ∧ list_all p l | [] := (and_true _).symm | (x :: l) := iff.rfl theorem list_all_iff_forall {α} (p : α → Prop) : ∀ (l : list α), list_all p l ↔ ∀ x ∈ l, p x | [] := (iff_true_intro $ list.ball_nil _).symm | (x :: l) := by rw [list.ball_cons, ← list_all_iff_forall l]; simp theorem list_all.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) : ∀ {l : list α}, list_all p l → list_all q l | [] := id | (x :: l) := by simpa using and.imp (h x) list_all.imp @[simp] theorem list_all_map {α β} {p : β → Prop} (f : α → β) {l : list α} : list_all p (l.map f) ↔ list_all (p ∘ f) l := by induction l; simp * theorem list_all_congr {α} {p q : α → Prop} (h : ∀ x, p x ↔ q x) {l : list α} : list_all p l ↔ list_all q l := ⟨list_all.imp (λx, (h x).1), list_all.imp (λx, (h x).2)⟩ instance decidable_list_all {α} (p : α → Prop) [decidable_pred p] (l : list α) : decidable (list_all p l) := decidable_of_decidable_of_iff (by apply_instance) (list_all_iff_forall _ _).symm /- poly -/ /-- A predicate asserting that a function is a multivariate integer polynomial. (We are being a bit lazy here by allowing many representations for multiplication, rather than only allowing monomials and addition, but the definition is equivalent and this is easier to use.) -/ inductive is_poly {α} : ((α → ℕ) → ℤ) → Prop | proj : ∀ i, is_poly (λx : α → ℕ, x i) | const : Π (n : ℤ), is_poly (λx : α → ℕ, n) | sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x - g x) | mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x * g x) /-- The type of multivariate integer polynomials -/ def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f} namespace poly section parameter {α : Type u} instance : has_coe_to_fun (poly α) := ⟨_, λ f, f.1⟩ /-- The underlying function of a `poly` is a polynomial -/ lemma isp (f : poly α) : is_poly f := f.2 /-- Extensionality for `poly α` -/ lemma ext {f g : poly α} (e : ∀x, f x = g x) : f = g := subtype.eq (funext e) /-- Construct a `poly` given an extensionally equivalent `poly`. -/ def subst (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀x, f x = g x) : poly α := ⟨g, by rw ← (funext e : coe_fn f = g); exact f.isp⟩ @[simp] theorem subst_eval (f g e x) : subst f g e x = g x := rfl /-- The `i`th projection function, `x_i`. -/ def proj (i) : poly α := ⟨_, is_poly.proj i⟩ @[simp] theorem proj_eval (i x) : proj i x = x i := rfl /-- The constant function with value `n : ℤ`. -/ def const (n) : poly α := ⟨_, is_poly.const n⟩ @[simp] theorem const_eval (n x) : const n x = n := rfl /-- The zero polynomial -/ def zero : poly α := const 0 instance : has_zero (poly α) := ⟨poly.zero⟩ @[simp] theorem zero_eval (x) : (0 : poly α) x = 0 := rfl /-- The zero polynomial -/ def one : poly α := const 1 instance : has_one (poly α) := ⟨poly.one⟩ @[simp] theorem one_eval (x) : (1 : poly α) x = 1 := rfl /-- Subtraction of polynomials -/ def sub : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.sub pf pg⟩ instance : has_sub (poly α) := ⟨poly.sub⟩ @[simp] theorem sub_eval : Π (f g x), (f - g : poly α) x = f x - g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Negation of a polynomial -/ def neg (f : poly α) : poly α := 0 - f instance : has_neg (poly α) := ⟨poly.neg⟩ @[simp] theorem neg_eval (f x) : (-f : poly α) x = -f x := show (0-f) x = _, by simp /-- Addition of polynomials -/ def add : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := subst (⟨f, pf⟩ - -⟨g, pg⟩) _ (λx, show f x - (0 - g x) = f x + g x, by simp) instance : has_add (poly α) := ⟨poly.add⟩ @[simp] theorem add_eval : Π (f g x), (f + g : poly α) x = f x + g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Multiplication of polynomials -/ def mul : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.mul pf pg⟩ instance : has_mul (poly α) := ⟨poly.mul⟩ @[simp] theorem mul_eval : Π (f g x), (f * g : poly α) x = f x * g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl instance : comm_ring (poly α) := by refine_struct { add := (+), zero := (0 : poly α), neg := has_neg.neg, mul := (*), one := 1, sub := has_sub.sub, npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨neg⟩ }; intros; try { refl }; refine ext (λ _, _); simp [sub_eq_add_neg, mul_add, mul_left_comm, mul_comm, add_comm, add_assoc] lemma induction {C : poly α → Prop} (H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n)) (H3 : ∀f g, C f → C g → C (f - g)) (H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f := begin cases f with f pf, induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg, apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg end /-- The sum of squares of a list of polynomials. This is relevant for Diophantine equations, because it means that a list of equations can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is equivalent to `x^2 + y^2 + z^2 = 0`. -/ def sumsq : list (poly α) → poly α | [] := 0 | (p::ps) := p*p + sumsq ps theorem sumsq_nonneg (x) : ∀ l, 0 ≤ sumsq l x | [] := le_refl 0 | (p::ps) := by rw sumsq; simp [-add_comm]; exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps) theorem sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ list_all (λa : poly α, a x = 0) l | [] := eq_self_iff_true _ | (p::ps) := by rw [list_all_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact ⟨λ(h : p x * p x + sumsq ps x = 0), have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm (by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t) (mul_self_nonneg _), ⟨this, by simp [this] at h; exact h⟩, λ⟨h1, h2⟩, by rw [h1, h2]; refl⟩ end /-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/ def remap {α β} (f : α → β) (g : poly α) : poly β := ⟨λv, g $ v ∘ f, g.induction (λi, by simp; apply is_poly.proj) (λn, by simp; apply is_poly.const) (λf g pf pg, by simp; apply is_poly.sub pf pg) (λf g pf pg, by simp; apply is_poly.mul pf pg)⟩ @[simp] theorem remap_eval {α β} (f : α → β) (g : poly α) (v) : remap f g v = g (v ∘ f) := rfl end poly namespace sum /-- combine two functions into a function on the disjoint union -/ def join {α β γ} (f : α → γ) (g : β → γ) : α ⊕ β → γ := by {refine sum.rec _ _, exacts [f, g]} end sum local infixr ` ⊗ `:65 := sum.join open sum namespace option /-- Functions from `option` can be combined similarly to `vector.cons` -/ def cons {α β} (a : β) (v : α → β) : option α → β := by {refine option.rec _ _, exacts [a, v]} notation a :: b := cons a b @[simp] theorem cons_head_tail {α β} (v : option α → β) : v none :: v ∘ some = v := funext $ λo, by cases o; refl end option /- dioph -/ /-- A set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/ def dioph {α : Type u} (S : set (α → ℕ)) : Prop := ∃ {β : Type u} (p : poly (α ⊕ β)), ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0 namespace dioph section variables {α β γ : Type u} theorem ext {S S' : set (α → ℕ)} (d : dioph S) (H : ∀v, S v ↔ S' v) : dioph S' := eq.rec d $ show S = S', from set.ext H theorem of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ (v : α → ℕ), S v ↔ p v = 0) : dioph S := ⟨ulift empty, p.remap inl, λv, (h v).trans ⟨λh, ⟨λt, empty.rec _ t.down, by simp; rw [ show (v ⊗ λt:ulift empty, empty.rec _ t.down) ∘ inl = v, from rfl, h]⟩, λ⟨t, ht⟩, by simp at ht; rwa [show (v ⊗ t) ∘ inl = v, from rfl] at ht⟩⟩ lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (v : α → ℕ) : (∃t, p (v ⊗ t) = 0) ↔ (∃t, p.remap (inl ⊗ (inr ∘ f)) (v ⊗ t) = 0) := begin simp, refine ⟨λt, _, λt, _⟩; cases t with t ht, { have : (v ⊗ (0 :: t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t := funext (λs, by cases s with a b; dsimp [join, (∘)]; try {rw inv}; refl), exact ⟨(0 :: t) ∘ g, by rwa this⟩ }, { have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) := funext (λs, by cases s with a b; refl), exact ⟨t ∘ f, by rwa this⟩ } end theorem inject_dummies {S : set (α → ℕ)} (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (h : ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0) : ∃ q : poly (α ⊕ γ), ∀ (v : α → ℕ), S v ↔ ∃t, q (v ⊗ t) = 0 := ⟨p.remap (inl ⊗ (inr ∘ f)), λv, (h v).trans $ inject_dummies_lem f g inv _ _⟩ theorem reindex_dioph {S : set (α → ℕ)} : Π (d : dioph S) (f : α → β), dioph (λv, S (v ∘ f)) | ⟨γ, p, pe⟩ f := ⟨γ, p.remap ((inl ∘ f) ⊗ inr), λv, (pe _).trans $ exists_congr $ λt, suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this], funext $ λs, by cases s with a b; refl⟩ theorem dioph_list_all (l) (d : list_all dioph l) : dioph (λv, list_all (λS : set (α → ℕ), S v) l) := suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v, list_all (λS : set _, S v) l ↔ ∃t, list_all (λp : poly (α ⊕ β), p (v ⊗ t) = 0) pl, from let ⟨β, pl, h⟩ := this in ⟨β, poly.sumsq pl, λv, (h v).trans $ exists_congr $ λt, (poly.sumsq_eq_zero _ _).symm⟩, begin induction l with S l IH, exact ⟨ulift empty, [], λv, by simp; exact ⟨λ⟨t⟩, empty.rec _ t, trivial⟩⟩, simp at d, exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) :: pl.map (λq, q.remap (inl ⊗ (inr ∘ inr))), λv, by simp; exact iff.trans (and_congr (pe v) (ple v)) ⟨λ⟨⟨m, hm⟩, ⟨n, hn⟩⟩, ⟨m ⊗ n, by rw [ show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m, from funext $ λs, by cases s with a b; refl]; exact hm, by { refine list_all.imp (λq hq, _) hn, dsimp [(∘)], rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n, from funext $ λs, by cases s with a b; refl]; exact hq }⟩, λ⟨t, hl, hr⟩, ⟨⟨t ∘ inl, by rwa [ show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl, from funext $ λs, by cases s with a b; refl] at hl⟩, ⟨t ∘ inr, by { refine list_all.imp (λq hq, _) hr, dsimp [(∘)] at hq, rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr, from funext $ λs, by cases s with a b; refl] at hq }⟩⟩⟩⟩ end theorem and_dioph {S S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph (λv, S v ∧ S' v) := dioph_list_all [S, S'] ⟨d, d'⟩ theorem or_dioph {S S' : set (α → ℕ)} : ∀ (d : dioph S) (d' : dioph S'), dioph (λv, S v ∨ S' v) | ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) * q.remap (inl ⊗ inr ∘ inr), λv, begin refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ λt, (@mul_eq_zero _ _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl))) (q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)), exact inject_dummies_lem _ (some ⊗ (λ_, none)) (λx, rfl) _ _, exact inject_dummies_lem _ ((λ_, none) ⊗ some) (λx, rfl) _ _, end⟩ /-- A partial function is Diophantine if its graph is Diophantine. -/ def dioph_pfun (f : (α → ℕ) →. ℕ) := dioph (λv : option α → ℕ, f.graph (v ∘ some, v none)) /-- A function is Diophantine if its graph is Diophantine. -/ def dioph_fn (f : (α → ℕ) → ℕ) := dioph (λv : option α → ℕ, f (v ∘ some) = v none) theorem reindex_dioph_fn {f : (α → ℕ) → ℕ} (d : dioph_fn f) (g : α → β) : dioph_fn (λv, f (v ∘ g)) := reindex_dioph d (functor.map g) theorem ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph (λv, ∃x, S (v ⊗ x)) | ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.remap ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [ show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [ show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph (λv, ∃x, S (x :: v)) | ⟨β, p, pe⟩ := ⟨option β, p.remap (inr none :: inl ⊗ inr ∘ some), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x :: t, by simp; rw [ show (v ⊗ x :: t) ∘ (inr none :: inl ⊗ inr ∘ some) = x :: v ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [ show (v ⊗ t) ∘ (inr none :: inl ⊗ inr ∘ some) = t none :: v ⊗ t ∘ some, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom := cast (congr_arg dioph $ set.ext $ λv, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d) theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f := by refine congr_arg dioph (set.ext $ λv, _); exact pfun.lift_graph.symm theorem abs_poly_dioph (p : poly α) : dioph_fn (λv, (p v).nat_abs) := by refine of_no_dummies _ ((p.remap some - poly.proj none) * (p.remap some + poly.proj none)) (λv, _); apply int.eq_nat_abs_iff_mul theorem proj_dioph (i : α) : dioph_fn (λv, v i) := abs_poly_dioph (poly.proj i) theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) : dioph (λv : α → ℕ, ∃ h : f.dom v, S (f.fn v h :: v)) := ext (ex1_dioph (and_dioph d df)) $ λv, ⟨λ⟨x, hS, (h: Exists _)⟩, by rw [show (x :: v) ∘ some = v, from funext $ λs, rfl] at h; cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS, λ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _, by rw [show (f.fn v x :: v) ∘ some = v, from funext $ λs, rfl]; exact ⟨x, rfl⟩⟩⟩ theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) : dioph (λv : α → ℕ, S (f v :: v)) := ext (dioph_pfun_comp1 d (cast (dioph_fn_iff_pfun f) df)) $ λv, ⟨λ⟨_, h⟩, h, λh, ⟨trivial, h⟩⟩ end section variables {α β γ : Type} open vector3 open_locale vector3 theorem dioph_fn_vec_comp1 {n} {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : (vector3 ℕ n) → ℕ} (df : dioph_fn f) : dioph (λv : vector3 ℕ n, S (cons (f v) v)) := ext (dioph_fn_comp1 (reindex_dioph d (none :: some)) df) $ λv, by rw [ show option.cons (f v) v ∘ (cons none some) = f v :: v, from funext $ λs, by cases s with a b; refl] theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) : dioph (λv : vector3 ℕ n, ∃x, S (x :: v)) := ext (ex1_dioph $ reindex_dioph d (none :: some)) $ λv, exists_congr $ λx, by rw [ show (option.cons x v) ∘ (cons none some) = x :: v, from funext $ λs, by cases s with a b; refl] theorem dioph_fn_vec {n} (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph (λv : vector3 ℕ (succ n), f (v ∘ fs) = v fz) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_pfun_vec {n} (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph (λv : vector3 ℕ (succ n), f.graph (v ∘ fs, v fz)) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_fn_compn {α : Type} : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f), dioph (λv : α → ℕ, S (v ⊗ λi, f i v)) | 0 S d f := λdf, ext (reindex_dioph d (id ⊗ fin2.elim0)) $ λv, by refine eq.to_iff (congr_arg S $ funext $ λs, _); {cases s with a b, refl, cases b} | (succ n) S d f := f.cons_elim $ λf fl, by simp; exact λ df dfl, have dioph (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)), from ext (dioph_fn_comp1 (reindex_dioph d (some ∘ inl ⊗ none :: some ∘ inr)) (reindex_dioph_fn df inl)) $ λv, by {refine eq.to_iff (congr_arg S $ funext $ λs, _); cases s with a b, refl, cases b; refl}, have dioph (λv, S (v ⊗ f v :: λ (i : fin2 n), fl i v)), from @dioph_fn_compn n (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl, ext this $ λv, by rw [ show cons (f v) (λ (i : fin2 n), fl i v) = λ (i : fin2 (succ n)), (f :: fl) i v, from funext $ λs, by cases s with a b; refl] theorem dioph_comp {n} {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph (λv, S (λi, f i v)) := dioph_fn_compn (reindex_dioph d inr) df theorem dioph_fn_comp {n} {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn (λv, f (λi, g i v)) := dioph_comp ((dioph_fn_vec _).1 df) ((λv, v none) :: λi v, g i (v ∘ some)) $ by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λi, reindex_dioph_fn ((vector_allp_iff_forall _ _).1 dg _) _⟩ localized "notation x ` D∧ `:35 y := dioph.and_dioph x y" in dioph localized "notation x ` D∨ `:35 y := dioph.or_dioph x y" in dioph localized "notation `D∃`:30 := dioph.vec_ex1_dioph" in dioph localized "prefix `&`:max := of_nat'" in dioph theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λv : vector3 ℕ n, v &m) := proj_dioph &m localized "prefix `D&`:100 := dioph.proj_dioph_of_nat" in dioph theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) := abs_poly_dioph (poly.const n) localized "prefix `D.`:100 := dioph.const_dioph" in dioph variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) include df dg theorem dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λv:vector3 ℕ 2, S (v &0) (v &1))) : dioph (λv, S (f v) (g v)) := dioph_comp d [f, g] (by exact ⟨df, dg⟩) theorem dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λv:vector3 ℕ 2, h (v &0) (v &1))) : dioph_fn (λv, h (f v) (g v)) := dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩) theorem eq_dioph : dioph (λv, f v = g v) := dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1) (λv, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans ⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩) localized "infix ` D= `:50 := dioph.eq_dioph" in dioph theorem add_dioph : dioph_fn (λv, f v + g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1) localized "infix ` D+ `:80 := dioph.add_dioph" in dioph theorem mul_dioph : dioph_fn (λv, f v * g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1) localized "infix ` D* `:90 := dioph.mul_dioph" in dioph theorem le_dioph : dioph (λv, f v ≤ g v) := dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λv, ⟨λ⟨x, hx⟩, le.intro hx, le.dest⟩) localized "infix ` D≤ `:50 := dioph.le_dioph" in dioph theorem lt_dioph : dioph (λv, f v < g v) := df D+ (D. 1) D≤ dg localized "infix ` D< `:50 := dioph.lt_dioph" in dioph theorem ne_dioph : dioph (λv, f v ≠ g v) := ext (df D< dg D∨ dg D< df) $ λv, ne_iff_lt_or_gt.symm localized "infix ` D≠ `:50 := dioph.ne_dioph" in dioph theorem sub_dioph : dioph_fn (λv, f v - g v) := dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λx y z, show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from ⟨λo, begin rcases o with ae | ⟨yz, x0⟩, { rw [ae, nat.add_sub_cancel] }, { rw [x0, nat.sub_eq_zero_of_le yz] } end, λh, begin subst x, cases le_total y z with yz zy, { exact or.inr ⟨yz, nat.sub_eq_zero_of_le yz⟩ }, { exact or.inl (nat.sub_add_cancel zy).symm }, end⟩ localized "infix ` D- `:80 := dioph.sub_dioph" in dioph theorem dvd_dioph : dioph (λv, f v ∣ g v) := dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩) localized "infix ` D∣ `:50 := dioph.dvd_dioph" in dioph theorem mod_dioph : dioph_fn (λv, f v % g v) := have dioph (λv : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1), from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from ⟨λ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end, λe, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λh, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _⟩⟩ localized "infix ` D% `:80 := dioph.mod_dioph" in dioph theorem modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λv, f v ≡ g v [MOD h v]) := df D% dh D= dg D% dh localized "notation `D≡` := dioph.modeq_dioph" in dioph theorem div_dioph : dioph_fn (λv, f v / g v) := have dioph (λv : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2), from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2, dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z, by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim (λy0, by rw [y0, nat.div_zero]; exact ⟨λo, (o.resolve_right $ λ⟨_, h2⟩, not_lt_zero _ h2).right, λz0, or.inl ⟨rfl, z0⟩⟩) (λypos, iff.trans ⟨λo, o.resolve_left $ λ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩ (le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $ iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul _ _ ypos)).symm) localized "infix ` D/ `:80 := dioph.div_dioph" in dioph omit df dg open pell theorem pell_dioph : dioph (λv:vector3 ℕ 4, ∃ h : 1 < v &0, xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) := have dioph {v : vector3 ℕ 4 | 1 < v &0 ∧ v &1 ≤ v &3 ∧ (v &2 = 1 ∧ v &3 = 0 ∨ ∃ (u w s t b : ℕ), v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧ u * u - (v &0 * v &0 - 1) * w * w = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧ 0 < w ∧ v &3 * v &3 ∣ w ∧ (s ≡ v &2 [MOD u]) ∧ (t ≡ v &1 [MOD 4 * v &3]))}, from D.1 D< D&0 D∧ D&1 D≤ D&3 D∧ ((D&2 D= D.1 D∧ D&3 D= D.0) D∨ (D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧ D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧ D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧ D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧ D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧ (D≡ (D&2) (D&7) D&4) D∧ (D≡ (D&1) (D&6) (D.4 D* D&8)))), dioph.ext this $ λv, matiyasevic.symm theorem xn_dioph : dioph_pfun (λv:vector3 ℕ 2, ⟨1 < v &0, λh, xn h (v &1)⟩) := have dioph (λv:vector3 ℕ 3, ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from let D_pell := @reindex_dioph _ (fin2 4) _ pell_dioph [&2, &3, &1, &0] in D∃3 D_pell, (dioph_pfun_vec _).2 $ dioph.ext this $ λv, ⟨λ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩ include df dg /-- A version of **Matiyasevic's theorem** -/ theorem pow_dioph : dioph_fn (λv, f v ^ g v) := have dioph {v : vector3 ℕ 3 | v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧ (v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧ ∃ (w a t z x y : ℕ), (∃ (a1 : 1 < a), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧ (x ≡ y * (a - v &1) + v &0 [MOD t]) ∧ 2 * a * v &1 = t + (v &1 * v &1 + 1) ∧ v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from let D_pell := @reindex_dioph _ (fin2 9) _ pell_dioph [&4, &8, &1, &0] in (D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧ ((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧ (D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧ (D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧ D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧ D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧ D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λv, iff.symm $ eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $ ⟨λ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩, λ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩ end end dioph
eb9493e1a4cafccd99eb1d28c45cb420433b46d0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/nat/sub_elim_auto.lean
06bf551f34f4da3647ce2ad997aeb7cb718b8e85
[]
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
3,041
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.nat.form import Mathlib.PostPort namespace Mathlib /- Subtraction elimination for linear natural number arithmetic. Works by repeatedly rewriting goals of the preform `P[t-s]` into `P[x] ∧ (t = s + x ∨ (t ≤ s ∧ x = 0))`, where `x` is fresh. -/ namespace omega namespace nat namespace preterm /-- Find subtraction inside preterm and return its operands -/ def sub_terms : preterm → Option (preterm × preterm) := sorry /-- Find (t - s) inside a preterm and replace it with variable k -/ def sub_subst (t : preterm) (s : preterm) (k : ℕ) : preterm → preterm := sorry theorem val_sub_subst {k : ℕ} {x : preterm} {y : preterm} {v : ℕ → ℕ} {t : preterm} : fresh_index t ≤ k → val (update k (val v x - val v y) v) (sub_subst x y k t) = val v t := sorry end preterm namespace preform /-- Find subtraction inside preform and return its operands -/ def sub_terms : preform → Option (preterm × preterm) := sorry /-- Find (t - s) inside a preform and replace it with variable k -/ @[simp] def sub_subst (x : preterm) (y : preterm) (k : ℕ) : preform → preform := sorry end preform /-- Preform which asserts that the value of variable k is the truncated difference between preterms t and s -/ def is_diff (t : preterm) (s : preterm) (k : ℕ) : preform := preform.or (preform.eq t (preterm.add s (preterm.var 1 k))) (preform.and (preform.le t s) (preform.eq (preterm.var 1 k) (preterm.cst 0))) theorem holds_is_diff {t : preterm} {s : preterm} {k : ℕ} {v : ℕ → ℕ} : v k = preterm.val v t - preterm.val v s → preform.holds v (is_diff t s k) := sorry /-- Helper function for sub_elim -/ def sub_elim_core (t : preterm) (s : preterm) (k : ℕ) (p : preform) : preform := preform.and (preform.sub_subst t s k p) (is_diff t s k) /-- Return de Brujin index of fresh variable that does not occur in any of the arguments -/ def sub_fresh_index (t : preterm) (s : preterm) (p : preform) : ℕ := max (preform.fresh_index p) (max (preterm.fresh_index t) (preterm.fresh_index s)) /-- Return a new preform with all subtractions eliminated -/ def sub_elim (t : preterm) (s : preterm) (p : preform) : preform := sub_elim_core t s (sub_fresh_index t s p) p theorem sub_subst_equiv {k : ℕ} {x : preterm} {y : preterm} {v : ℕ → ℕ} (p : preform) : preform.fresh_index p ≤ k → (preform.holds (update k (preterm.val v x - preterm.val v y) v) (preform.sub_subst x y k p) ↔ preform.holds v p) := sorry theorem sat_sub_elim {t : preterm} {s : preterm} {p : preform} : preform.sat p → preform.sat (sub_elim t s p) := sorry theorem unsat_of_unsat_sub_elim (t : preterm) (s : preterm) (p : preform) : preform.unsat (sub_elim t s p) → preform.unsat p := mt sat_sub_elim end Mathlib
7f7998927592a946a56f14a4e9f0cc12319088f2
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/normed/group/SemiNormedGroup/kernels.lean
1769c78efedd539646942129455b6f1902bee639
[ "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
13,097
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca, Johan Commelin, Scott Morrison -/ import analysis.normed.group.SemiNormedGroup import analysis.normed.group.quotient import category_theory.limits.shapes.kernels /-! # Kernels and cokernels in SemiNormedGroup₁ and SemiNormedGroup We show that `SemiNormedGroup₁` has cokernels (for which of course the `cokernel.π f` maps are norm non-increasing), as well as the easier result that `SemiNormedGroup` has cokernels. We also show that `SemiNormedGroup` has kernels. So far, I don't see a way to state nicely what we really want: `SemiNormedGroup` has cokernels, and `cokernel.π f` is norm non-increasing. The problem is that the limits API doesn't promise you any particular model of the cokernel, and in `SemiNormedGroup` one can always take a cokernel and rescale its norm (and hence making `cokernel.π f` arbitrarily large in norm), obtaining another categorical cokernel. -/ open category_theory category_theory.limits universe u namespace SemiNormedGroup₁ noncomputable theory /-- Auxiliary definition for `has_cokernels SemiNormedGroup₁`. -/ def cokernel_cocone {X Y : SemiNormedGroup₁.{u}} (f : X ⟶ Y) : cofork f 0 := cofork.of_π (@SemiNormedGroup₁.mk_hom _ (SemiNormedGroup.of (Y ⧸ (normed_group_hom.range f.1))) f.1.range.normed_mk (normed_group_hom.is_quotient_quotient _).norm_le) begin ext, simp only [comp_apply, limits.zero_comp, normed_group_hom.zero_apply, SemiNormedGroup₁.mk_hom_apply, SemiNormedGroup₁.zero_apply, ←normed_group_hom.mem_ker, f.1.range.ker_normed_mk, f.1.mem_range], use x, refl, end /-- Auxiliary definition for `has_cokernels SemiNormedGroup₁`. -/ def cokernel_lift {X Y : SemiNormedGroup₁.{u}} (f : X ⟶ Y) (s : cokernel_cofork f) : (cokernel_cocone f).X ⟶ s.X := begin fsplit, -- The lift itself: { apply normed_group_hom.lift _ s.π.1, rintro _ ⟨b, rfl⟩, change (f ≫ s.π) b = 0, simp, }, -- The lift has norm at most one: exact normed_group_hom.lift_norm_noninc _ _ _ s.π.2, end instance : has_cokernels SemiNormedGroup₁.{u} := { has_colimit := λ X Y f, has_colimit.mk { cocone := cokernel_cocone f, is_colimit := is_colimit_aux _ (cokernel_lift f) (λ s, begin ext, apply normed_group_hom.lift_mk f.1.range, rintro _ ⟨b, rfl⟩, change (f ≫ s.π) b = 0, simp, end) (λ s m w, subtype.eq (normed_group_hom.lift_unique f.1.range _ _ _ (congr_arg subtype.val w : _))), } } -- Sanity check example : has_cokernels SemiNormedGroup₁ := by apply_instance end SemiNormedGroup₁ namespace SemiNormedGroup section equalizers_and_kernels /-- The equalizer cone for a parallel pair of morphisms of seminormed groups. -/ def parallel_pair_cone {V W : SemiNormedGroup.{u}} (f g : V ⟶ W) : cone (parallel_pair f g) := @fork.of_ι _ _ _ _ _ _ (of (f - g).ker) (normed_group_hom.incl (f - g).ker) $ begin ext v, have : v.1 ∈ (f - g).ker := v.2, simpa only [normed_group_hom.incl_apply, pi.zero_apply, coe_comp, normed_group_hom.coe_zero, subtype.val_eq_coe, normed_group_hom.mem_ker, normed_group_hom.coe_sub, pi.sub_apply, sub_eq_zero] using this end instance has_limit_parallel_pair {V W : SemiNormedGroup.{u}} (f g : V ⟶ W) : has_limit (parallel_pair f g) := { exists_limit := nonempty.intro { cone := parallel_pair_cone f g, is_limit := fork.is_limit.mk _ (λ c, normed_group_hom.ker.lift (fork.ι c) _ $ show normed_group_hom.comp_hom (f - g) c.ι = 0, by { rw [add_monoid_hom.map_sub, add_monoid_hom.sub_apply, sub_eq_zero], exact c.condition }) (λ c, normed_group_hom.ker.incl_comp_lift _ _ _) (λ c g h, by { ext x, dsimp, rw ← h, refl }) } } instance : limits.has_equalizers.{u (u+1)} SemiNormedGroup := @has_equalizers_of_has_limit_parallel_pair SemiNormedGroup _ $ λ V W f g, SemiNormedGroup.has_limit_parallel_pair f g end equalizers_and_kernels section cokernel -- PROJECT: can we reuse the work to construct cokernels in `SemiNormedGroup₁` here? -- I don't see a way to do this that is less work than just repeating the relevant parts. /-- Auxiliary definition for `has_cokernels SemiNormedGroup`. -/ def cokernel_cocone {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : cofork f 0 := @cofork.of_π _ _ _ _ _ _ (SemiNormedGroup.of (Y ⧸ (normed_group_hom.range f))) f.range.normed_mk begin ext, simp only [comp_apply, limits.zero_comp, normed_group_hom.zero_apply, ←normed_group_hom.mem_ker, f.range.ker_normed_mk, f.mem_range, exists_apply_eq_apply], end /-- Auxiliary definition for `has_cokernels SemiNormedGroup`. -/ def cokernel_lift {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) (s : cokernel_cofork f) : (cokernel_cocone f).X ⟶ s.X := normed_group_hom.lift _ s.π begin rintro _ ⟨b, rfl⟩, change (f ≫ s.π) b = 0, simp, end /-- Auxiliary definition for `has_cokernels SemiNormedGroup`. -/ def is_colimit_cokernel_cocone {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : is_colimit (cokernel_cocone f) := is_colimit_aux _ (cokernel_lift f) (λ s, begin ext, apply normed_group_hom.lift_mk f.range, rintro _ ⟨b, rfl⟩, change (f ≫ s.π) b = 0, simp, end) (λ s m w, normed_group_hom.lift_unique f.range _ _ _ w) instance : has_cokernels SemiNormedGroup.{u} := { has_colimit := λ X Y f, has_colimit.mk { cocone := cokernel_cocone f, is_colimit := is_colimit_cokernel_cocone f } } -- Sanity check example : has_cokernels SemiNormedGroup := by apply_instance section explicit_cokernel /-- An explicit choice of cokernel, which has good properties with respect to the norm. -/ def explicit_cokernel {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : SemiNormedGroup.{u} := (cokernel_cocone f).X /-- Descend to the explicit cokernel. -/ def explicit_cokernel_desc {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) : explicit_cokernel f ⟶ Z := (is_colimit_cokernel_cocone f).desc (cofork.of_π g (by simp [w])) /-- The projection from `Y` to the explicit cokernel of `X ⟶ Y`. -/ def explicit_cokernel_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : Y ⟶ explicit_cokernel f := (cokernel_cocone f).ι.app walking_parallel_pair.one lemma explicit_cokernel_π_surjective {X Y : SemiNormedGroup.{u}} {f : X ⟶ Y} : function.surjective (explicit_cokernel_π f) := surjective_quot_mk _ @[simp, reassoc] lemma comp_explicit_cokernel_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : f ≫ explicit_cokernel_π f = 0 := begin convert (cokernel_cocone f).w walking_parallel_pair_hom.left, simp, end @[simp] lemma explicit_cokernel_π_apply_dom_eq_zero {X Y : SemiNormedGroup.{u}} {f : X ⟶ Y} (x : X) : (explicit_cokernel_π f) (f x) = 0 := show (f ≫ (explicit_cokernel_π f)) x = 0, by { rw [comp_explicit_cokernel_π], refl } @[simp, reassoc] lemma explicit_cokernel_π_desc {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) : explicit_cokernel_π f ≫ explicit_cokernel_desc w = g := (is_colimit_cokernel_cocone f).fac _ _ @[simp] lemma explicit_cokernel_π_desc_apply {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} {cond : f ≫ g = 0} (x : Y) : explicit_cokernel_desc cond (explicit_cokernel_π f x) = g x := show (explicit_cokernel_π f ≫ explicit_cokernel_desc cond) x = g x, by rw explicit_cokernel_π_desc lemma explicit_cokernel_desc_unique {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) (e : explicit_cokernel f ⟶ Z) (he : explicit_cokernel_π f ≫ e = g) : e = explicit_cokernel_desc w := begin apply (is_colimit_cokernel_cocone f).uniq (cofork.of_π g (by simp [w])), rintro (_|_), { convert w.symm, simp }, { exact he } end lemma explicit_cokernel_desc_comp_eq_desc {X Y Z W : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} {h : Z ⟶ W} {cond : f ≫ g = 0} : explicit_cokernel_desc cond ≫ h = explicit_cokernel_desc (show f ≫ (g ≫ h) = 0, by rw [← category_theory.category.assoc, cond, limits.zero_comp]) := begin refine explicit_cokernel_desc_unique _ _ _, rw [← category_theory.category.assoc, explicit_cokernel_π_desc] end @[simp] lemma explicit_cokernel_desc_zero {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} : explicit_cokernel_desc (show f ≫ (0 : Y ⟶ Z) = 0, from category_theory.limits.comp_zero) = 0 := eq.symm $ explicit_cokernel_desc_unique _ _ category_theory.limits.comp_zero @[ext] lemma explicit_cokernel_hom_ext {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} (e₁ e₂ : explicit_cokernel f ⟶ Z) (h : explicit_cokernel_π f ≫ e₁ = explicit_cokernel_π f ≫ e₂) : e₁ = e₂ := begin let g : Y ⟶ Z := explicit_cokernel_π f ≫ e₂, have w : f ≫ g = 0, by simp, have : e₂ = explicit_cokernel_desc w, { apply explicit_cokernel_desc_unique, refl }, rw this, apply explicit_cokernel_desc_unique, exact h, end instance explicit_cokernel_π.epi {X Y : SemiNormedGroup.{u}} {f : X ⟶ Y} : epi (explicit_cokernel_π f) := begin constructor, intros Z g h H, ext x, obtain ⟨x, hx⟩ := explicit_cokernel_π_surjective (explicit_cokernel_π f x), change (explicit_cokernel_π f ≫ g) _ = _, rw [H] end lemma is_quotient_explicit_cokernel_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : normed_group_hom.is_quotient (explicit_cokernel_π f) := normed_group_hom.is_quotient_quotient _ lemma norm_noninc_explicit_cokernel_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : (explicit_cokernel_π f).norm_noninc := (is_quotient_explicit_cokernel_π f).norm_le open_locale nnreal lemma explicit_cokernel_desc_norm_le_of_norm_le {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) (c : ℝ≥0) (h : ∥ g ∥ ≤ c) : ∥ explicit_cokernel_desc w ∥ ≤ c := normed_group_hom.lift_norm_le _ _ _ h lemma explicit_cokernel_desc_norm_noninc {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} {cond : f ≫ g = 0} (hg : g.norm_noninc) : (explicit_cokernel_desc cond).norm_noninc := begin refine normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.2 _, rw [← nnreal.coe_one], exact explicit_cokernel_desc_norm_le_of_norm_le cond 1 (normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.1 hg) end lemma explicit_cokernel_desc_comp_eq_zero {X Y Z W : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} {h : Z ⟶ W} (cond : f ≫ g = 0) (cond2 : g ≫ h = 0) : explicit_cokernel_desc cond ≫ h = 0 := begin rw [← cancel_epi (explicit_cokernel_π f), ← category.assoc, explicit_cokernel_π_desc], simp [cond2] end lemma explicit_cokernel_desc_norm_le {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) : ∥ explicit_cokernel_desc w ∥ ≤ ∥ g ∥ := explicit_cokernel_desc_norm_le_of_norm_le w ∥ g ∥₊ le_rfl /-- The explicit cokernel is isomorphic to the usual cokernel. -/ def explicit_cokernel_iso {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : explicit_cokernel f ≅ cokernel f := (is_colimit_cokernel_cocone f).cocone_point_unique_up_to_iso (colimit.is_colimit _) @[simp] lemma explicit_cokernel_iso_hom_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : explicit_cokernel_π f ≫ (explicit_cokernel_iso f).hom = cokernel.π _ := by simp [explicit_cokernel_π, explicit_cokernel_iso] @[simp] lemma explicit_cokernel_iso_inv_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : cokernel.π f ≫ (explicit_cokernel_iso f).inv = explicit_cokernel_π f := by simp [explicit_cokernel_π, explicit_cokernel_iso] @[simp] lemma explicit_cokernel_iso_hom_desc {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) : (explicit_cokernel_iso f).hom ≫ cokernel.desc f g w = explicit_cokernel_desc w := begin ext1, simp [explicit_cokernel_desc, explicit_cokernel_π, explicit_cokernel_iso], end /-- A special case of `category_theory.limits.cokernel.map` adapted to `explicit_cokernel`. -/ noncomputable def explicit_cokernel.map {A B C D : SemiNormedGroup.{u}} {fab : A ⟶ B} {fbd : B ⟶ D} {fac : A ⟶ C} {fcd : C ⟶ D} (h : fab ≫ fbd = fac ≫ fcd) : explicit_cokernel fab ⟶ explicit_cokernel fcd := @explicit_cokernel_desc _ _ _ fab (fbd ≫ explicit_cokernel_π _) $ by simp [reassoc_of h] /-- A special case of `category_theory.limits.cokernel.map_desc` adapted to `explicit_cokernel`. -/ lemma explicit_coker.map_desc {A B C D B' D' : SemiNormedGroup.{u}} {fab : A ⟶ B} {fbd : B ⟶ D} {fac : A ⟶ C} {fcd : C ⟶ D} {h : fab ≫ fbd = fac ≫ fcd} {fbb' : B ⟶ B'} {fdd' : D ⟶ D'} {condb : fab ≫ fbb' = 0} {condd : fcd ≫ fdd' = 0} {g : B' ⟶ D'} (h' : fbb' ≫ g = fbd ≫ fdd'): explicit_cokernel_desc condb ≫ g = explicit_cokernel.map h ≫ explicit_cokernel_desc condd := begin delta explicit_cokernel.map, simp [← cancel_epi (explicit_cokernel_π fab), category.assoc, explicit_cokernel_π_desc, h'] end end explicit_cokernel end cokernel end SemiNormedGroup
d3e0ded80a4adb09fa6bb185e95738fb72001b0c
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/closure_bug2.lean
0a027e06054b5b20c856d9c86f43eebd327713be
[ "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
555
lean
def f (x : Nat) : Nat × (Nat → String) := let x1 := x + 1; let x2 := x + 2; let x3 := x + 3; let x4 := x + 4; let x5 := x + 5; let x6 := x + 6; let x7 := x + 7; let x8 := x + 8; let x9 := x + 9; let x10 := x + 10; let x11 := x + 11; let x12 := x + 12; let x13 := x + 13; let x14 := x + 14; let x15 := x + 15; let x16 := x + 16; let x17 := x + 17; (x, fun y => toString [x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17]) def main (xs : List String) : IO Unit := IO.println ((f (xs.headD "0").toNat!).2 (xs.headD "0").toNat!)
fdc3fbeb478ddbf76d0458609397ad592865204b
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/nilpotent.lean
77c70116bfa646e0d170d80f65e6f8e05a328ebd
[ "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
37,956
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Ines Wright, Joachim Breitner -/ import group_theory.quotient_group import group_theory.solvable import group_theory.p_group import group_theory.sylow import data.nat.factorization import tactic.tfae /-! # Nilpotent groups An API for nilpotent groups, that is, groups for which the upper central series reaches `⊤`. ## Main definitions Recall that if `H K : subgroup G` then `⁅H, K⁆ : subgroup G` is the subgroup of `G` generated by the commutators `hkh⁻¹k⁻¹`. Recall also Lean's conventions that `⊤` denotes the subgroup `G` of `G`, and `⊥` denotes the trivial subgroup `{1}`. * `upper_central_series G : ℕ → subgroup G` : the upper central series of a group `G`. This is an increasing sequence of normal subgroups `H n` of `G` with `H 0 = ⊥` and `H (n + 1) / H n` is the centre of `G / H n`. * `lower_central_series G : ℕ → subgroup G` : the lower central series of a group `G`. This is a decreasing sequence of normal subgroups `H n` of `G` with `H 0 = ⊤` and `H (n + 1) = ⁅H n, G⁆`. * `is_nilpotent` : A group G is nilpotent if its upper central series reaches `⊤`, or equivalently if its lower central series reaches `⊥`. * `nilpotency_class` : the length of the upper central series of a nilpotent group. * `is_ascending_central_series (H : ℕ → subgroup G) : Prop` and * `is_descending_central_series (H : ℕ → subgroup G) : Prop` : Note that in the literature a "central series" for a group is usually defined to be a *finite* sequence of normal subgroups `H 0`, `H 1`, ..., starting at `⊤`, finishing at `⊥`, and with each `H n / H (n + 1)` central in `G / H (n + 1)`. In this formalisation it is convenient to have two weaker predicates on an infinite sequence of subgroups `H n` of `G`: we say a sequence is a *descending central series* if it starts at `G` and `⁅H n, ⊤⁆ ⊆ H (n + 1)` for all `n`. Note that this series may not terminate at `⊥`, and the `H i` need not be normal. Similarly a sequence is an *ascending central series* if `H 0 = ⊥` and `⁅H (n + 1), ⊤⁆ ⊆ H n` for all `n`, again with no requirement that the series reaches `⊤` or that the `H i` are normal. ## Main theorems `G` is *defined* to be nilpotent if the upper central series reaches `⊤`. * `nilpotent_iff_finite_ascending_central_series` : `G` is nilpotent iff some ascending central series reaches `⊤`. * `nilpotent_iff_finite_descending_central_series` : `G` is nilpotent iff some descending central series reaches `⊥`. * `nilpotent_iff_lower` : `G` is nilpotent iff the lower central series reaches `⊥`. * The `nilpotency_class` can likeways be obtained from these equivalent definitions, see `least_ascending_central_series_length_eq_nilpotency_class`, `least_descending_central_series_length_eq_nilpotency_class` and `lower_central_series_length_eq_nilpotency_class`. * If `G` is nilpotent, then so are its subgroups, images, quotients and preimages. Binary and finite products of nilpotent groups are nilpotent. Infinite products are nilpotent if their nilpotent class is bounded. Corresponding lemmas about the `nilpotency_class` are provided. * The `nilpotency_class` of `G ⧸ center G` is given explicitly, and an induction principle is derived from that. * `is_nilpotent.to_is_solvable`: If `G` is nilpotent, it is solvable. ## Warning A "central series" is usually defined to be a finite sequence of normal subgroups going from `⊥` to `⊤` with the property that each subquotient is contained within the centre of the associated quotient of `G`. This means that if `G` is not nilpotent, then none of what we have called `upper_central_series G`, `lower_central_series G` or the sequences satisfying `is_ascending_central_series` or `is_descending_central_series` are actually central series. Note that the fact that the upper and lower central series are not central series if `G` is not nilpotent is a standard abuse of notation. -/ open subgroup section with_group variables {G : Type*} [group G] (H : subgroup G) [normal H] /-- If `H` is a normal subgroup of `G`, then the set `{x : G | ∀ y : G, x*y*x⁻¹*y⁻¹ ∈ H}` is a subgroup of `G` (because it is the preimage in `G` of the centre of the quotient group `G/H`.) -/ def upper_central_series_step : subgroup G := { carrier := {x : G | ∀ y : G, x * y * x⁻¹ * y⁻¹ ∈ H}, one_mem' := λ y, by simp [subgroup.one_mem], mul_mem' := λ a b ha hb y, begin convert subgroup.mul_mem _ (ha (b * y * b⁻¹)) (hb y) using 1, group, end, inv_mem' := λ x hx y, begin specialize hx y⁻¹, rw [mul_assoc, inv_inv] at ⊢ hx, exact subgroup.normal.mem_comm infer_instance hx, end } lemma mem_upper_central_series_step (x : G) : x ∈ upper_central_series_step H ↔ ∀ y, x * y * x⁻¹ * y⁻¹ ∈ H := iff.rfl open quotient_group /-- The proof that `upper_central_series_step H` is the preimage of the centre of `G/H` under the canonical surjection. -/ lemma upper_central_series_step_eq_comap_center : upper_central_series_step H = subgroup.comap (mk' H) (center (G ⧸ H)) := begin ext, rw [mem_comap, mem_center_iff, forall_coe], apply forall_congr, intro y, rw [coe_mk', ←quotient_group.coe_mul, ←quotient_group.coe_mul, eq_comm, eq_iff_div_mem, div_eq_mul_inv, mul_inv_rev, mul_assoc], end instance : normal (upper_central_series_step H) := begin rw upper_central_series_step_eq_comap_center, apply_instance, end variable (G) /-- An auxiliary type-theoretic definition defining both the upper central series of a group, and a proof that it is normal, all in one go. -/ def upper_central_series_aux : ℕ → Σ' (H : subgroup G), normal H | 0 := ⟨⊥, infer_instance⟩ | (n + 1) := let un := upper_central_series_aux n, un_normal := un.2 in by exactI ⟨upper_central_series_step un.1, infer_instance⟩ /-- `upper_central_series G n` is the `n`th term in the upper central series of `G`. -/ def upper_central_series (n : ℕ) : subgroup G := (upper_central_series_aux G n).1 instance (n : ℕ) : normal (upper_central_series G n) := (upper_central_series_aux G n).2 @[simp] lemma upper_central_series_zero : upper_central_series G 0 = ⊥ := rfl @[simp] lemma upper_central_series_one : upper_central_series G 1 = center G := begin ext, simp only [upper_central_series, upper_central_series_aux, upper_central_series_step, center, set.center, mem_mk, mem_bot, set.mem_set_of_eq], exact forall_congr (λ y, by rw [mul_inv_eq_one, mul_inv_eq_iff_eq_mul, eq_comm]), end /-- The `n+1`st term of the upper central series `H i` has underlying set equal to the `x` such that `⁅x,G⁆ ⊆ H n`-/ lemma mem_upper_central_series_succ_iff (n : ℕ) (x : G) : x ∈ upper_central_series G (n + 1) ↔ ∀ y : G, x * y * x⁻¹ * y⁻¹ ∈ upper_central_series G n := iff.rfl -- is_nilpotent is already defined in the root namespace (for elements of rings). /-- A group `G` is nilpotent if its upper central series is eventually `G`. -/ class group.is_nilpotent (G : Type*) [group G] : Prop := (nilpotent [] : ∃ n : ℕ, upper_central_series G n = ⊤) open group variable {G} /-- A sequence of subgroups of `G` is an ascending central series if `H 0` is trivial and `⁅H (n + 1), G⁆ ⊆ H n` for all `n`. Note that we do not require that `H n = G` for some `n`. -/ def is_ascending_central_series (H : ℕ → subgroup G) : Prop := H 0 = ⊥ ∧ ∀ (x : G) (n : ℕ), x ∈ H (n + 1) → ∀ g, x * g * x⁻¹ * g⁻¹ ∈ H n /-- A sequence of subgroups of `G` is a descending central series if `H 0` is `G` and `⁅H n, G⁆ ⊆ H (n + 1)` for all `n`. Note that we do not requre that `H n = {1}` for some `n`. -/ def is_descending_central_series (H : ℕ → subgroup G) := H 0 = ⊤ ∧ ∀ (x : G) (n : ℕ), x ∈ H n → ∀ g, x * g * x⁻¹ * g⁻¹ ∈ H (n + 1) /-- Any ascending central series for a group is bounded above by the upper central series. -/ lemma ascending_central_series_le_upper (H : ℕ → subgroup G) (hH : is_ascending_central_series H) : ∀ n : ℕ, H n ≤ upper_central_series G n | 0 := hH.1.symm ▸ le_refl ⊥ | (n + 1) := begin intros x hx, rw mem_upper_central_series_succ_iff, exact λ y, ascending_central_series_le_upper n (hH.2 x n hx y), end variable (G) /-- The upper central series of a group is an ascending central series. -/ lemma upper_central_series_is_ascending_central_series : is_ascending_central_series (upper_central_series G) := ⟨rfl, λ x n h, h⟩ lemma upper_central_series_mono : monotone (upper_central_series G) := begin refine monotone_nat_of_le_succ _, intros n x hx y, rw [mul_assoc, mul_assoc, ← mul_assoc y x⁻¹ y⁻¹], exact mul_mem hx (normal.conj_mem (upper_central_series.subgroup.normal G n) x⁻¹ (inv_mem hx) y) end /-- A group `G` is nilpotent iff there exists an ascending central series which reaches `G` in finitely many steps. -/ theorem nilpotent_iff_finite_ascending_central_series : is_nilpotent G ↔ ∃ n : ℕ, ∃ H : ℕ → subgroup G, is_ascending_central_series H ∧ H n = ⊤ := begin split, { rintro ⟨n, nH⟩, refine ⟨_, _, upper_central_series_is_ascending_central_series G, nH⟩ }, { rintro ⟨n, H, hH, hn⟩, use n, rw [eq_top_iff, ←hn], exact ascending_central_series_le_upper H hH n } end lemma is_decending_rev_series_of_is_ascending {H: ℕ → subgroup G} {n : ℕ} (hn : H n = ⊤) (hasc : is_ascending_central_series H) : is_descending_central_series (λ (m : ℕ), H (n - m)) := begin cases hasc with h0 hH, refine ⟨hn, λ x m hx g, _⟩, dsimp at hx, by_cases hm : n ≤ m, { rw [tsub_eq_zero_of_le hm, h0, subgroup.mem_bot] at hx, subst hx, convert subgroup.one_mem _, group }, { push_neg at hm, apply hH, convert hx, rw [tsub_add_eq_add_tsub (nat.succ_le_of_lt hm), nat.succ_sub_succ] }, end lemma is_ascending_rev_series_of_is_descending {H: ℕ → subgroup G} {n : ℕ} (hn : H n = ⊥) (hdesc : is_descending_central_series H) : is_ascending_central_series (λ (m : ℕ), H (n - m)) := begin cases hdesc with h0 hH, refine ⟨hn, λ x m hx g, _⟩, dsimp only at hx ⊢, by_cases hm : n ≤ m, { have hnm : n - m = 0 := tsub_eq_zero_iff_le.mpr hm, rw [hnm, h0], exact mem_top _ }, { push_neg at hm, convert hH x _ hx g, rw [tsub_add_eq_add_tsub (nat.succ_le_of_lt hm), nat.succ_sub_succ] }, end /-- A group `G` is nilpotent iff there exists a descending central series which reaches the trivial group in a finite time. -/ theorem nilpotent_iff_finite_descending_central_series : is_nilpotent G ↔ ∃ n : ℕ, ∃ H : ℕ → subgroup G, is_descending_central_series H ∧ H n = ⊥ := begin rw nilpotent_iff_finite_ascending_central_series, split, { rintro ⟨n, H, hH, hn⟩, refine ⟨n, λ m, H (n - m), is_decending_rev_series_of_is_ascending G hn hH, _⟩, rw tsub_self, exact hH.1 }, { rintro ⟨n, H, hH, hn⟩, refine ⟨n, λ m, H (n - m), is_ascending_rev_series_of_is_descending G hn hH, _⟩, rw tsub_self, exact hH.1 }, end /-- The lower central series of a group `G` is a sequence `H n` of subgroups of `G`, defined by `H 0` is all of `G` and for `n≥1`, `H (n + 1) = ⁅H n, G⁆` -/ def lower_central_series (G : Type*) [group G] : ℕ → subgroup G | 0 := ⊤ | (n+1) := ⁅lower_central_series n, ⊤⁆ variable {G} @[simp] lemma lower_central_series_zero : lower_central_series G 0 = ⊤ := rfl @[simp] lemma lower_central_series_one : lower_central_series G 1 = commutator G := rfl lemma mem_lower_central_series_succ_iff (n : ℕ) (q : G) : q ∈ lower_central_series G (n + 1) ↔ q ∈ closure {x | ∃ (p ∈ lower_central_series G n) (q ∈ (⊤ : subgroup G)), p * q * p⁻¹ * q⁻¹ = x} := iff.rfl lemma lower_central_series_succ (n : ℕ) : lower_central_series G (n + 1) = closure {x | ∃ (p ∈ lower_central_series G n) (q ∈ (⊤ : subgroup G)), p * q * p⁻¹ * q⁻¹ = x} := rfl instance (n : ℕ) : normal (lower_central_series G n) := begin induction n with d hd, { exact (⊤ : subgroup G).normal_of_characteristic }, { exactI subgroup.commutator_normal (lower_central_series G d) ⊤ }, end lemma lower_central_series_antitone : antitone (lower_central_series G) := begin refine antitone_nat_of_succ_le (λ n x hx, _), simp only [mem_lower_central_series_succ_iff, exists_prop, mem_top, exists_true_left, true_and] at hx, refine closure_induction hx _ (subgroup.one_mem _) (@subgroup.mul_mem _ _ _) (@subgroup.inv_mem _ _ _), rintros y ⟨z, hz, a, ha⟩, rw [← ha, mul_assoc, mul_assoc, ← mul_assoc a z⁻¹ a⁻¹], exact mul_mem hz (normal.conj_mem (lower_central_series.subgroup.normal n) z⁻¹ (inv_mem hz) a) end /-- The lower central series of a group is a descending central series. -/ theorem lower_central_series_is_descending_central_series : is_descending_central_series (lower_central_series G) := begin split, refl, intros x n hxn g, exact commutator_mem_commutator hxn (mem_top g), end /-- Any descending central series for a group is bounded below by the lower central series. -/ lemma descending_central_series_ge_lower (H : ℕ → subgroup G) (hH : is_descending_central_series H) : ∀ n : ℕ, lower_central_series G n ≤ H n | 0 := hH.1.symm ▸ le_refl ⊤ | (n + 1) := commutator_le.mpr (λ x hx q _, hH.2 x n (descending_central_series_ge_lower n hx) q) /-- A group is nilpotent if and only if its lower central series eventually reaches the trivial subgroup. -/ theorem nilpotent_iff_lower_central_series : is_nilpotent G ↔ ∃ n, lower_central_series G n = ⊥ := begin rw nilpotent_iff_finite_descending_central_series, split, { rintro ⟨n, H, ⟨h0, hs⟩, hn⟩, use n, rw [eq_bot_iff, ←hn], exact descending_central_series_ge_lower H ⟨h0, hs⟩ n }, { rintro ⟨n, hn⟩, exact ⟨n, lower_central_series G, lower_central_series_is_descending_central_series, hn⟩ }, end section classical open_locale classical variables [hG : is_nilpotent G] include hG variable (G) /-- The nilpotency class of a nilpotent group is the smallest natural `n` such that the `n`'th term of the upper central series is `G`. -/ noncomputable def group.nilpotency_class : ℕ := nat.find (is_nilpotent.nilpotent G) variable {G} @[simp] lemma upper_central_series_nilpotency_class : upper_central_series G (group.nilpotency_class G) = ⊤ := nat.find_spec (is_nilpotent.nilpotent G) lemma upper_central_series_eq_top_iff_nilpotency_class_le {n : ℕ} : (upper_central_series G n = ⊤) ↔ (group.nilpotency_class G ≤ n) := begin split, { intro h, exact (nat.find_le h), }, { intro h, apply eq_top_iff.mpr, rw ← upper_central_series_nilpotency_class, exact (upper_central_series_mono _ h), } end /-- The nilpotency class of a nilpotent `G` is equal to the smallest `n` for which an ascending central series reaches `G` in its `n`'th term. -/ lemma least_ascending_central_series_length_eq_nilpotency_class : nat.find ((nilpotent_iff_finite_ascending_central_series G).mp hG) = group.nilpotency_class G := begin refine le_antisymm (nat.find_mono _) (nat.find_mono _), { intros n hn, exact ⟨upper_central_series G, upper_central_series_is_ascending_central_series G, hn ⟩, }, { rintros n ⟨H, ⟨hH, hn⟩⟩, rw [←top_le_iff, ←hn], exact ascending_central_series_le_upper H hH n, } end /-- The nilpotency class of a nilpotent `G` is equal to the smallest `n` for which the descending central series reaches `⊥` in its `n`'th term. -/ lemma least_descending_central_series_length_eq_nilpotency_class : nat.find ((nilpotent_iff_finite_descending_central_series G).mp hG) = group.nilpotency_class G := begin rw ← least_ascending_central_series_length_eq_nilpotency_class, refine le_antisymm (nat.find_mono _) (nat.find_mono _), { rintros n ⟨H, ⟨hH, hn⟩⟩, refine ⟨(λ m, H (n - m)), is_decending_rev_series_of_is_ascending G hn hH, _⟩, rw tsub_self, exact hH.1 }, { rintros n ⟨H, ⟨hH, hn⟩⟩, refine ⟨(λ m, H (n - m)), is_ascending_rev_series_of_is_descending G hn hH, _⟩, rw tsub_self, exact hH.1 }, end /-- The nilpotency class of a nilpotent `G` is equal to the length of the lower central series. -/ lemma lower_central_series_length_eq_nilpotency_class : nat.find (nilpotent_iff_lower_central_series.mp hG) = @group.nilpotency_class G _ _ := begin rw ← least_descending_central_series_length_eq_nilpotency_class, refine le_antisymm (nat.find_mono _) (nat.find_mono _), { rintros n ⟨H, ⟨hH, hn⟩⟩, rw [←le_bot_iff, ←hn], exact (descending_central_series_ge_lower H hH n), }, { rintros n h, exact ⟨lower_central_series G, ⟨lower_central_series_is_descending_central_series, h⟩⟩ }, end @[simp] lemma lower_central_series_nilpotency_class : lower_central_series G (group.nilpotency_class G) = ⊥ := begin rw ← lower_central_series_length_eq_nilpotency_class, exact (nat.find_spec (nilpotent_iff_lower_central_series.mp _)) end lemma lower_central_series_eq_bot_iff_nilpotency_class_le {n : ℕ} : (lower_central_series G n = ⊥) ↔ (group.nilpotency_class G ≤ n) := begin split, { intro h, rw ← lower_central_series_length_eq_nilpotency_class, exact (nat.find_le h), }, { intro h, apply eq_bot_iff.mpr, rw ← lower_central_series_nilpotency_class, exact (lower_central_series_antitone h), } end end classical lemma lower_central_series_map_subtype_le (H : subgroup G) (n : ℕ) : (lower_central_series H n).map H.subtype ≤ lower_central_series G n := begin induction n with d hd, { simp }, { rw [lower_central_series_succ, lower_central_series_succ, monoid_hom.map_closure], apply subgroup.closure_mono, rintros x1 ⟨x2, ⟨x3, hx3, x4, hx4, rfl⟩, rfl⟩, exact ⟨x3, (hd (mem_map.mpr ⟨x3, hx3, rfl⟩)), x4, by simp⟩ } end /-- A subgroup of a nilpotent group is nilpotent -/ instance subgroup.is_nilpotent (H : subgroup G) [hG : is_nilpotent G] : is_nilpotent H := begin rw nilpotent_iff_lower_central_series at *, rcases hG with ⟨n, hG⟩, use n, have := lower_central_series_map_subtype_le H n, simp only [hG, set_like.le_def, mem_map, forall_apply_eq_imp_iff₂, exists_imp_distrib] at this, exact eq_bot_iff.mpr (λ x hx, subtype.ext (this x hx)), end /-- A the nilpotency class of a subgroup is less or equal the the nilpotency class of the group -/ lemma subgroup.nilpotency_class_le (H : subgroup G) [hG : is_nilpotent G] : group.nilpotency_class H ≤ group.nilpotency_class G := begin repeat { rw ← lower_central_series_length_eq_nilpotency_class }, apply nat.find_mono, intros n hG, have := lower_central_series_map_subtype_le H n, simp only [hG, set_like.le_def, mem_map, forall_apply_eq_imp_iff₂, exists_imp_distrib] at this, exact eq_bot_iff.mpr (λ x hx, subtype.ext (this x hx)), end @[priority 100] instance is_nilpotent_of_subsingleton [subsingleton G] : is_nilpotent G := nilpotent_iff_lower_central_series.2 ⟨0, subsingleton.elim ⊤ ⊥⟩ lemma upper_central_series.map {H : Type*} [group H] {f : G →* H} (h : function.surjective f) (n : ℕ) : subgroup.map f (upper_central_series G n) ≤ upper_central_series H n := begin induction n with d hd, { simp }, { rintros _ ⟨x, hx : x ∈ upper_central_series G d.succ, rfl⟩ y', rcases h y' with ⟨y, rfl⟩, simpa using hd (mem_map_of_mem f (hx y)) } end lemma lower_central_series.map {H : Type*} [group H] (f : G →* H) (n : ℕ) : subgroup.map f (lower_central_series G n) ≤ lower_central_series H n := begin induction n with d hd, { simp [nat.nat_zero_eq_zero] }, { rintros a ⟨x, hx : x ∈ lower_central_series G d.succ, rfl⟩, refine closure_induction hx _ (by simp [f.map_one, subgroup.one_mem _]) (λ y z hy hz, by simp [monoid_hom.map_mul, subgroup.mul_mem _ hy hz]) (λ y hy, by simp [f.map_inv, subgroup.inv_mem _ hy]), rintros a ⟨y, hy, z, ⟨-, rfl⟩⟩, apply mem_closure.mpr, exact λ K hK, hK ⟨f y, hd (mem_map_of_mem f hy), by simp [commutator_element_def]⟩ } end lemma lower_central_series_succ_eq_bot {n : ℕ} (h : lower_central_series G n ≤ center G) : lower_central_series G (n + 1) = ⊥ := begin rw [lower_central_series_succ, closure_eq_bot_iff, set.subset_singleton_iff], rintro x ⟨y, hy1, z, ⟨⟩, rfl⟩, rw [mul_assoc, ←mul_inv_rev, mul_inv_eq_one, eq_comm], exact mem_center_iff.mp (h hy1) z, end /-- The preimage of a nilpotent group is nilpotent if the kernel of the homomorphism is contained in the center -/ lemma is_nilpotent_of_ker_le_center {H : Type*} [group H] (f : G →* H) (hf1 : f.ker ≤ center G) (hH : is_nilpotent H) : is_nilpotent G := begin rw nilpotent_iff_lower_central_series at *, rcases hH with ⟨n, hn⟩, use (n + 1), refine lower_central_series_succ_eq_bot (le_trans ((map_eq_bot_iff _).mp _) hf1), exact eq_bot_iff.mpr (hn ▸ (lower_central_series.map f n)), end lemma nilpotency_class_le_of_ker_le_center {H : Type*} [group H] (f : G →* H) (hf1 : f.ker ≤ center G) (hH : is_nilpotent H) : @group.nilpotency_class G _ (is_nilpotent_of_ker_le_center f hf1 hH) ≤ group.nilpotency_class H + 1 := begin rw ← lower_central_series_length_eq_nilpotency_class, apply nat.find_min', refine lower_central_series_succ_eq_bot (le_trans ((map_eq_bot_iff _).mp _) hf1), apply eq_bot_iff.mpr, apply (le_trans (lower_central_series.map f _)), simp only [lower_central_series_nilpotency_class, le_bot_iff], end /-- The range of a surjective homomorphism from a nilpotent group is nilpotent -/ lemma nilpotent_of_surjective {G' : Type*} [group G'] [h : is_nilpotent G] (f : G →* G') (hf : function.surjective f) : is_nilpotent G' := begin unfreezingI { rcases h with ⟨n, hn⟩ }, use n, apply eq_top_iff.mpr, calc ⊤ = f.range : symm (f.range_top_of_surjective hf) ... = subgroup.map f ⊤ : monoid_hom.range_eq_map _ ... = subgroup.map f (upper_central_series G n) : by rw hn ... ≤ upper_central_series G' n : upper_central_series.map hf n, end /-- The nilpotency class of the range of a surejctive homomorphism from a nilpotent group is less or equal the nilpotency class of the domain -/ lemma nilpotency_class_le_of_surjective {G' : Type*} [group G'] (f : G →* G') (hf : function.surjective f) [h : is_nilpotent G] : @group.nilpotency_class G' _ (nilpotent_of_surjective _ hf) ≤ group.nilpotency_class G := begin apply nat.find_mono, intros n hn, apply eq_top_iff.mpr, calc ⊤ = f.range : symm (f.range_top_of_surjective hf) ... = subgroup.map f ⊤ : monoid_hom.range_eq_map _ ... = subgroup.map f (upper_central_series G n) : by rw hn ... ≤ upper_central_series G' n : upper_central_series.map hf n, end /-- Nilpotency respects isomorphisms -/ lemma nilpotent_of_mul_equiv {G' : Type*} [group G'] [h : is_nilpotent G] (f : G ≃* G') : is_nilpotent G' := nilpotent_of_surjective f.to_monoid_hom (mul_equiv.surjective f) /-- A quotient of a nilpotent group is nilpotent -/ instance nilpotent_quotient_of_nilpotent (H : subgroup G) [H.normal] [h : is_nilpotent G] : is_nilpotent (G ⧸ H) := nilpotent_of_surjective _ (show function.surjective (quotient_group.mk' H), by tidy) /-- The nilpotency class of a quotient of `G` is less or equal the nilpotency class of `G` -/ lemma nilpotency_class_quotient_le (H : subgroup G) [H.normal] [h : is_nilpotent G] : group.nilpotency_class (G ⧸ H) ≤ group.nilpotency_class G := nilpotency_class_le_of_surjective _ _ -- This technical lemma helps with rewriting the subgroup, which occurs in indices private lemma comap_center_subst {H₁ H₂ : subgroup G} [normal H₁] [normal H₂] (h : H₁ = H₂) : comap (mk' H₁) (center (G ⧸ H₁)) = comap (mk' H₂) (center (G ⧸ H₂)) := by unfreezingI { subst h } lemma comap_upper_central_series_quotient_center (n : ℕ) : comap (mk' (center G)) (upper_central_series (G ⧸ center G) n) = upper_central_series G n.succ := begin induction n with n ih, { simp, }, { let Hn := upper_central_series (G ⧸ center G) n, calc comap (mk' (center G)) (upper_central_series_step Hn) = comap (mk' (center G)) (comap (mk' Hn) (center ((G ⧸ center G) ⧸ Hn))) : by rw upper_central_series_step_eq_comap_center ... = comap (mk' (comap (mk' (center G)) Hn)) (center (G ⧸ (comap (mk' (center G)) Hn))) : quotient_group.comap_comap_center ... = comap (mk' (upper_central_series G n.succ)) (center (G ⧸ upper_central_series G n.succ)) : comap_center_subst ih ... = upper_central_series_step (upper_central_series G n.succ) : symm (upper_central_series_step_eq_comap_center _), } end lemma nilpotency_class_zero_iff_subsingleton [is_nilpotent G] : group.nilpotency_class G = 0 ↔ subsingleton G := by simp [group.nilpotency_class, nat.find_eq_zero, subsingleton_iff_bot_eq_top] /-- Quotienting the `center G` reduces the nilpotency class by 1 -/ lemma nilpotency_class_quotient_center [hH : is_nilpotent G] : group.nilpotency_class (G ⧸ center G) = group.nilpotency_class G - 1 := begin generalize hn : group.nilpotency_class G = n, rcases n with rfl | n, { simp [nilpotency_class_zero_iff_subsingleton] at *, haveI := hn, apply_instance, }, { suffices : group.nilpotency_class (G ⧸ center G) = n, by simpa, apply le_antisymm, { apply upper_central_series_eq_top_iff_nilpotency_class_le.mp, apply (@comap_injective G _ _ _ (mk' (center G)) (surjective_quot_mk _)), rw [ comap_upper_central_series_quotient_center, comap_top, ← hn], exact upper_central_series_nilpotency_class, }, { apply le_of_add_le_add_right, calc n + 1 = n.succ : rfl ... = group.nilpotency_class G : symm hn ... ≤ group.nilpotency_class (G ⧸ center G) + 1 : nilpotency_class_le_of_ker_le_center _ (le_of_eq (ker_mk _)) _, } } end /-- The nilpotency class of a non-trivial group is one more than its quotient by the center -/ lemma nilpotency_class_eq_quotient_center_plus_one [hH : is_nilpotent G] [nontrivial G] : group.nilpotency_class G = group.nilpotency_class (G ⧸ center G) + 1 := begin rw nilpotency_class_quotient_center, rcases h : group.nilpotency_class G, { exfalso, rw nilpotency_class_zero_iff_subsingleton at h, resetI, apply (false_of_nontrivial_of_subsingleton G), }, { simp } end /-- If the quotient by `center G` is nilpotent, then so is G. -/ lemma of_quotient_center_nilpotent (h : is_nilpotent (G ⧸ center G)) : is_nilpotent G := begin obtain ⟨n, hn⟩ := h.nilpotent, use n.succ, simp [← comap_upper_central_series_quotient_center, hn], end /-- A custom induction principle for nilpotent groups. The base case is a trivial group (`subsingleton G`), and in the induction step, one can assume the hypothesis for the group quotiented by its center. -/ @[elab_as_eliminator] lemma nilpotent_center_quotient_ind {P : Π G [group G], by exactI ∀ [is_nilpotent G], Prop} (G : Type*) [group G] [is_nilpotent G] (hbase : ∀ G [group G] [subsingleton G], by exactI P G) (hstep : ∀ G [group G], by exactI ∀ [is_nilpotent G], by exactI ∀ (ih : P (G ⧸ center G)), P G) : P G := begin obtain ⟨n, h⟩ : ∃ n, group.nilpotency_class G = n := ⟨ _, rfl⟩, unfreezingI { induction n with n ih generalizing G }, { haveI := nilpotency_class_zero_iff_subsingleton.mp h, exact hbase _, }, { have hn : group.nilpotency_class (G ⧸ center G) = n := by simp [nilpotency_class_quotient_center, h], exact hstep _ (ih _ hn), }, end lemma derived_le_lower_central (n : ℕ) : derived_series G n ≤ lower_central_series G n := by { induction n with i ih, { simp }, { apply commutator_mono ih, simp } } /-- Abelian groups are nilpotent -/ @[priority 100] instance comm_group.is_nilpotent {G : Type*} [comm_group G] : is_nilpotent G := begin use 1, rw upper_central_series_one, apply comm_group.center_eq_top, end /-- Abelian groups have nilpotency class at most one -/ lemma comm_group.nilpotency_class_le_one {G : Type*} [comm_group G] : group.nilpotency_class G ≤ 1 := begin apply upper_central_series_eq_top_iff_nilpotency_class_le.mp, rw upper_central_series_one, apply comm_group.center_eq_top, end /-- Groups with nilpotency class at most one are abelian -/ def comm_group_of_nilpotency_class [is_nilpotent G] (h : group.nilpotency_class G ≤ 1) : comm_group G := group.comm_group_of_center_eq_top $ begin rw ← upper_central_series_one, exact upper_central_series_eq_top_iff_nilpotency_class_le.mpr h, end section prod variables {G₁ G₂ : Type*} [group G₁] [group G₂] lemma lower_central_series_prod (n : ℕ): lower_central_series (G₁ × G₂) n = (lower_central_series G₁ n).prod (lower_central_series G₂ n) := begin induction n with n ih, { simp, }, { calc lower_central_series (G₁ × G₂) n.succ = ⁅lower_central_series (G₁ × G₂) n, ⊤⁆ : rfl ... = ⁅(lower_central_series G₁ n).prod (lower_central_series G₂ n), ⊤⁆ : by rw ih ... = ⁅(lower_central_series G₁ n).prod (lower_central_series G₂ n), (⊤ : subgroup G₁).prod ⊤⁆ : by simp ... = ⁅lower_central_series G₁ n, (⊤ : subgroup G₁)⁆.prod ⁅lower_central_series G₂ n, ⊤⁆ : commutator_prod_prod _ _ _ _ ... = (lower_central_series G₁ n.succ).prod (lower_central_series G₂ n.succ) : rfl } end /-- Products of nilpotent groups are nilpotent -/ instance is_nilpotent_prod [is_nilpotent G₁] [is_nilpotent G₂] : is_nilpotent (G₁ × G₂) := begin rw nilpotent_iff_lower_central_series, refine ⟨max (group.nilpotency_class G₁) (group.nilpotency_class G₂), _ ⟩, rw [lower_central_series_prod, lower_central_series_eq_bot_iff_nilpotency_class_le.mpr (le_max_left _ _), lower_central_series_eq_bot_iff_nilpotency_class_le.mpr (le_max_right _ _), bot_prod_bot], end /-- The nilpotency class of a product is the max of the nilpotency classes of the factors -/ lemma nilpotency_class_prod [is_nilpotent G₁] [is_nilpotent G₂] : group.nilpotency_class (G₁ × G₂) = max (group.nilpotency_class G₁) (group.nilpotency_class G₂) := begin refine eq_of_forall_ge_iff (λ k, _), simp only [max_le_iff, ← lower_central_series_eq_bot_iff_nilpotency_class_le, lower_central_series_prod, prod_eq_bot_iff ], end end prod section bounded_pi -- First the case of infinite products with bounded nilpotency class variables {η : Type*} {Gs : η → Type*} [∀ i, group (Gs i)] lemma lower_central_series_pi_le (n : ℕ): lower_central_series (Π i, Gs i) n ≤ subgroup.pi set.univ (λ i, lower_central_series (Gs i) n) := begin let pi := λ (f : Π i, subgroup (Gs i)), subgroup.pi set.univ f, induction n with n ih, { simp [pi_top] }, { calc lower_central_series (Π i, Gs i) n.succ = ⁅lower_central_series (Π i, Gs i) n, ⊤⁆ : rfl ... ≤ ⁅pi (λ i, (lower_central_series (Gs i) n)), ⊤⁆ : commutator_mono ih (le_refl _) ... = ⁅pi (λ i, (lower_central_series (Gs i) n)), pi (λ i, ⊤)⁆ : by simp [pi, pi_top] ... ≤ pi (λ i, ⁅(lower_central_series (Gs i) n), ⊤⁆) : commutator_pi_pi_le _ _ ... = pi (λ i, lower_central_series (Gs i) n.succ) : rfl } end /-- products of nilpotent groups are nilpotent if their nipotency class is bounded -/ lemma is_nilpotent_pi_of_bounded_class [∀ i, is_nilpotent (Gs i)] (n : ℕ) (h : ∀ i, group.nilpotency_class (Gs i) ≤ n) : is_nilpotent (Π i, Gs i) := begin rw nilpotent_iff_lower_central_series, refine ⟨n, _⟩, rw eq_bot_iff, apply le_trans (lower_central_series_pi_le _), rw [← eq_bot_iff, pi_eq_bot_iff], intros i, apply lower_central_series_eq_bot_iff_nilpotency_class_le.mpr (h i), end end bounded_pi section finite_pi -- Now for finite products variables {η : Type*} [fintype η] {Gs : η → Type*} [∀ i, group (Gs i)] lemma lower_central_series_pi_of_fintype (n : ℕ): lower_central_series (Π i, Gs i) n = subgroup.pi set.univ (λ i, lower_central_series (Gs i) n) := begin let pi := λ (f : Π i, subgroup (Gs i)), subgroup.pi set.univ f, induction n with n ih, { simp [pi_top] }, { calc lower_central_series (Π i, Gs i) n.succ = ⁅lower_central_series (Π i, Gs i) n, ⊤⁆ : rfl ... = ⁅pi (λ i, (lower_central_series (Gs i) n)), ⊤⁆ : by rw ih ... = ⁅pi (λ i, (lower_central_series (Gs i) n)), pi (λ i, ⊤)⁆ : by simp [pi, pi_top] ... = pi (λ i, ⁅(lower_central_series (Gs i) n), ⊤⁆) : commutator_pi_pi_of_fintype _ _ ... = pi (λ i, lower_central_series (Gs i) n.succ) : rfl } end /-- n-ary products of nilpotent groups are nilpotent -/ instance is_nilpotent_pi [∀ i, is_nilpotent (Gs i)] : is_nilpotent (Π i, Gs i) := begin rw nilpotent_iff_lower_central_series, refine ⟨finset.univ.sup (λ i, group.nilpotency_class (Gs i)), _⟩, rw [lower_central_series_pi_of_fintype, pi_eq_bot_iff], intros i, apply lower_central_series_eq_bot_iff_nilpotency_class_le.mpr, exact @finset.le_sup _ _ _ _ finset.univ (λ i, group.nilpotency_class (Gs i)) _ (finset.mem_univ i), end /-- The nilpotency class of an n-ary product is the sup of the nilpotency classes of the factors -/ lemma nilpotency_class_pi [∀ i, is_nilpotent (Gs i)] : group.nilpotency_class (Π i, Gs i) = finset.univ.sup (λ i, group.nilpotency_class (Gs i)) := begin apply eq_of_forall_ge_iff, intros k, simp only [finset.sup_le_iff, ← lower_central_series_eq_bot_iff_nilpotency_class_le, lower_central_series_pi_of_fintype, pi_eq_bot_iff, finset.mem_univ, true_implies_iff ], end end finite_pi /-- A nilpotent subgroup is solvable -/ @[priority 100] instance is_nilpotent.to_is_solvable [h : is_nilpotent G]: is_solvable G := begin obtain ⟨n, hn⟩ := nilpotent_iff_lower_central_series.1 h, use n, rw [eq_bot_iff, ←hn], exact derived_le_lower_central n, end lemma normalizer_condition_of_is_nilpotent [h : is_nilpotent G] : normalizer_condition G := begin -- roughly based on https://groupprops.subwiki.org/wiki/Nilpotent_implies_normalizer_condition rw normalizer_condition_iff_only_full_group_self_normalizing, unfreezingI { induction h using nilpotent_center_quotient_ind with G' _ _ G' _ _ ih; clear _inst_1 G; rename G' → G, }, { rintros H -, apply subsingleton.elim, }, { intros H hH, have hch : center G ≤ H := subgroup.center_le_normalizer.trans (le_of_eq hH), have hkh : (mk' (center G)).ker ≤ H, by simpa using hch, have hsur : function.surjective (mk' (center G)), by exact surjective_quot_mk _, let H' := H.map (mk' (center G)), have hH' : H'.normalizer = H', { apply comap_injective hsur, rw [comap_normalizer_eq_of_surjective _ hsur, comap_map_eq_self hkh], exact hH, }, apply map_injective_of_ker_le (mk' (center G)) hkh le_top, exact (ih H' hH').trans (symm (map_top_of_surjective _ hsur)), }, end end with_group section with_finite_group open group fintype variables {G : Type*} [hG : group G] [hf : fintype G] include hG hf /-- A p-group is nilpotent -/ lemma is_p_group.is_nilpotent {p : ℕ} [hp : fact (nat.prime p)] (h : is_p_group p G) : is_nilpotent G := begin classical, unfreezingI { revert hG, induction hf using fintype.induction_subsingleton_or_nontrivial with G hG hS G hG hN ih }, { apply_instance, }, { introI _, intro h, have hcq : fintype.card (G ⧸ center G) < fintype.card G, { rw card_eq_card_quotient_mul_card_subgroup (center G), apply lt_mul_of_one_lt_right, exact (fintype.card_pos_iff.mpr has_one.nonempty), exact ((subgroup.one_lt_card_iff_ne_bot _).mpr (ne_of_gt h.bot_lt_center)), }, have hnq : is_nilpotent (G ⧸ center G) := ih _ hcq (h.to_quotient (center G)), exact (of_quotient_center_nilpotent hnq), } end /-- If a finite group is the direct product of its Sylow groups, it is nilpotent -/ theorem is_nilpotent_of_product_of_sylow_group (e : (Π p : (fintype.card G).factorization.support, Π P : sylow p G, (↑P : subgroup G)) ≃* G) : is_nilpotent G := begin classical, let ps := (fintype.card G).factorization.support, haveI : ∀ (p : ps) (P : sylow p G), is_nilpotent (↑P : subgroup G), { intros p P, haveI : fact (nat.prime ↑p) := fact.mk (nat.prime_of_mem_factorization (finset.coe_mem p)), exact P.is_p_group'.is_nilpotent, }, exact nilpotent_of_mul_equiv e, end /-- A finite group is nilpotent iff the normalizer condition holds, and iff all maximal groups are normal and iff all sylow groups are normal and iff the group is the direct product of its sylow groups. -/ theorem is_nilpotent_of_finite_tfae : tfae [ is_nilpotent G, normalizer_condition G, ∀ (H : subgroup G), is_coatom H → H.normal, ∀ (p : ℕ) (hp : fact p.prime) (P : sylow p G), (↑P : subgroup G).normal, nonempty ((Π p : (card G).factorization.support, Π P : sylow p G, (↑P : subgroup G)) ≃* G) ] := begin tfae_have : 1 → 2, { exact @normalizer_condition_of_is_nilpotent _ _ }, tfae_have : 2 → 3, { exact λ h H, normalizer_condition.normal_of_coatom H h }, tfae_have : 3 → 4, { introsI h p _ P, exact sylow.normal_of_all_max_subgroups_normal h _ }, tfae_have : 4 → 5, { exact λ h, nonempty.intro (sylow.direct_product_of_normal h) }, tfae_have : 5 → 1, { rintros ⟨e⟩, exact is_nilpotent_of_product_of_sylow_group e }, tfae_finish, end end with_finite_group
018eb716def98f780c2e7efe8faa5b9f748ca4b3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/testing/slim_check/functions_auto.lean
e70e231301345052abcad8c1ab06514ad35d8c05
[]
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
13,232
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.sigma import Mathlib.testing.slim_check.sampleable import Mathlib.testing.slim_check.testable import Mathlib.tactic.pretty_cases import Mathlib.PostPort universes u v l u_1 u_2 w namespace Mathlib /-! ## `slim_check`: generators for functions This file defines `sampleable` instances for `α → β` functions and `ℤ → ℤ` injective functions. Functions are generated by creating a list of pairs and one more value using the list as a lookup table and resorting to the additional value when a value is not found in the table. Injective functions are generated by creating a list of numbers and a permutation of that list. The permutation insures that every input is mapped to a unique output. When an input is not found in the list the input itself is used as an output. Injective functions `f : α → α` could be generated easily instead of `ℤ → ℤ` by generating a `list α`, removing duplicates and creating a permutations. One has to be careful when generating the domain to make if vast enough that, when generating arguments to apply `f` to, they argument should be likely to lie in the domain of `f`. This is the reason that injective functions `f : ℤ → ℤ` are generated by fixing the domain to the range `[-2*size .. -2*size]`, with `size` the size parameter of the `gen` monad. Much of the machinery provided in this file is applicable to generate injective functions of type `α → α` and new instances should be easy to define. Other classes of functions such as monotone functions can generated using similar techniques. For monotone functions, generating two lists, sorting them and matching them should suffice, with appropriate default values. Some care must be taken for shrinking such functions to make sure their defining property is invariant through shrinking. Injective functions are an example of how complicated it can get. -/ namespace slim_check /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `with_default f y` encodes `x ↦ f x` when `x ∈ f` and `x ↦ y` otherwise. We use `Σ` to encode mappings instead of `×` because we rely on the association list API defined in `data.list.sigma`. -/ inductive total_function (α : Type u) (β : Type v) where | with_default : List (sigma fun (_x : α) => β) → β → total_function α β protected instance total_function.inhabited {α : Type u_1} {β : Type u_2} [Inhabited β] : Inhabited (total_function α β) := { default := total_function.with_default ∅ Inhabited.default } namespace total_function /-- Apply a total function to an argument. -/ def apply {α : Type u_1} {β : Type u_2} [DecidableEq α] : total_function α β → α → β := sorry /-- Implementation of `has_repr (total_function α β)`. Creates a string for a given `finmap` and output, `x₀ ↦ y₀, .. xₙ ↦ yₙ` for each of the entries. The brackets are provided by the calling function. -/ def repr_aux {α : Type u} [has_repr α] {β : Type v} [has_repr β] (m : List (sigma fun (_x : α) => β)) : string := string.join (list.qsort (fun (x y : string) => to_bool (x < y)) (list.map (fun (x : sigma fun (_x : α) => β) => string.empty ++ to_string (repr (sigma.fst x)) ++ (string.str (string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1))))))) (char.of_nat (bit0 (bit1 (bit1 (bit0 (bit0 (bit1 (bit0 (bit1 (bit1 (bit0 (bit0 (bit0 (bit0 1))))))))))))))) (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++ to_string (repr (sigma.snd x)) ++ string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 1))))))) (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))) m)) /-- Produce a string for a given `total_function`. The output is of the form `[x₀ ↦ f x₀, .. xₙ ↦ f xₙ, _ ↦ y]`. -/ protected def repr {α : Type u} [has_repr α] {β : Type v} [has_repr β] : total_function α β → string := sorry protected instance has_repr (α : Type u) (β : Type v) [has_repr α] [has_repr β] : has_repr (total_function α β) := has_repr.mk total_function.repr /-- Create a `finmap` from a list of pairs. -/ def list.to_finmap' {α : Type u_1} {β : Type u_2} (xs : List (α × β)) : List (sigma fun (_x : α) => β) := list.map prod.to_sigma xs /-- Redefine `sizeof` to follow the structure of `sampleable` instances. -/ def total.sizeof {α : Type u} {β : Type v} [sampleable α] [sampleable β] : total_function α β → ℕ := sorry protected instance has_sizeof {α : Type u} {β : Type v} [sampleable α] [sampleable β] : SizeOf (total_function α β) := { sizeOf := total.sizeof } /-- Shrink a total function by shrinking the lists that represent it. -/ protected def shrink {α : Type u} {β : Type v} [sampleable α] [sampleable β] [DecidableEq α] : shrink_fn (total_function α β) := sorry protected instance pi.sampleable_ext {α : Type u} {β : Type v} [sampleable α] [sampleable β] [DecidableEq α] [has_repr α] [has_repr β] : sampleable_ext (α → β) := sampleable_ext.mk (total_function α β) (do sample (List (α × β)) uliftable.up (sample β) sorry) total_function.shrink protected instance pi_pred.sampleable_ext {α : Type u} [sampleable_ext (α → Bool)] : sampleable_ext (α → Prop) := sampleable_ext.mk (sampleable_ext.proxy_repr (α → Bool)) (sampleable_ext.sample (α → Bool)) sampleable_ext.shrink protected instance pi_uncurry.sampleable_ext {α : Type u} {β : Type v} {γ : Sort w} [sampleable_ext (α × β → γ)] : sampleable_ext (α → β → γ) := sampleable_ext.mk (sampleable_ext.proxy_repr (α × β → γ)) (sampleable_ext.sample (α × β → γ)) sampleable_ext.shrink end total_function /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `map_to_self f` encodes `x ↦ f x` when `x ∈ f` and `x ↦ x`, i.e. `x` to itself, otherwise. We use `Σ` to encode mappings instead of `×` because we rely on the association list API defined in `data.list.sigma`. -/ inductive injective_function (α : Type u) where | map_to_self : (xs : List (sigma fun (_x : α) => α)) → list.map sigma.fst xs ~ list.map sigma.snd xs → list.nodup (list.map sigma.snd xs) → injective_function α protected instance injective_function.inhabited {α : Type u_1} : Inhabited (injective_function α) := { default := injective_function.map_to_self [] list.perm.nil list.nodup_nil } namespace injective_function /-- Apply a total function to an argument. -/ def apply {α : Type u} [DecidableEq α] : injective_function α → α → α := sorry /-- Produce a string for a given `total_function`. The output is of the form `[x₀ ↦ f x₀, .. xₙ ↦ f xₙ, x ↦ x]`. Unlike for `total_function`, the default value is not a constant but the identity function. -/ protected def repr {α : Type u} [has_repr α] : injective_function α → string := sorry protected instance has_repr (α : Type u) [has_repr α] : has_repr (injective_function α) := has_repr.mk injective_function.repr /-- Interpret a list of pairs as a total function, defaulting to the identity function when no entries are found for a given function -/ def list.apply_id {α : Type u} [DecidableEq α] (xs : List (α × α)) (x : α) : α := option.get_or_else (list.lookup x (list.map prod.to_sigma xs)) x @[simp] theorem list.apply_id_cons {α : Type u} [DecidableEq α] (xs : List (α × α)) (x : α) (y : α) (z : α) : list.apply_id ((y, z) :: xs) x = ite (y = x) z (list.apply_id xs x) := sorry theorem list.apply_id_zip_eq {α : Type u} [DecidableEq α] {xs : List α} {ys : List α} (h₀ : list.nodup xs) (h₁ : list.length xs = list.length ys) (x : α) (y : α) (i : ℕ) (h₂ : list.nth xs i = some x) : list.apply_id (list.zip xs ys) x = y ↔ list.nth ys i = some y := sorry theorem apply_id_mem_iff {α : Type u} [DecidableEq α] {xs : List α} {ys : List α} (h₀ : list.nodup xs) (h₁ : xs ~ ys) (x : α) : list.apply_id (list.zip xs ys) x ∈ ys ↔ x ∈ xs := sorry theorem list.apply_id_eq_self {α : Type u} [DecidableEq α] {xs : List α} {ys : List α} (x : α) : ¬x ∈ xs → list.apply_id (list.zip xs ys) x = x := sorry theorem apply_id_injective {α : Type u} [DecidableEq α] {xs : List α} {ys : List α} (h₀ : list.nodup xs) (h₁ : xs ~ ys) : function.injective (list.apply_id (list.zip xs ys)) := sorry /-- Remove a slice of length `m` at index `n` in a list and a permutation, maintaining the property that it is a permutation. -/ def perm.slice {α : Type u_1} [DecidableEq α] (n : ℕ) (m : ℕ) : (psigma fun (xs : List α) => psigma fun (ys : List α) => xs ~ ys ∧ list.nodup ys) → psigma fun (xs : List α) => psigma fun (ys : List α) => xs ~ ys ∧ list.nodup ys := sorry /-- A lazy list, in decreasing order, of sizes that should be sliced off a list of length `n` -/ def slice_sizes : ℕ → lazy_list ℕ+ := sorry /-- Shrink a permutation of a list, slicing a segment in the middle. The sizes of the slice being removed start at `n` (with `n` the length of the list) and then `n / 2`, then `n / 4`, etc down to 1. The slices will be taken at index `0`, `n / k`, `2n / k`, `3n / k`, etc. -/ protected def shrink_perm {α : Type} [DecidableEq α] [SizeOf α] : shrink_fn (psigma fun (xs : List α) => psigma fun (ys : List α) => xs ~ ys ∧ list.nodup ys) := sorry protected instance has_sizeof {α : Type u_1} [SizeOf α] : SizeOf (injective_function α) := { sizeOf := fun (_x : injective_function α) => sorry } /-- Shrink an injective function slicing a segment in the middle of the domain and removing the corresponding elements in the codomain, hence maintaining the property that one is a permutation of the other. -/ protected def shrink {α : Type} [SizeOf α] [DecidableEq α] : shrink_fn (injective_function α) := sorry /-- Create an injective function from one list and a permutation of that list. -/ protected def mk {α : Type (max u_1 u_2)} (xs : List α) (ys : List α) (h : xs ~ ys) (h' : list.nodup ys) : injective_function α := (fun (h₀ : list.length xs ≤ list.length ys) => (fun (h₁ : list.length ys ≤ list.length xs) => map_to_self (total_function.list.to_finmap' (list.zip xs ys)) sorry sorry) sorry) sorry protected theorem injective {α : Type u} [DecidableEq α] (f : injective_function α) : function.injective (apply f) := sorry protected instance pi_injective.sampleable_ext : sampleable_ext (Subtype fun (f : ℤ → ℤ) => function.injective f) := sampleable_ext.mk (injective_function ℤ) (gen.sized fun (sz : ℕ) => let xs' : List ℤ := int.range (-(bit0 1 * ↑sz + bit0 1)) (bit0 1 * ↑sz + bit0 1); do let ys ← gen.permutation_of xs' (fun (Hinj : function.injective fun (r : ℕ) => -(bit0 1 * ↑sz + bit0 1) + ↑r) => let r : injective_function ℤ := injective_function.mk xs' (subtype.val ys) sorry sorry; pure r) sorry) injective_function.shrink end injective_function protected instance injective.testable {α : Sort u_1} {β : Sort u_2} (f : α → β) [I : testable (named_binder (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit1 (bit1 1)))))))) (∀ (x : α), named_binder (string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit1 (bit1 1)))))))) (∀ (y : α), named_binder (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 (bit0 1)))))))) (f x = f y → x = y))))] : testable (function.injective f) := I protected instance monotone.testable {α : Type u_1} {β : Type u_2} [preorder α] [preorder β] (f : α → β) [I : testable (named_binder (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit1 (bit1 1)))))))) (∀ (x : α), named_binder (string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit1 (bit1 1)))))))) (∀ (y : α), named_binder (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 (bit0 1)))))))) (x ≤ y → f x ≤ f y))))] : testable (monotone f) := I end Mathlib
edea083510f500a05f385406452654e894383214
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/n3.lean
34cc76fb1898a98d408153b356b9df52088bcb30
[ "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
620
lean
prelude definition Prop : Type.{1} := Type.{0} constant N : Type.{1} constant and : Prop → Prop → Prop infixr `∧`:35 := and constant le : N → N → Prop constant lt : N → N → Prop constant f : N → N constant add : N → N → N infixl `+`:65 := add precedence `≤`:50 precedence `<`:50 infixl ≤ := le infixl < := lt notation A ≤ B:prev ≤ C:prev := A ≤ B ∧ B ≤ C notation A ≤ B:prev < C:prev := A ≤ B ∧ B < C notation A < B:prev ≤ C:prev := A < B ∧ B ≤ C constants a b c d e : N #check a ≤ b ≤ f c + b ∧ a < b #check a ≤ d #check a < b ≤ c #check a ≤ b < c #check a < b
4c094d9fc4ada854bc37ffe2ab88d7b972c99156
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/topology/uniform_space/basic.lean
feed27e4ebc8ee8056a6c45d4e7fcea1d6ee9fde
[ "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
69,028
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.lift import topology.separation /-! # Uniform spaces Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * uniform continuity (in this file) * completeness (in `cauchy.lean`) * extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`) * totally bounded sets (in `cauchy.lean`) * totally bounded complete sets are compact (in `cauchy.lean`) A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means "for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages of `X`. The two main examples are: * If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V` * If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V` Those examples are generalizations in two different directions of the elementary example where `X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological group structure on `ℝ` and its metric space structure. Each uniform structure on `X` induces a topology on `X` characterized by > `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)` where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product constructor. The dictionary with metric spaces includes: * an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X` * a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}` for some `V ∈ 𝓤 X`, but the later is more general (it includes in particular both open and closed balls for suitable `V`). In particular we have: `is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s` The triangle inequality is abstracted to a statement involving the composition of relations in `X`. First note that the triangle inequality in a metric space is equivalent to `∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`. Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`. In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }` then the triangle inequality, as reformulated above, says `V ○ W` is contained in `{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`. In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`. Note that this discussion does not depend on any axiom imposed on the uniformity filter, it is simply captured by the definition of composition. The uniform space axioms ask the filter `𝓤 X` to satisfy the following: * every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that `x - x` belongs to every neighborhood of zero in the topological group case. * `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x` in a metric space, and to continuity of negation in the topological group case. * `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds to cutting the radius of a ball in half and applying the triangle inequality. In the topological group case, it comes from continuity of addition at `(0, 0)`. These three axioms are stated more abstractly in the definition below, in terms of operations on filters, without directly manipulating entourages. ## Main definitions * `uniform_space X` is a uniform space structure on a type `X` * `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r` In this file we also define a complete lattice structure on the type `uniform_space X` of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures coming from the pullback of filters. Like distance functions, uniform structures cannot be pushed forward in general. ## Notations Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`, and `○` for composition of relations, seen as terms with type `set (X × X)`. ## Implementation notes There is already a theory of relations in `data/rel.lean` where the main definition is `def rel (α β : Type*) := α → β → Prop`. The relations used in the current file involve only one type, but this is not the reason why we don't reuse `data/rel.lean`. We use `set (α × α)` instead of `rel α α` because we really need sets to use the filter library, and elements of filters on `α × α` have type `set (α × α)`. The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and an assumption saying those are compatible. This may not seem mathematically reasonable at first, but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance] below. ## References The formalization uses the books: * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] But it makes a more systematic use of the filter library. -/ open set filter classical open_locale classical topological_space filter set_option eqn_compiler.zeta true universes u /-! ### Relations, seen as `set (α × α)` -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} localized "infix ` ○ `:55 := comp_rel" in uniformity @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ @[mono] lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k := λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ s ○ t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : (r ○ s) ○ t = r ○ (s ○ t) := by ext p; cases p; simp only [mem_comp_rel]; tauto lemma subset_comp_self {α : Type*} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s := λ ⟨x, y⟩ xy_in, ⟨x, h (by rw mem_id_rel), xy_in⟩ /-- The relation is invariant under swapping factors. -/ def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V /-- The maximal symmetric relation contained in a given relation. -/ def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) := by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp] lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V := sep_subset _ _ @[mono] lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W := inter_subset_inter h $ preimage_mono h lemma symmetric_rel_inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) : symmetric_rel (U ∩ V) := begin unfold symmetric_rel at *, rw [preimage_inter, hU, hV], end /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : 𝓟 id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, s ○ s) ≤ uniformity) /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] section prio /-- Suppose that one can put two mathematical structures on a type, a rich one `R` and a poor one `P`, and that one can deduce the poor structure from the rich structure through a map `F` (called a forgetful functor) (think `R = metric_space` and `P = topological_space`). A possible implementation would be to have a type class `rich` containing a field `R`, a type class `poor` containing a field `P`, and an instance from `rich` to `poor`. However, this creates diamond problems, and a better approach is to let `rich` extend `poor` and have a field saying that `F R = P`. To illustrate this, consider the pair `metric_space` / `topological_space`. Consider the topology on a product of two metric spaces. With the first approach, it could be obtained by going first from each metric space to its topology, and then taking the product topology. But it could also be obtained by considering the product metric space (with its sup distance) and then the topology coming from this distance. These would be the same topology, but not definitionally, which means that from the point of view of Lean's kernel, there would be two different `topological_space` instances on the product. This is not compatible with the way instances are designed and used: there should be at most one instance of a kind on each type. This approach has created an instance diamond that does not commute definitionally. The second approach solves this issue. Now, a metric space contains both a distance, a topology, and a proof that the topology coincides with the one coming from the distance. When one defines the product of two metric spaces, one uses the sup distance and the product topology, and one has to give the proof that the sup distance induces the product topology. Following both sides of the instance diamond then gives rise (definitionally) to the product topology on the product space. Another approach would be to have the rich type class take the poor type class as an instance parameter. It would solve the diamond problem, but it would lead to a blow up of the number of type classes one would need to declare to work with complicated classes, say a real inner product space, and would create exponential complexity when working with products of such complicated spaces, that are avoided by bundling things carefully as above. Note that this description of this specific case of the product of metric spaces is oversimplified compared to mathlib, as there is an intermediate typeclass between `metric_space` and `topological_space` called `uniform_space`. The above scheme is used at both levels, embedding a topology in the uniform space structure, and a uniform structure in the metric space structure. Note also that, when `P` is a proposition, there is no such issue as any two proofs of `P` are definitionally equivalent in Lean. To avoid boilerplate, there are some designs that can automatically fill the poor fields when creating a rich structure if one doesn't want to do something special about them. For instance, in the definition of metric spaces, default tactics fill the uniform space fields if they are not given explicitly. One can also have a helper function creating the rich structure from a structure with less fields, where the helper function fills the remaining fields. See for instance `uniform_space.of_core` or `real_inner_product.of_core`. For more details on this question, called the forgetful inheritance pattern, see [Competing inheritance paths in dependent type theory: a case study in functional analysis](https://hal.inria.fr/hal-02463336). -/ library_note "forgetful inheritance" set_option default_priority 100 -- see Note [default priority] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) end prio /-- Alternative constructor for `uniform_space α` when a topology is already given. -/ @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, t ○ t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α} (h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) : tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) := begin refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity, filter_upwards [h₁₂ hs, h₂₃ hs], exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩ end /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α} (h : tendsto f l (𝓤 α)) : tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) := tendsto_swap_uniformity.comp h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ lemma tendsto_diag_uniformity (f : β → α) (l : filter β) : tendsto (λ x, (f x, f x)) l (𝓤 α) := assume s hs, mem_map.2 $ univ_mem_sets' $ λ x, refl_mem_uniformity hs lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := tendsto_diag_uniformity (λ _, a) f lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α := begin apply (𝓤 α).inter_sets h, rw [← image_swap_eq_preimage_swap, uniformity_eq_symm], exact image_mem_map h, end theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (s ○ s)) = ((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, d ○ (d ○ d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), s ○ s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s := begin obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs, use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w], have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w, calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono ... ⊆ s : w_sub, end lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s := subset_comp_self (refl_le_uniformity h) lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s := begin rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩, rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩, use [t, t_in, t_symm], have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in, calc t ○ t ○ t ⊆ w ○ t : by mono ... ⊆ w ○ (t ○ t) : by mono ... ⊆ w ○ w : by mono ... ⊆ s : w_sub, end /-! ### Balls in uniform spaces -/ /-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/ def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V open uniform_space (ball) /-- The triangle inequality for `uniform_space.ball` -/ lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W) := prod_mk_mem_comp_rel h h' lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) : ball x W ⊆ ball y V := λ z z_in, h' (mem_ball_comp h z_in) lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W := by tauto lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} : x ∈ ball y V ↔ y ∈ ball x V := show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV } lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} : ball x V = {y | (y, x) ∈ V} := by { ext y, rw mem_ball_symmetry hV, exact iff.rfl } lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V) (hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W := begin rw mem_ball_symmetry hV at hx, exact ⟨z, hx, hy⟩ end lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} : p ∈ V ○ M ○ W ↔ ((ball p.1 V).prod (ball p.2 W) ∩ M).nonempty := begin cases p with x y, split, { rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩, exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, }, { rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩, rwa mem_ball_symmetry hW' at z_in, use [z, w] ; tauto }, end /-! ### Neighborhoods in uniform spaces -/ lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ t ○ t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α := by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl } lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} : {p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F := by rw mem_comap_sets ; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, F.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux } lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity], exact iff.rfl, end lemma nhds_basis_uniformity' {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (x, y) ∈ s i}) := by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) } lemma nhds_basis_uniformity {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) := begin replace h := h.comap prod.swap, rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h, exact nhds_basis_uniformity' h end lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin rw [nhds_eq_comap_uniformity, mem_comap_sets], exact iff.rfl, end lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x := begin rw uniform_space.mem_nhds_iff, exact ⟨V, V_in, subset.refl _⟩ end lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s := begin rw uniform_space.mem_nhds_iff, split, { rintros ⟨V, V_in, V_sub⟩, use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V], exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub }, { rintros ⟨V, V_in, V_symm, V_sub⟩, exact ⟨V, V_in, V_sub⟩ } end lemma uniform_space.has_basis_nhds (x : α) : has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) := ⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩ open uniform_space lemma uniform_space.has_basis_nhds_prod (x y : α) : has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, (ball x s).prod (ball y s) := begin rw nhds_prod_eq, apply (has_basis_nhds x).prod' (has_basis_nhds y), rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩, exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, symmetric_rel_inter U_symm V_symm⟩, ball_mono (inter_subset_left U V) x, ball_mono (inter_subset_right U V) y⟩, end lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) := (nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := (nhds_basis_uniformity' (𝓤 α).basis_sets).mem_of_mem h lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : 𝓝 a ×ᶠ 𝓝 b = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, 𝓟 (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end /-- Entourages are neighborhoods of the diagonal. -/ lemma nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α := begin apply supr_le _, intros x V V_in, rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩, have : (ball x w).prod (ball x w) ∈ 𝓝 (x, x), { rw nhds_prod_eq, exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) }, apply mem_sets_of_superset this, rintros ⟨u, v⟩ ⟨u_in, v_in⟩, exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in) end /-! ### Closure and interior in uniform spaces -/ lemma closure_eq_uniformity (s : set $ α × α) : closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V := begin ext ⟨x, y⟩, simp_rw [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter, mem_set_of_eq], apply forall_congr, intro V, apply forall_congr, rintros ⟨V_in, V_symm⟩, simp_rw [mem_comp_comp V_symm, inter_comm, exists_prop], exact iff.rfl, end lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id := begin rw filter.has_basis_self, intro t, split, { intro h, rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩, refine ⟨closure w, _, is_closed_closure, _⟩, apply mem_sets_of_superset w_in subset_closure, refine subset.trans _ r, rw closure_eq_uniformity, apply Inter_subset_of_subset, apply Inter_subset, exact ⟨w_in, w_symm⟩ }, { rintros ⟨r, r_in, r_closed, r_sub⟩, exact mem_sets_of_superset r_in r_sub, } end /-- Closed entourages form a basis of the uniformity filter. -/ lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure := ⟨begin intro t, rw uniformity_has_basis_closed.mem_iff, split, { rintros ⟨r, ⟨r_in, r_closed⟩, r_sub⟩, use [r, r_in], convert r_sub, rw r_closed.closure_eq, refl }, { rintros ⟨r, r_in, r_sub⟩, exact ⟨closure r, ⟨mem_sets_of_superset r_in subset_closure, is_closed_closure⟩, r_sub⟩ } end⟩ lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ 𝓟 t ≠ ⊥) : mem_closure_iff_cluster_pt ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) : begin rw [lift'_inf_principal_eq, ← ne_bot, lift'_ne_bot_iff], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ s ○ (t ○ s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, d ○ (d ○ d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h, have ∃ t ∈ 𝓤 α, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /-! ### Uniformity bases -/ lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)} (h : (𝓤 α).has_basis p s) {t : set (α × α)} : t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t := h.mem_iff.trans $ by simp only [prod.forall, subset_def] /-- Symmetric entourages form a basis of `𝓤 α` -/ lemma uniform_space.has_basis_symmetric : (𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id := ⟨λ t, ⟨λ t_in, ⟨symmetrize_rel t, ⟨⟨symmetrize_mem_uniformity t_in, symmetric_symmetrize_rel t⟩, symmetrize_rel_subset_self _⟩⟩, λ ⟨s, ⟨s_in, h⟩, hst⟩, mem_sets_of_superset s_in hst⟩⟩ lemma uniform_space.has_seq_basis (h : is_countably_generated $ 𝓤 α) : ∃ V : ℕ → set (α × α), has_antimono_basis (𝓤 α) (λ _, true) V ∧ ∀ n, symmetric_rel (V n) := begin rcases h.has_antimono_basis with ⟨U, hbasis, hdec, monotrue⟩, clear monotrue, simp only [forall_prop_of_true] at hdec, use λ n, symmetrize_rel (U n), refine ⟨⟨⟨_⟩, by intros ; mono, by tauto⟩, λ n, symmetric_symmetrize_rel _⟩, intros t, rw hbasis.mem_iff, split, { rintro ⟨i, _, hi⟩, exact ⟨i, trivial, subset.trans (inter_subset_left _ _) hi⟩ }, { rintro ⟨i, _, hi⟩, rcases hbasis.mem_iff.mp (symmetrize_mem_uniformity $ hbasis.mem_of_mem trivial) with ⟨j, _, hj⟩, use j, tauto } end /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) /-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `s`.-/ def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop := tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s.prod s)) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := uniform_continuous_of_const $ λ _ _, rfl lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} : uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i := (ha.tendsto_iff hb).trans $ by simp only [prod.forall] end uniform_space open_locale uniformity section constructions instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := 𝓟 id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ instance inhabited_uniform_space_core : inhabited (uniform_space.core α) := ⟨@uniform_space.to_core _ (default _)⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ } end } lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓤 α = comap (prod.map f f) (𝓤 β) := by { rw h, refl } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume ⟨x, hx⟩, have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := begin by_cases h : nonempty ι, { resetI, refine (eq_of_nhds_eq_nhds $ assume a, _), rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, rw [infi_uniformity, lift'_infi], { simp only [nhds_eq_uniformity], refl }, { exact assume a b, rfl } }, { rw [infi_of_empty h, infi_of_empty h, to_topological_space_top] } end lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi], simp only [← to_topological_space_infi], end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space unit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] (f : α → β) (s : set α) : uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) := begin unfold uniform_continuous_on set.restrict uniform_continuous tendsto, rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl, uniformity_comap rfl, show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl], conv in (map _ (comap _ _)) { rw ← filter.map_map }, rw subtype_coe_map_comap_prod, refl, end lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := (hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] local notation f `∘₂` g := function.bicompr f g /-- Uniform continuity for functions of two variables. -/ def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (uncurry f) := h lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [uniform_continuous₂, uncurry_curry] lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (bicompl f ga gb) := hf.uniform_continuous.comp (hga.prod_map hgb) end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions -- For a version of the Lebesgue number lemma assuming only a sequentially compact space, -- see topology/sequences.lean /-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/ lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end /-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/ lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform variables [uniform_space α] theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) := ⟨λ H, tendsto_left_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩ theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) := ⟨λ H, tendsto_right_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩ theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_right] theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_left] theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_right] theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_left] theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_right] theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_left] theorem continuous_iff'_right [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right theorem continuous_iff'_left [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left end uniform lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto g l (𝓝 b) := uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) := ⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
348d22596e4b38ef7456bf7985dedc034c090d4a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1772.lean
26bdb99efc051be7f9f9ee81b47b5ac35d6effb5
[ "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
294
lean
example (p : Prop) (f : ∀ q : Prop, q → q) : p = p := by apply f _ _; refl example (p : Prop) (f : ∀ q : Prop, q → q) : p = p := by apply f _ _; transitivity; refl example (p r : Prop) (f : ∀ q : Prop, (r = q → q) → q) (h2 : r): p := by apply f _ (λ h, _); subst h; assumption
8d5d045736b7bb8c2a05afebcda90cbbc6aaeebf
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/list/basic.lean
0167c2ca363b4be0d13d2cff2378972c691b317f
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
154,168
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import algebra.group import deprecated.group import data.nat.basic /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /-! ### mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] /-! ### length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ lemma injective_length_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end lemma injective_length [subsingleton α] : injective (length : list α → ℕ) := injective_length_iff.mpr $ by apply_instance /-! ### set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] := by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] } /-! ### bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [mem_cons_iff, forall_mem_cons'] theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /-! ### list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_right h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /-! ### repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /-! ### bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ /-! ### concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by simp theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by simp /-! ### reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl theorem reverse_injective : injective (@reverse α) := left_inverse.injective reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /-! ### is_nil -/ lemma is_nil_iff_eq_nil {l : list α} : l.is_nil ↔ l = [] := list.cases_on l (by simp [is_nil]) (by simp [is_nil]) /-! ### last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l | [] h := absurd rfl h | [a] h := or.inl rfl | (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) } /-! ### last' -/ @[simp] theorem last'_is_none : ∀ {l : list α}, (last' l).is_none ↔ l = [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_none (b::l)] @[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_some (b::l)] theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h | [] x hx := false.elim $ by simpa using hx | [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩ | (a::b::l) x hx := begin rw last' at hx, rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩, use cons_ne_nil _ _, rwa [last_cons] end theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l := let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _ theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l | [] a ha := (option.not_mem_none a ha).elim | [a] _ rfl := rfl | (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] } theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget | [] := by simp [ilast, arbitrary] | [a] := rfl | [a, b] := rfl | [a, b, c] := rfl | (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)] @[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α), last' (l₁ ++ a :: l₂) = last' (a :: l₂) | [] a l₂ := rfl | [b] a l₂ := rfl | (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons] theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []), last' (l₁ ++ l₂) = last' l₂ | [] hl₂ := by contradiction | (b::l₂) _ := last'_append_cons l₁ b l₂ /-! ### head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l | [] h := (option.not_mem_none _ h).elim | (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl } @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l | [] a h := by contradiction | (b::l) a h := by { simp at h, simp [h] } theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l | [] h := by contradiction | (a::l) h := rfl theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := cons_head'_tail (head_mem_head' h) @[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl /-! ### sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact ih.append_right [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff] using h.reverse, λ h, h.append_right l⟩ theorem sublist.append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (hl.append_right _).trans ((append_sublist_append_left _).2 hr) theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (sublist.subset s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, h.subset (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ s.subset theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /-! ### index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp, priority 990] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp, priority 980] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /-! ### nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ /-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as `hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make such a rewrite, with `rw (nth_le_of_eq h)`. -/ lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) : nth_le L i hi = nth_le L' i (h ▸ hi) := by { congr, exact h} @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) : L.nth_le 0 h = L.head := by { cases L, cases h, simp, } lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) : (list.repeat a n).nth_le m h = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[ext] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], } @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) : l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] := begin refine ext_le (by convert h) (λ n h₁ h₂, _), simp only [nth_le_singleton], congr, exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂) end lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /-! ### map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem injective_map_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /-! ### map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /-! ### take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m) | n 0 := by simp | 0 m := by simp | (succ n) (succ m) := by simp [min_succ_succ, take_repeat] lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] /-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first `i` elements of `l₂` to `l₁`. -/ lemma take_append {l₁ l₂ : list α} (i : ℕ) : take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self] end /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) : nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) := by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ } /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) : nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) := by { simp at hi, rw nth_le_take L _ hi.1 } @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_length (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] /-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements up to `i` in `l₂`. -/ lemma drop_append {l₁ l₂ : list α} (i : ℕ) : drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, drop, l₁_ih] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) : nth_le L (i + j) h = nth_le (L.drop i) j begin have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h, rw (take_append_drop i L).symm at h, simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h end := begin have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)], rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right]; simp [A] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) : nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) := by rw nth_le_drop @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /-! ### foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp /- scanl -/ lemma length_scanl {β : Type*} {f : α → β → α} : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /-! ### mfoldl, mfoldr -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl variables [is_lawful_monad m] @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /-! ### prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[to_additive] theorem prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] @[to_additive] theorem prod_eq_foldr : l.prod = foldr (*) 1 l := list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α → β) [is_monoid_hom f] : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, (is_monoid_hom.map_one f).symm], exact l.foldl_hom _ _ _ 1 (is_monoid_hom.map_mul f) } -- `to_additive` chokes on the next few lemmas, so we do them by hand below @[simp] lemma prod_take_mul_prod_drop : ∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], } @[simp] lemma prod_take_succ : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], } /-- A list with product not one must have positive length. -/ lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } end monoid @[simp] lemma sum_take_add_sum_drop [add_monoid α] : ∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], } @[simp] lemma sum_take_succ [add_monoid α] : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], } lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length) (h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' := begin apply ext_le h (λ i h₁ h₂, _), have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁), rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this, exact add_left_cancel this end lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) : monotone (λ i, (L.take i).sum) := begin apply monotone_of_monotone_nat (λ n, _), by_cases h : n < L.length, { rw sum_take_succ _ _ h, exact le_add_right (le_refl _) }, { push_neg at h, simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] } end /-- A list with sum not zero must have positive length. -/ lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } /-- If all elements in a list are bounded below by `1`, then the length of the list is bounded by the sum of the elements. -/ lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum := begin induction L with j L IH h, { simp }, rw [sum_cons, length, add_comm], exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi))) end -- Now we tie those lemmas back to their multiplicative versions. attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one /-- A list with positive sum must have positive length. -/ -- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications. lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) : 0 < L.length := length_pos_of_sum_ne_zero L (ne_of_gt h) @[simp, to_additive] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end -- Several lemmas about sum/head/tail for `list ℕ`. -- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`. -- We'd like to state this as `L.head * L.tail.prod = L.prod`, -- but because `L.head` relies on an inhabited instances and -- returns a garbage value for the empty list, this is not possible. -- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`, -- and below, restate the lemma just for `ℕ`. @[to_additive] lemma head_mul_tail_prod' [monoid α] (L : list α) : (L.nth 0).get_or_else 1 * L.tail.prod = L.prod := by { cases L, { simp, refl, }, { simp, }, } lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum := by { cases L, { simp, refl, }, { simp, }, } lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L) lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head := by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel] /-! ### join -/ attribute [simp] join theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end /-! ### lexicographic ordering -/ /-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which `[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`. The definition is given for any relation `r`, not only strict orders. -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /-! ### all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /-! ### map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap /-! ### find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /-! ### lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /-! ### filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem sublist.map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := filter_map_eq_map f ▸ s.filter_map _ /-! ### filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := (filter_sublist l).subset theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := filter_map_eq_filter p ▸ s.filter_map _ theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /-! ### count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /-! ### prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /-! ### sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s, { simp only [sublists'_nil, mem_singleton], exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, simp only [sublists'_cons, mem_append, IH, mem_map], split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ h }, { exact cons_sublist_cons _ h }, { cases h with _ _ _ h s _ _ h, { exact or.inl h }, { exact or.inr ⟨s, h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, pow_succ, mul_succ, mul_zero, zero_add] @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc] theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih, {refl}, simp only [ih, foldr_cons] end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil] | (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := rfl | (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l] theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind], congr, funext x, apply congr_arg _, rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map, map_eq_map, map_id' (append_nil), append_nil] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l with hd tl ih; [refl, simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro, {rwa foldr}, simp only [foldr, mem_cons_iff, false_or, not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp only [map, map_append, sublists_concat]; exact ((append_sublist_append_left _).2 $ singleton_sublist.2 $ mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans ((append_sublist_append_right _).2 IH) /-! ### sublists_len -/ /-- Auxiliary function to construct the list of all sublists of a given length. Given an integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/ def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β | 0 l f r := f [] :: r | (n+1) [] f r := r | (n+1) (a::l) f r := sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ list.cons a) r) /-- The list of all sublists of a list `l` that are of length `n`. For instance, for `l = [0, 1, 2, 3]` and `n = 2`, one gets `[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/ def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) := sublists_len_aux n l id [] lemma sublists_len_aux_append {α β γ : Type*} : ∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ), sublists_len_aux n l (g ∘ f) (r.map g ++ s) = (sublists_len_aux n l f r).map g ++ s | 0 l f g r s := rfl | (n+1) [] f g r s := rfl | (n+1) (a::l) f g r s := begin unfold sublists_len_aux, rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl, sublists_len_aux_append, sublists_len_aux_append] end lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) : sublists_len_aux n l f r = (sublists_len n l).map f ++ r := by rw [sublists_len, ← sublists_len_aux_append]; refl lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) : sublists_len_aux 0 l f r = f [] :: r := by cases l; refl @[simp] lemma sublists_len_zero {α : Type*} (l : list α) : sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _ @[simp] lemma sublists_len_succ_nil {α : Type*} (n) : sublists_len (n+1) (@nil α) = [] := rfl @[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) : sublists_len (n + 1) (a::l) = sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) := by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id, append_nil]; refl @[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α), length (sublists_len n l) = nat.choose (length l) n | 0 l := by simp | (n+1) [] := by simp | (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α), sublists_len n l <+ sublists' l | 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _)) | (n+1) [] := nil_sublist _ | (n+1) (a::l) := begin rw [sublists_len_succ_cons, sublists'_cons], exact (sublists_len_sublist_sublists' _ _).append ((sublists_len_sublist_sublists' _ _).map _) end lemma sublists_len_sublist_of_sublist {α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl}, { refine IH.trans _, rw sublists_len_succ_cons, apply sublist_append_left }, { simp [sublists_len_succ_cons], exact IH.append ((IHn s).map _) } end lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α}, l' ∈ sublists_len n l → length l' = n | 0 l l' (or.inl rfl) := rfl | (n+1) (a::l) l' h := begin rw [sublists_len_succ_cons, mem_append, mem_map] at h, rcases h with h | ⟨l', h, rfl⟩, { exact length_of_sublists_len h }, { exact congr_arg (+1) (length_of_sublists_len h) }, end lemma mem_sublists_len_self {α : Type*} {l l' : list α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH, { exact or.inl rfl }, { cases l₁ with b l₁, { exact or.inl rfl }, { rw [length, sublists_len_succ_cons], exact mem_append_left _ IH } }, { rw [length, sublists_len_succ_cons], exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) } end @[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := ⟨λ h, ⟨mem_sublists'.1 ((sublists_len_sublist_sublists' _ _).subset h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩ /-! ### permutations -/ section permutations @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl end permutations /-! ### insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /-! ### erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := (erasep_sublist l).subset theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /-! ### erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp, priority 980] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := (erase_sublist a l).subset theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact sublist.erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /-! ### diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := (diff_sublist _ _).subset theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, (h.erase _).diff_right] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (h.erase b) end diff /-! ### enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : ∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end /-! ### product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /-! ### sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /-! ### disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] := by rw disjoint_comm; exact disjoint_nil_left _ @[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /-! ### union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /-! ### inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter section choose variables (p : α → Prop) [decidable_pred p] (l : list α) lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose -- A jumble of lost lemmas: theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val end list @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm namespace list @[to_additive] theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) : (L.map (g ∘ f)).prod = g ((L.map f).prod) := by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm} theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, r * f b)).sum = r * (L.map f).sum := sum_map_hom L f $ add_monoid_hom.mul_left r theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, f b * r)).sum = (L.map f).sum * r := sum_map_hom L f $ add_monoid_hom.mul_right r end list
a4a7f5182b73e9770ac46c9ca2f1aedd3df1405a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/omega/misc.lean
b6ebe964c9c8ab791f4adb81ffdcc4fa7adc2a89
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
2,142
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Miscellaneous. -/ import tactic.localized variables {α β γ : Type} namespace omega lemma fun_mono_2 {p : α → β → γ} {a1 a2 : α} {b1 b2 : β} : a1 = a2 → b1 = b2 → (p a1 b1 = p a2 b2) := λ h1 h2, by rw [h1, h2] lemma pred_mono_2 {p : α → β → Prop} {a1 a2 : α} {b1 b2 : β} : a1 = a2 → b1 = b2 → (p a1 b1 ↔ p a2 b2) := λ h1 h2, by rw [h1, h2] lemma pred_mono_2' {c : Prop → Prop → Prop} {a1 a2 b1 b2 : Prop} : (a1 ↔ a2) → (b1 ↔ b2) → (c a1 b1 ↔ c a2 b2) := λ h1 h2, by rw [h1, h2] /-- Update variable assignment for a specific variable and leave everything else unchanged -/ def update (m : nat) (a : α) (v : nat → α) : nat → α | n := if n = m then a else v n localized "notation v ` ⟨` m ` ↦ ` a `⟩` := omega.update m a v" in omega lemma update_eq (m : nat) (a : α) (v : nat → α) : (v ⟨m ↦ a⟩) m = a := by simp only [update, if_pos rfl] lemma update_eq_of_ne {m : nat} {a : α} {v : nat → α} (k : nat) : k ≠ m → update m a v k = v k := by {intro h1, unfold update, rw if_neg h1} /-- Assign a new value to the zeroth variable, and push all other assignments up by 1 -/ def update_zero (a : α) (v : nat → α) : nat → α | 0 := a | (k+1) := v k open tactic /-- Intro with a fresh name -/ meta def intro_fresh : tactic unit := do n ← mk_fresh_name, intro n, skip /-- Revert an expr if it passes the given test -/ meta def revert_cond (t : expr → tactic unit) (x : expr) : tactic unit := (t x >> revert x >> skip) <|> skip /-- Revert all exprs in the context that pass the given test -/ meta def revert_cond_all (t : expr → tactic unit) : tactic unit := do hs ← local_context, mmap (revert_cond t) hs, skip /-- Try applying a tactic to each of the element in a list until success, and return the first successful result -/ meta def app_first {α β : Type} (t : α → tactic β) : list α → tactic β | [] := failed | (a :: as) := t a <|> app_first as end omega
bcead15d104801319161db272847ec5c950d1f8a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/PreDefinition/Eqns.lean
9ab0b767f13845dc395612e20e886210325a3b33
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
16,152
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.Meta.Eqns import Lean.Util.CollectFVars import Lean.Meta.Tactic.Split import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Refl namespace Lean.Elab.Eqns open Meta structure EqnInfoCore where declName : Name levelParams : List Name type : Expr value : Expr deriving Inhabited partial def expand : Expr → Expr | Expr.letE _ _ v b _ => expand (b.instantiate1 v) | Expr.mdata _ b => expand b | e => e def expandRHS? (mvarId : MVarId) : MetaM (Option MVarId) := do let target ← mvarId.getType' let some (_, lhs, rhs) := target.eq? | return none unless rhs.isLet || rhs.isMData do return none return some (← mvarId.replaceTargetDefEq (← mkEq lhs (expand rhs))) def funext? (mvarId : MVarId) : MetaM (Option MVarId) := do let target ← mvarId.getType' let some (_, _, rhs) := target.eq? | return none unless rhs.isLambda do return none commitWhenSome? do let [mvarId] ← mvarId.apply (← mkConstWithFreshMVarLevels ``funext) | return none let (_, mvarId) ← mvarId.intro1 return some mvarId def simpMatch? (mvarId : MVarId) : MetaM (Option MVarId) := do let mvarId' ← Split.simpMatchTarget mvarId if mvarId != mvarId' then return some mvarId' else return none def simpIf? (mvarId : MVarId) : MetaM (Option MVarId) := do let mvarId' ← simpIfTarget mvarId (useDecide := true) if mvarId != mvarId' then return some mvarId' else return none private def findMatchToSplit? (env : Environment) (e : Expr) (declNames : Array Name) (exceptionSet : ExprSet) : Option Expr := e.findExt? fun e => Id.run do if e.hasLooseBVars || exceptionSet.contains e then return Expr.FindStep.visit else if let some info := isMatcherAppCore? env e then let args := e.getAppArgs -- If none of the discriminants is a free variable, then it is not worth splitting the match let mut hasFVarDiscr := false for i in [info.getFirstDiscrPos : info.getFirstDiscrPos + info.numDiscrs] do let discr := args[i]! if discr.isFVar then hasFVarDiscr := true break unless hasFVarDiscr do return Expr.FindStep.visit -- At least one alternative must contain a `declNames` application with loose bound variables. for i in [info.getFirstAltPos : info.getFirstAltPos + info.numAlts] do let alt := args[i]! if Option.isSome <| alt.find? fun e => declNames.any e.isAppOf && e.hasLooseBVars then return Expr.FindStep.found return Expr.FindStep.visit else let Expr.const declName .. := e.getAppFn | return Expr.FindStep.visit if declName == ``WellFounded.fix || isBRecOnRecursor env declName then -- We should not go inside unfolded nested recursive applications return Expr.FindStep.done else return Expr.FindStep.visit partial def splitMatch? (mvarId : MVarId) (declNames : Array Name) : MetaM (Option (List MVarId)) := commitWhenSome? do let target ← mvarId.getType' let rec go (badCases : ExprSet) : MetaM (Option (List MVarId)) := do if let some e := findMatchToSplit? (← getEnv) target declNames badCases then try Meta.Split.splitMatch mvarId e catch _ => go (badCases.insert e) else trace[Meta.Tactic.split] "did not find term to split\n{MessageData.ofGoal mvarId}" return none go {} structure Context where declNames : Array Name private def lhsDependsOn (type : Expr) (fvarId : FVarId) : MetaM Bool := forallTelescope type fun _ type => do if let some (_, lhs, _) ← matchEq? type then dependsOn lhs fvarId else dependsOn type fvarId /-- Try to close goal using `rfl` with smart unfolding turned off. -/ def tryURefl (mvarId : MVarId) : MetaM Bool := withOptions (smartUnfolding.set · false) do try mvarId.refl; return true catch _ => return false /-- Eliminate `namedPatterns` from equation, and trivial hypotheses. -/ def simpEqnType (eqnType : Expr) : MetaM Expr := do forallTelescopeReducing (← instantiateMVars eqnType) fun ys type => do let proofVars := collect type trace[Elab.definition] "simpEqnType type: {type}" let mut type ← Match.unfoldNamedPattern type let mut eliminated : FVarIdSet := {} for y in ys.reverse do trace[Elab.definition] ">> simpEqnType: {← inferType y}, {type}" if proofVars.contains y.fvarId! then let some (_, Expr.fvar fvarId, rhs) ← matchEq? (← inferType y) | throwError "unexpected hypothesis in altenative{indentExpr eqnType}" eliminated := eliminated.insert fvarId type := type.replaceFVarId fvarId rhs else if eliminated.contains y.fvarId! then if (← dependsOn type y.fvarId!) then type ← mkForallFVars #[y] type else if let some (_, lhs, rhs) ← matchEq? (← inferType y) then if (← isDefEq lhs rhs) then if !(← dependsOn type y.fvarId!) then continue else if !(← lhsDependsOn type y.fvarId!) then -- Since the `lhs` of the `type` does not depend on `y`, we replace it with `Eq.refl` in the `rhs` type := type.replaceFVar y (← mkEqRefl lhs) continue type ← mkForallFVars #[y] type return type where -- Collect eq proof vars used in `namedPatterns` collect (e : Expr) : FVarIdSet := let go (e : Expr) (ω) : ST ω FVarIdSet := do let ref ← ST.mkRef {} e.forEach fun e => do if let some e := Match.isNamedPattern? e then let arg := e.appArg!.consumeMData if arg.isFVar then ST.Prim.Ref.modify ref (·.insert arg.fvarId!) ST.Prim.Ref.get ref runST (go e) private partial def saveEqn (mvarId : MVarId) : StateRefT (Array Expr) MetaM Unit := mvarId.withContext do let target ← mvarId.getType' let fvarState := collectFVars {} target let fvarState ← (← getLCtx).foldrM (init := fvarState) fun decl fvarState => do if fvarState.fvarSet.contains decl.fvarId then return collectFVars fvarState (← instantiateMVars decl.type) else return fvarState let mut fvarIdSet := fvarState.fvarSet let mut fvarIds ← sortFVarIds <| fvarState.fvarSet.toArray -- Include (relevant) propositions that are not already in `fvarIdSet` let mut modified := false repeat modified := false for decl in (← getLCtx) do unless fvarIdSet.contains decl.fvarId do if (← isProp decl.type) then let type ← instantiateMVars decl.type unless (← isIrrelevant fvarIdSet type) do modified := true (fvarIdSet, fvarIds) ← pushDecl fvarIdSet fvarIds decl until !modified let type ← mkForallFVars (fvarIds.map mkFVar) target let type ← simpEqnType type modify (·.push type) where /-- We say the type/proposition is "irrelevant" if 1- It does not contain any variable in `fvarIdSet` OR 2- It is of the form `x = t` or `t = x` where `x` is a free variable that is not in `fvarIdSet`. This can of equality can be eliminated by substitution. -/ isIrrelevant (fvarIdSet : FVarIdSet) (type : Expr) : MetaM Bool := do if Option.isNone <| type.find? fun e => e.isFVar && fvarIdSet.contains e.fvarId! then return true else if let some (_, lhs, rhs) := type.eq? then return (lhs.isFVar && !fvarIdSet.contains lhs.fvarId!) || (rhs.isFVar && !fvarIdSet.contains rhs.fvarId!) else return false pushDecl (fvarIdSet : FVarIdSet) (fvarIds : Array FVarId) (localDecl : LocalDecl) : MetaM (FVarIdSet × Array FVarId) := do let (fvarIdSet, fvarIds) ← collectDeps fvarIdSet fvarIds (← instantiateMVars localDecl.type) return (fvarIdSet.insert localDecl.fvarId, fvarIds.push localDecl.fvarId) collectDeps (fvarIdSet : FVarIdSet) (fvarIds : Array FVarId) (type : Expr) : MetaM (FVarIdSet × Array FVarId) := do let s := collectFVars {} type let usedFVarIds ← sortFVarIds <| s.fvarSet.toArray let mut fvarIdSet := fvarIdSet let mut fvarIds := fvarIds for fvarId in usedFVarIds do unless fvarIdSet.contains fvarId do (fvarIdSet, fvarIds) ← pushDecl fvarIdSet fvarIds (← fvarId.getDecl) return (fvarIdSet, fvarIds) /-- Quick filter for deciding whether to use `simpMatch?` at `mkEqnTypes`. If the result is `false`, then it is not worth trying `simpMatch`. -/ private def shouldUseSimpMatch (e : Expr) : MetaM Bool := do let env ← getEnv return Option.isSome <| e.find? fun e => Id.run do if let some info := isMatcherAppCore? env e then let args := e.getAppArgs for discr in args[info.getFirstDiscrPos : info.getFirstDiscrPos + info.numDiscrs] do if discr.isConstructorApp env then return true return false partial def mkEqnTypes (declNames : Array Name) (mvarId : MVarId) : MetaM (Array Expr) := do let (_, eqnTypes) ← go mvarId |>.run { declNames } |>.run #[] return eqnTypes where go (mvarId : MVarId) : ReaderT Context (StateRefT (Array Expr) MetaM) Unit := do trace[Elab.definition.eqns] "mkEqnTypes step\n{MessageData.ofGoal mvarId}" if (← tryURefl mvarId) then saveEqn mvarId return () if let some mvarId ← expandRHS? mvarId then return (← go mvarId) -- The following `funext?` was producing an overapplied `lhs`. Possible refinement: only do it if we want to apply `splitMatch` on the body of the lambda /- if let some mvarId ← funext? mvarId then return (← go mvarId) -/ if (← shouldUseSimpMatch (← mvarId.getType')) then if let some mvarId ← simpMatch? mvarId then return (← go mvarId) if let some mvarIds ← splitMatch? mvarId declNames then return (← mvarIds.forM go) saveEqn mvarId /-- Some of the hypotheses added by `mkEqnTypes` may not be used by the actual proof (i.e., `value` argument). This method eliminates them. Alternative solution: improve `saveEqn` and make sure it never includes unnecessary hypotheses. These hypotheses are leftovers from tactics such as `splitMatch?` used in `mkEqnTypes`. -/ def removeUnusedEqnHypotheses (declType declValue : Expr) : CoreM (Expr × Expr) := do go declType declValue #[] {} where go (type value : Expr) (xs : Array Expr) (lctx : LocalContext) : CoreM (Expr × Expr) := do match value with | .lam n d b bi => let d := d.instantiateRev xs let fvarId ← mkFreshFVarId go (type.bindingBody!) b (xs.push (mkFVar fvarId)) (lctx.mkLocalDecl fvarId n d bi) | _ => let type := type.instantiateRev xs let value := value.instantiateRev xs let mut s := collectFVars (collectFVars {} type) value let mut xsNew := #[] for x in xs.reverse do if s.fvarSet.contains x.fvarId! then s := collectFVars s (lctx.getFVar! x).type xsNew := xsNew.push x if xsNew.size == xs.size then return (declType, declValue) else xsNew := xsNew.reverse return (lctx.mkForall xsNew type, lctx.mkLambda xsNew value) /-- Delta reduce the equation left-hand-side -/ def deltaLHS (mvarId : MVarId) : MetaM MVarId := mvarId.withContext do let target ← mvarId.getType' let some (_, lhs, rhs) := target.eq? | throwTacticEx `deltaLHS mvarId "equality expected" let some lhs ← delta? lhs | throwTacticEx `deltaLHS mvarId "failed to delta reduce lhs" mvarId.replaceTargetDefEq (← mkEq lhs rhs) def deltaRHS? (mvarId : MVarId) (declName : Name) : MetaM (Option MVarId) := mvarId.withContext do let target ← mvarId.getType' let some (_, lhs, rhs) := target.eq? | return none let some rhs ← delta? rhs.consumeMData (· == declName) | return none mvarId.replaceTargetDefEq (← mkEq lhs rhs) private partial def whnfAux (e : Expr) : MetaM Expr := do let e ← whnfI e -- Must reduce instances too, otherwise it will not be able to reduce `(Nat.rec ... ... (OfNat.ofNat 0))` let f := e.getAppFn match f with | .proj _ _ s => return mkAppN (f.updateProj! (← whnfAux s)) e.getAppArgs | _ => return e /-- Apply `whnfR` to lhs, return `none` if `lhs` was not modified -/ def whnfReducibleLHS? (mvarId : MVarId) : MetaM (Option MVarId) := mvarId.withContext do let target ← mvarId.getType' let some (_, lhs, rhs) := target.eq? | return none let lhs' ← whnfAux lhs if lhs' != lhs then return some (← mvarId.replaceTargetDefEq (← mkEq lhs' rhs)) else return none def tryContradiction (mvarId : MVarId) : MetaM Bool := do mvarId.contradictionCore { genDiseq := true } structure UnfoldEqnExtState where map : Std.PHashMap Name Name := {} deriving Inhabited /- We generate the unfold equation on demand, and do not save them on .olean files. -/ builtin_initialize unfoldEqnExt : EnvExtension UnfoldEqnExtState ← registerEnvExtension (pure {}) /-- Auxiliary method for `mkUnfoldEq`. The structure is based on `mkEqnTypes`. `mvarId` is the goal to be proved. It is a goal of the form ``` declName x_1 ... x_n = body[x_1, ..., x_n] ``` The proof is constracted using the automatically generated equational theorems. We basically keep splitting the `match` and `if-then-else` expressions in the right hand side until one of the equational theorems is applicable. -/ partial def mkUnfoldProof (declName : Name) (mvarId : MVarId) : MetaM Unit := do let some eqs ← getEqnsFor? declName | throwError "failed to generate equations for '{declName}'" let tryEqns (mvarId : MVarId) : MetaM Bool := eqs.anyM fun eq => commitWhen do try let subgoals ← mvarId.apply (← mkConstWithFreshMVarLevels eq) subgoals.allM fun subgoal => do if (← subgoal.isAssigned) then return true -- Subgoal was already solved. This can happen when there are dependencies between the subgoals else subgoal.assumptionCore catch _ => return false let rec go (mvarId : MVarId) : MetaM Unit := do if (← tryEqns mvarId) then return () -- Remark: we removed funext? from `mkEqnTypes` -- else if let some mvarId ← funext? mvarId then -- go mvarId if (← shouldUseSimpMatch (← mvarId.getType')) then if let some mvarId ← simpMatch? mvarId then return (← go mvarId) if let some mvarIds ← splitTarget? mvarId (splitIte := false) then return (← mvarIds.forM go) if (← tryContradiction mvarId) then return () throwError "failed to generate unfold theorem for '{declName}'\n{MessageData.ofGoal mvarId}" go mvarId /-- Generate the "unfold" lemma for `declName`. -/ def mkUnfoldEq (declName : Name) (info : EqnInfoCore) : MetaM Name := withLCtx {} {} do let env ← getEnv withOptions (tactic.hygienic.set · false) do let baseName := mkPrivateName env declName lambdaTelescope info.value fun xs body => do let us := info.levelParams.map mkLevelParam let type ← mkEq (mkAppN (Lean.mkConst declName us) xs) body let goal ← mkFreshExprSyntheticOpaqueMVar type mkUnfoldProof declName goal.mvarId! let type ← mkForallFVars xs type let value ← mkLambdaFVars xs (← instantiateMVars goal) let name := baseName ++ `_unfold addDecl <| Declaration.thmDecl { name, type, value levelParams := info.levelParams } return name def getUnfoldFor? (declName : Name) (getInfo? : Unit → Option EqnInfoCore) : MetaM (Option Name) := do let env ← getEnv if let some eq := unfoldEqnExt.getState env |>.map.find? declName then return some eq else if let some info := getInfo? () then let eq ← mkUnfoldEq declName info modifyEnv fun env => unfoldEqnExt.modifyState env fun s => { s with map := s.map.insert declName eq } return some eq else return none builtin_initialize registerTraceClass `Elab.definition.unfoldEqn registerTraceClass `Elab.definition.eqns end Lean.Elab.Eqns
cd05769359702c4d6962944ee2e78de15c90807e
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20170116_POPL/debug/has_to_string.lean
e565736982d82136b82ba53d7cb8659e7168e53a
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
1,566
lean
/- We revist an example from earlier, showing how the debugger can be used to interactively debug & introspect on tactics. -/ /- First we import the debugger. -/ import tools.debugger /- Then we set the option which enables the debugger. -/ set_option debugger true /- We then set the option which enables autorun, which allows the debugger to launch the CLI debugger upon execution of the file. -/ set_option debugger.autorun true open tactic expr inductive color | red | blue | green open color /- We now define a tactic for automatically generating has_to_string instances for enumeration types. -/ meta def close_goals_using : list name → tactic unit | [] := now <|> fail "mk_enum_has_to_string tactic failed, unexpected number of goals" | (name.mk_string s p :: cs) := do s^.to_expr >>= exact, close_goals_using cs | _ := fail "mk_enum_has_to_string tactic failed, unexpected constructor name" /- We set a top-level breakpoint on the tactic which synthesizes a to_string implementation. -/ @[breakpoint] meta def mk_enum_has_to_string : tactic unit := do env ← get_env, constructor, e ← intro1, (const Enum []) ← infer_type e >>= whnf | failed, when (¬ env^.is_inductive Enum) (fail "mk_has_to_string failed, type is not an inductive datatype"), cs ← return $ env^.constructors_of Enum, cases e, close_goals_using cs /- Now, we automatically generate an instance using our mk_enum_has_to_string tactic. -/ instance : has_to_string color := by mk_enum_has_to_string vm_eval [red, blue, green, red]
183c0ec771e7fd7ff8674a52bc56f9b1798d4d57
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/pnat/basic.lean
41f3f00d22bacb00a270b7dfdec4c7631207dbbd
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
16,471
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Neil Strickland -/ import data.nat.basic /-! # The positive natural numbers This file defines the type `ℕ+` or `pnat`, the subtype of natural numbers that are positive. -/ /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ def pnat := {n : ℕ // 0 < n} notation `ℕ+` := pnat instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩ instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩ /-- Predecessor of a `ℕ+`, as a `ℕ`. -/ def pnat.nat_pred (i : ℕ+) : ℕ := i - 1 @[simp] lemma pnat.one_add_nat_pred (n : ℕ+) : 1 + n.nat_pred = n := by rw [pnat.nat_pred, add_tsub_cancel_iff_le.mpr $ show 1 ≤ (n : ℕ), from n.2] @[simp] lemma pnat.nat_pred_add_one (n : ℕ+) : n.nat_pred + 1 = n := (add_comm _ _).trans n.one_add_nat_pred @[simp] lemma pnat.nat_pred_eq_pred {n : ℕ} (h : 0 < n) : pnat.nat_pred (⟨n, h⟩ : ℕ+) = n.pred := rfl namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : ℕ) (h : 0 < n . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩ /-- Write a successor as an element of `ℕ+`. -/ def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl theorem succ_pnat_inj {n m : ℕ} : succ_pnat n = succ_pnat m → n = m := λ h, by { let h' := congr_arg (coe : ℕ+ → ℕ) h, exact nat.succ.inj h' } /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n) @[simp] theorem to_pnat'_coe : ∀ (n : ℕ), ((to_pnat' n) : ℕ) = ite (0 < n) n 1 | 0 := rfl | (m + 1) := by {rw [if_pos (succ_pos m)], refl} end nat namespace pnat open nat /-- We now define a long list of structures on ℕ+ induced by similar structures on ℕ. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ instance : decidable_eq ℕ+ := λ (a b : ℕ+), by apply_instance instance : linear_order ℕ+ := subtype.linear_order _ @[simp] lemma mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k := iff.rfl @[simp] lemma mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k := iff.rfl @[simp, norm_cast] lemma coe_le_coe (n k : ℕ+) : (n : ℕ) ≤ k ↔ n ≤ k := iff.rfl @[simp, norm_cast] lemma coe_lt_coe (n k : ℕ+) : (n : ℕ) < k ↔ n < k := iff.rfl @[simp] theorem pos (n : ℕ+) : 0 < (n : ℕ) := n.2 -- see note [fact non_instances] lemma fact_pos (n : ℕ+) : fact (0 < ↑n) := ⟨n.pos⟩ theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq @[simp] lemma coe_inj {m n : ℕ+} : (m : ℕ) = n ↔ m = n := set_coe.ext_iff lemma coe_injective : function.injective (coe : ℕ+ → ℕ) := subtype.coe_injective @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl instance : has_add ℕ+ := ⟨λ a b, ⟨(a + b : ℕ), add_pos a.pos b.pos⟩⟩ instance : add_comm_semigroup ℕ+ := coe_injective.add_comm_semigroup coe (λ _ _, rfl) @[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl /-- `pnat.coe` promoted to an `add_hom`, that is, a morphism which preserves addition. -/ def coe_add_hom : add_hom ℕ+ ℕ := { to_fun := coe, map_add' := add_coe } instance : add_left_cancel_semigroup ℕ+ := coe_injective.add_left_cancel_semigroup coe (λ _ _, rfl) instance : add_right_cancel_semigroup ℕ+ := coe_injective.add_right_cancel_semigroup coe (λ _ _, rfl) /-- The order isomorphism between ℕ and ℕ+ given by `succ`. -/ @[simps] def succ_order_iso : ℕ ≃o ℕ+ := { to_fun := λ n, ⟨_, succ_pos n⟩, inv_fun := λ n, pred (n : ℕ), left_inv := pred_succ, right_inv := λ ⟨x, hx⟩, by simpa using succ_pred_eq_of_pos hx, map_rel_iff' := @succ_le_succ_iff } @[priority 10] instance : covariant_class ℕ+ ℕ+ ((+)) (≤) := ⟨by { rintro ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, simp [←pnat.coe_le_coe] }⟩ @[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := n.2.ne' theorem to_pnat'_coe {n : ℕ} : 0 < n → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos) instance : has_mul ℕ+ := ⟨λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩⟩ instance : has_one ℕ+ := ⟨succ_pnat 0⟩ instance : has_pow ℕ+ ℕ := ⟨λ x n, ⟨x ^ n, pow_pos x.2 n⟩⟩ instance : comm_monoid ℕ+ := coe_injective.comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) theorem lt_add_one_iff : ∀ {a b : ℕ+}, a < b + 1 ↔ a ≤ b := λ a b, nat.lt_add_one_iff theorem add_one_le_iff : ∀ {a b : ℕ+}, a + 1 ≤ b ↔ a < b := λ a b, nat.add_one_le_iff @[simp] lemma one_le (n : ℕ+) : (1 : ℕ+) ≤ n := n.2 @[simp] lemma not_lt_one (n : ℕ+) : ¬ n < 1 := not_lt_of_le n.one_le instance : order_bot ℕ+ := { bot := 1, bot_le := λ a, a.property } @[simp] lemma bot_eq_one : (⊥ : ℕ+) = 1 := rfl instance : inhabited ℕ+ := ⟨1⟩ -- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] lemma mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) := rfl @[simp] lemma mk_bit0 (n) {h} : (⟨bit0 n, h⟩ : ℕ+) = (bit0 ⟨n, pos_of_bit0_pos h⟩ : ℕ+) := rfl @[simp] lemma mk_bit1 (n) {h} {k} : (⟨bit1 n, h⟩ : ℕ+) = (bit1 ⟨n, k⟩ : ℕ+) := rfl -- Some lemmas that rewrite inequalities between explicit numerals in `ℕ+` -- into the corresponding inequalities in `ℕ`. -- TODO: perhaps this should not be attempted by `simp`, -- and instead we should expect `norm_num` to take care of these directly? -- TODO: these lemmas are perhaps incomplete: -- * 1 is not represented as a bit0 or bit1 -- * strict inequalities? @[simp] lemma bit0_le_bit0 (n m : ℕ+) : (bit0 n) ≤ (bit0 m) ↔ (bit0 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit0_le_bit1 (n m : ℕ+) : (bit0 n) ≤ (bit1 m) ↔ (bit0 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit0 (n m : ℕ+) : (bit1 n) ≤ (bit0 m) ↔ (bit1 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit1 (n m : ℕ+) : (bit1 n) ≤ (bit1 m) ↔ (bit1 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl @[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl /-- `pnat.coe` promoted to a `monoid_hom`. -/ def coe_monoid_hom : ℕ+ →* ℕ := { to_fun := coe, map_one' := one_coe, map_mul' := mul_coe } @[simp] lemma coe_coe_monoid_hom : (coe_monoid_hom : ℕ+ → ℕ) = coe := rfl @[simp] lemma coe_eq_one_iff {m : ℕ+} : (m : ℕ) = 1 ↔ m = 1 := by { split; intro h; try { apply pnat.eq}; rw h; simp } @[simp] lemma le_one_iff {n : ℕ+} : n ≤ 1 ↔ n = 1 := begin rcases n with ⟨_|n, hn⟩, { exact absurd hn (lt_irrefl _) }, { simp [←pnat.coe_le_coe, subtype.ext_iff, nat.succ_le_succ_iff, nat.succ_inj'], } end lemma lt_add_left (n m : ℕ+) : n < m + n := begin rcases m with ⟨_|m, hm⟩, { exact absurd hm (lt_irrefl _) }, { simp [←pnat.coe_lt_coe] } end lemma lt_add_right (n m : ℕ+) : n < n + m := (lt_add_left n m).trans_le (add_comm _ _).le @[simp] lemma coe_bit0 (a : ℕ+) : ((bit0 a : ℕ+) : ℕ) = bit0 (a : ℕ) := rfl @[simp] lemma coe_bit1 (a : ℕ+) : ((bit1 a : ℕ+) : ℕ) = bit1 (a : ℕ) := rfl @[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : ((m ^ n : ℕ+) : ℕ) = (m : ℕ) ^ n := rfl instance : ordered_cancel_comm_monoid ℕ+ := { mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption }, le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, }, mul_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_right_inj a.pos).mp h)}, .. pnat.comm_monoid, .. pnat.linear_order } instance : distrib ℕ+ := coe_injective.distrib coe (λ _ _, rfl) (λ _ _, rfl) /-- Subtraction a - b is defined in the obvious way when a > b, and by a - b = 1 if a ≤ b. -/ instance : has_sub ℕ+ := ⟨λ a b, to_pnat' (a - b : ℕ)⟩ theorem sub_coe (a b : ℕ+) : ((a - b : ℕ+) : ℕ) = ite (b < a) (a - b : ℕ) 1 := begin change (to_pnat' _ : ℕ) = ite _ _ _, split_ifs with h, { exact to_pnat'_coe (tsub_pos_of_lt h) }, { rw tsub_eq_zero_iff_le.mpr (le_of_not_gt h : (a : ℕ) ≤ b), refl } end theorem add_sub_of_lt {a b : ℕ+} : a < b → a + (b - a) = b := λ h, eq $ by { rw [add_coe, sub_coe, if_pos h], exact add_tsub_cancel_of_le h.le } instance : has_well_founded ℕ+ := ⟨(<), measure_wf coe⟩ /-- Strong induction on `ℕ+`. -/ def strong_induction_on {p : ℕ+ → Sort*} : ∀ (n : ℕ+) (h : ∀ k, (∀ m, m < k → p m) → p k), p n | n := λ IH, IH _ (λ a h, strong_induction_on a IH) using_well_founded { dec_tac := `[assumption] } /-- If `n : ℕ+` is different from `1`, then it is the successor of some `k : ℕ+`. -/ lemma exists_eq_succ_of_ne_one : ∀ {n : ℕ+} (h1 : n ≠ 1), ∃ (k : ℕ+), n = k + 1 | ⟨1, _⟩ h1 := false.elim $ h1 rfl | ⟨n+2, _⟩ _ := ⟨⟨n+1, by simp⟩, rfl⟩ /-- Strong induction on `ℕ+`, with `n = 1` treated separately. -/ def case_strong_induction_on {p : ℕ+ → Sort*} (a : ℕ+) (hz : p 1) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (n + 1)) : p a := begin apply strong_induction_on a, rintro ⟨k, kprop⟩ hk, cases k with k, { exact (lt_irrefl 0 kprop).elim }, cases k with k, { exact hz }, exact hi ⟨k.succ, nat.succ_pos _⟩ (λ m hm, hk _ (lt_succ_iff.2 hm)), end /-- An induction principle for `ℕ+`: it takes values in `Sort*`, so it applies also to Types, not only to `Prop`. -/ @[elab_as_eliminator] def rec_on (n : ℕ+) {p : ℕ+ → Sort*} (p1 : p 1) (hp : ∀ n, p n → p (n + 1)) : p n := begin rcases n with ⟨n, h⟩, induction n with n IH, { exact absurd h dec_trivial }, { cases n with n, { exact p1 }, { exact hp _ (IH n.succ_pos) } } end @[simp] theorem rec_on_one {p} (p1 hp) : @pnat.rec_on 1 p p1 hp = p1 := rfl @[simp] theorem rec_on_succ (n : ℕ+) {p : ℕ+ → Sort*} (p1 hp) : @pnat.rec_on (n + 1) p p1 hp = hp n (@pnat.rec_on n p p1 hp) := by { cases n with n h, cases n; [exact absurd h dec_trivial, refl] } /-- We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div_aux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ | k 0 q := ⟨k, q.pred⟩ | k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩ lemma mod_div_aux_spec : ∀ (k : ℕ+) (r q : ℕ) (h : ¬ (r = 0 ∧ q = 0)), (((mod_div_aux k r q).1 : ℕ) + k * (mod_div_aux k r q).2 = (r + k * q)) | k 0 0 h := (h ⟨rfl, rfl⟩).elim | k 0 (q + 1) h := by { change (k : ℕ) + (k : ℕ) * (q + 1).pred = 0 + (k : ℕ) * (q + 1), rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]} | k (r + 1) q h := rfl /-- `mod_div m k = (m % k, m / k)`. We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div (m k : ℕ+) : ℕ+ × ℕ := mod_div_aux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) /-- We define `m % k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive. -/ def mod (m k : ℕ+) : ℕ+ := (mod_div m k).1 /-- We define `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def div (m k : ℕ+) : ℕ := (mod_div m k).2 theorem mod_add_div (m k : ℕ+) : ((mod m k) + k * (div m k) : ℕ) = m := begin let h₀ := nat.mod_add_div (m : ℕ) (k : ℕ), have : ¬ ((m : ℕ) % (k : ℕ) = 0 ∧ (m : ℕ) / (k : ℕ) = 0), by { rintro ⟨hr, hq⟩, rw [hr, hq, mul_zero, zero_add] at h₀, exact (m.ne_zero h₀.symm).elim }, have := mod_div_aux_spec k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) this, exact (this.trans h₀), end theorem div_add_mod (m k : ℕ+) : (k * (div m k) + mod m k : ℕ) = m := (add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ+) : ((mod m k) + (div m k) * k : ℕ) = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ+) : ((div m k) * k + mod m k : ℕ) = m := by { rw mul_comm, exact div_add_mod _ _ } theorem mod_coe (m k : ℕ+) : ((mod m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) := begin dsimp [mod, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem div_coe (m k : ℕ+) : ((div m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) := begin dsimp [div, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem mod_le (m k : ℕ+) : mod m k ≤ m ∧ mod m k ≤ k := begin change ((mod m k) : ℕ) ≤ (m : ℕ) ∧ ((mod m k) : ℕ) ≤ (k : ℕ), rw [mod_coe], split_ifs, { have hm : (m : ℕ) > 0 := m.pos, rw [← nat.mod_add_div (m : ℕ) (k : ℕ), h, zero_add] at hm ⊢, by_cases h' : ((m : ℕ) / (k : ℕ)) = 0, { rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim}, { let h' := nat.mul_le_mul_left (k : ℕ) (nat.succ_le_of_lt (nat.pos_of_ne_zero h')), rw [mul_one] at h', exact ⟨h', le_refl (k : ℕ)⟩ } }, { exact ⟨nat.mod_le (m : ℕ) (k : ℕ), (nat.mod_lt (m : ℕ) k.pos).le⟩ } end theorem dvd_iff {k m : ℕ+} : k ∣ m ↔ (k : ℕ) ∣ (m : ℕ) := begin split; intro h, rcases h with ⟨_, rfl⟩, apply dvd_mul_right, rcases h with ⟨a, h⟩, cases a, { contrapose h, apply ne_zero, }, use a.succ, apply nat.succ_pos, rw [← coe_inj, h, mul_coe, mk_coe], end theorem dvd_iff' {k m : ℕ+} : k ∣ m ↔ mod m k = k := begin rw dvd_iff, rw [nat.dvd_iff_mod_eq_zero], split, { intro h, apply eq, rw [mod_coe, if_pos h] }, { intro h, by_cases h' : (m : ℕ) % (k : ℕ) = 0, { exact h'}, { replace h : ((mod m k) : ℕ) = (k : ℕ) := congr_arg _ h, rw [mod_coe, if_neg h'] at h, exact ((nat.mod_lt (m : ℕ) k.pos).ne h).elim } } end lemma le_of_dvd {m n : ℕ+} : m ∣ n → m ≤ n := by { rw dvd_iff', intro h, rw ← h, apply (mod_le n m).left } /-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/ def div_exact (m k : ℕ+) : ℕ+ := ⟨(div m k).succ, nat.succ_pos _⟩ theorem mul_div_exact {m k : ℕ+} (h : k ∣ m) : k * (div_exact m k) = m := begin apply eq, rw [mul_coe], change (k : ℕ) * (div m k).succ = m, rw [← div_add_mod m k, dvd_iff'.mp h, nat.mul_succ] end theorem dvd_antisymm {m n : ℕ+} : m ∣ n → n ∣ m → m = n := λ hmn hnm, (le_of_dvd hmn).antisymm (le_of_dvd hnm) theorem dvd_one_iff (n : ℕ+) : n ∣ 1 ↔ n = 1 := ⟨λ h, dvd_antisymm h (one_dvd n), λ h, h.symm ▸ (dvd_refl 1)⟩ lemma pos_of_div_pos {n : ℕ+} {a : ℕ} (h : a ∣ n) : 0 < a := begin apply pos_iff_ne_zero.2, intro hzero, rw hzero at h, exact pnat.ne_zero n (eq_zero_of_zero_dvd h) end end pnat section can_lift instance nat.can_lift_pnat : can_lift ℕ ℕ+ := ⟨coe, λ n, 0 < n, λ n hn, ⟨nat.to_pnat' n, pnat.to_pnat'_coe hn⟩⟩ instance int.can_lift_pnat : can_lift ℤ ℕ+ := ⟨coe, λ n, 0 < n, λ n hn, ⟨nat.to_pnat' (int.nat_abs n), by rw [coe_coe, nat.to_pnat'_coe, if_pos (int.nat_abs_pos_of_ne_zero hn.ne'), int.nat_abs_of_nonneg hn.le]⟩⟩ end can_lift
6f0f98817725f219048e9c290fd73cf1752099d6
ea4aee6b11f86433e69bb5e50d0259e056d0ae61
/src/tidy/timing.lean
9365f104386054b8bdfedd73178e8a18bf5b3918
[]
no_license
timjb/lean-tidy
e18feff0b7f0aad08c614fb4d34aaf527bf21e20
e767e259bf76c69edfd4ab8af1b76e6f1ed67f48
refs/heads/master
1,624,861,693,182
1,504,411,006,000
1,504,411,006,000
103,740,824
0
0
null
1,505,553,968,000
1,505,553,968,000
null
UTF-8
Lean
false
false
550
lean
import system.io open tactic universe variables u -- There's apparently about a 1/5th of a second overhead here... meta def time_in_nanos : tactic ℕ := do time ← tactic.run_io (λ [ioi : io.interface], @io.cmd ioi { cmd := "gdate", args := [ "+%s%N" ] } ), pure time.to_nat meta def time_tactic { α : Type } ( t : tactic α ) : tactic (α × ℕ) := do time_before ← time_in_nanos, r ← t, time_after ← time_in_nanos, pure (r, time_after - time_before) lemma f : 1 = 1 := begin (time_tactic skip) >>= trace, simp end
dd76e8b339c809aaae8bb0218367964a0389aff0
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2009/IMO_2009_P2.lean
3365ef54b021856e4ae9ab017a9f0fda7b9ee510
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
369
lean
import Geo.Geo.Core namespace Geo open Seg Triangle def IMO_2009_P2 : Prop := ∀ (A B C P Q : Point), let O := circumcenter ⟨A, B, C⟩; on P (Seg.mk C A) → on Q (Seg.mk A B) → let K := (Seg.mk B P).midp; let L := (Seg.mk C Q).midp; let M := (Seg.mk P Q).midp; let Γ := Circle.buildPPP K L M; tangent (Line.mk P Q) Γ → cong ⟨O, P⟩ ⟨O, Q⟩ end Geo
03debf47e8c79ce2b3dfc91f3526d2798fd04bb7
129628888508a22919f176e3ba2033c3b52fa859
/src/ftg.lean
14fcdf1873b42d31d7be2cbdfa51b76863aecdfe
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/P11-Galois-Theory
1aa35b6aa71c08aec6da3296ba404bf246db8df3
ced2caa52300feb633316b3120c40ca957c8e8ff
refs/heads/master
1,671,253,848,362
1,600,080,687,000
1,600,080,687,000
160,926,153
4
0
null
null
null
null
UTF-8
Lean
false
false
532
lean
import ring_theory.algebra data.fintype.basic linear_algebra.dimension universes u v w variables (K : Type u) (L : Type v) [field K] [field L] class finite_Galois_extension extends algebra K L. definition galois_group : Type u → Type v → Type w := sorry instance [finite_Galois_extension K L] : fintype (galois_group L K) := sorry -- needs fixing theorem fundamental_theorem_of_Galois_theory (HL : finite_Galois_extension K L) : (fintype.card (galois_group L K) : cardinal) = vector_space.dim K L := sorry
19b22620be5046dae0cb5d698b3dcdcc67d2b80e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/shapes/pullbacks.lean
6a52b692c2abd4bebdff4e649de7b32ec28535f2
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
29,299
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel, Bhavik Mehta -/ import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. ## References * [Stacks: Fibre products](https://stacks.math.columbia.edu/tag/001U) * [Stacks: Pushouts](https://stacks.math.columbia.edu/tag/0025) -/ noncomputable theory open category_theory namespace category_theory.limits universes v u u₂ local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback, defined as a special case of `wide_pullback_shape`. -/ abbreviation walking_cospan : Type v := wide_pullback_shape walking_pair /-- The left point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.one : walking_cospan := none /-- The type of objects for the diagram indexing a pushout, defined as a special case of `wide_pushout_shape`. -/ abbreviation walking_span : Type v := wide_pushout_shape walking_pair /-- The left point of the walking span. -/ @[pattern] abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ @[pattern] abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ @[pattern] abbreviation walking_span.zero : walking_span := none namespace walking_cospan /-- The type of arrows for the diagram indexing a pullback. -/ abbreviation hom : walking_cospan → walking_cospan → Type v := wide_pullback_shape.hom /-- The left arrow of the walking cospan. -/ @[pattern] abbreviation hom.inl : left ⟶ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ @[pattern] abbreviation hom.inr : right ⟶ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ @[pattern] abbreviation hom.id (X : walking_cospan) : X ⟶ X := wide_pullback_shape.hom.id X instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy end walking_cospan namespace walking_span /-- The type of arrows for the diagram indexing a pushout. -/ abbreviation hom : walking_span → walking_span → Type v := wide_pushout_shape.hom /-- The left arrow of the walking span. -/ @[pattern] abbreviation hom.fst : zero ⟶ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ @[pattern] abbreviation hom.snd : zero ⟶ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ @[pattern] abbreviation hom.id (X : walking_span) : X ⟶ X := wide_pushout_shape.hom.id X instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy end walking_span open walking_span.hom walking_cospan.hom wide_pullback_shape.hom wide_pushout_shape.hom variables {C : Type u} [category.{v} C] /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan ⥤ C := wide_pullback_shape.wide_cospan Z (λ j, walking_pair.cases_on j X Y) (λ j, walking_pair.cases_on j f g) /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span ⥤ C := wide_pushout_shape.wide_span X (λ j, walking_pair.cases_on j Y Z) (λ j, walking_pair.cases_on j f g) @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an pullback is naturally isomorphic (actually, equal) to a `cospan` -/ @[simps {rhs_md := semireducible}] def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) /-- Every diagram indexing a pushout is naturally isomorphic (actually, equal) to a `span` -/ @[simps {rhs_md := semireducible}] def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) variables {X Y Z : C} /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app walking_cospan.left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app walking_cospan.right /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : pullback_cone f g) (lift : Π (s : pullback_cone f g), s.X ⟶ t.X) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ t.fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ t.snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, option.cases_on j (by { rw [← s.w inl, ← t.w inl, ←category.assoc], congr, exact fac_left s, } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_limit_aux' (t : pullback_cone f g) (create : Π (s : pullback_cone f g), {l // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ ∀ {m}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) : limits.is_limit t := pullback_cone.is_limit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ @[simps] def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, option.cases_on j (fst ≫ f) (λ j', walking_pair.cases_on j' fst snd) } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.one = fst ≫ f := rfl @[simp] lemma mk_fst {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).fst = fst := rfl @[simp] lemma mk_snd {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).snd = snd := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := (t.w inl).trans (t.w inr).symm /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w inl, reassoc_of h₀] lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pullback_cone` constructed using `pullback_cone.mk` is a limit cone. -/ def is_limit.mk {W : C} {fst : W ⟶ X} {snd : W ⟶ Y} (eq : fst ≫ f = snd ≫ g) (lift : Π (s : pullback_cone f g), s.X ⟶ W) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ W) (w_fst : m ≫ fst = s.fst) (w_snd : m ≫ snd = s.snd), m = lift s) : is_limit (mk fst snd eq) := is_limit_aux _ lift fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pullback square is a pullback square. -/ def flip_is_limit {W : C} {h : W ⟶ X} {k : W ⟶ Y} {comm : h ≫ f = k ≫ g} (t : is_limit (mk _ _ comm.symm)) : is_limit (mk _ _ comm) := is_limit_aux' _ $ λ s, begin refine ⟨(is_limit.lift' t _ _ s.condition.symm).1, (is_limit.lift' t _ _ _).2.2, (is_limit.lift' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).equalizer_ext, { rwa (is_limit.lift' t _ _ _).2.1 }, { rwa (is_limit.lift' t _ _ _).2.2 }, end /-- The pullback cone `(𝟙 X, 𝟙 X)` for the pair `(f, f)` is a limit if `f` is a mono. The converse is shown in `mono_of_pullback_is_id`. -/ def is_limit_mk_id_id (f : X ⟶ Y) [mono f] : is_limit (mk (𝟙 X) (𝟙 X) rfl : pullback_cone f f) := is_limit.mk _ (λ s, s.fst) (λ s, category.comp_id _) (λ s, by rw [←cancel_mono f, category.comp_id, s.condition]) (λ s m m₁ m₂, by simpa using m₁) /-- `f` is a mono if the pullback cone `(𝟙 X, 𝟙 X)` is a limit for the pair `(f, f)`. The converse is given in `pullback_cone.is_id_of_mono`. -/ lemma mono_of_is_limit_mk_id_id (f : X ⟶ Y) (t : is_limit (mk (𝟙 X) (𝟙 X) rfl : pullback_cone f f)) : mono f := ⟨λ Z g h eq, by { rcases pullback_cone.is_limit.lift' t _ _ eq with ⟨_, rfl, rfl⟩, refl } ⟩ end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app walking_span.left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app walking_span.right /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : pushout_cocone f g) (desc : Π (s : pushout_cocone f g), t.X ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), t.inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), t.inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, option.cases_on j (by { simp [← s.w fst, ← t.w fst, fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_colimit_aux' (t : pushout_cocone f g) (create : Π (s : pushout_cocone f g), {l // t.inl ≫ l = s.inl ∧ t.inr ≫ l = s.inr ∧ ∀ {m}, t.inl ≫ m = s.inl → t.inr ≫ m = s.inr → m = l}) : is_colimit t := is_colimit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ @[simps] def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, option.cases_on j (f ≫ inl) (λ j', walking_pair.cases_on j' inl inr) } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.zero = f ≫ inl := rfl @[simp] lemma mk_inl {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inl = inl := rfl @[simp] lemma mk_inr {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inr = inr := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := (t.w fst).trans (t.w snd).symm /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w fst, category.assoc, category.assoc, h₀] lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pushout_cocone` constructed using `pushout_cocone.mk` is a colimit cocone. -/ def is_colimit.mk {W : C} {inl : Y ⟶ W} {inr : Z ⟶ W} (eq : f ≫ inl = g ≫ inr) (desc : Π (s : pushout_cocone f g), W ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : W ⟶ s.X) (w_inl : inl ≫ m = s.inl) (w_inr : inr ≫ m = s.inr), m = desc s) : is_colimit (mk inl inr eq) := is_colimit_aux _ desc fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pushout square is a pushout square. -/ def flip_is_colimit {W : C} {h : Y ⟶ W} {k : Z ⟶ W} {comm : f ≫ h = g ≫ k} (t : is_colimit (mk _ _ comm.symm)) : is_colimit (mk _ _ comm) := is_colimit_aux' _ $ λ s, begin refine ⟨(is_colimit.desc' t _ _ s.condition.symm).1, (is_colimit.desc' t _ _ _).2.2, (is_colimit.desc' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).coequalizer_ext, { rwa (is_colimit.desc' t _ _ _).2.1 }, { rwa (is_colimit.desc' t _ _ _).2.2 }, end end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ @[simps] def cone.of_pullback_cone {F : walking_cospan ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).inv } /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ @[simps] def cocone.of_pushout_cocone {F : walking_span ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := (diagram_iso_span F).hom ≫ t.ι } /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ @[simps] def pullback_cone.of_cone {F : walking_cospan ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).hom } /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ @[simps] def pushout_cocone.of_cocone {F : walking_span ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := (diagram_iso_span F).inv ≫ t.ι } /-- `has_pullback f g` represents a particular choice of limiting cone for the pair of morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`. -/ abbreviation has_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) := has_limit (cospan f g) /-- `has_pushout f g` represents a particular choice of colimiting cocone for the pair of morphisms `f : X ⟶ Y` and `g : X ⟶ Z`. -/ abbreviation has_pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) := has_colimit (span f g) /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ @[reassoc] lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ @[reassoc] lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback cone built from the pullback projections is a pullback. -/ def pullback_is_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] : is_limit (pullback_cone.mk (pullback.fst : pullback f g ⟶ _) pullback.snd pullback.condition) := pullback_cone.is_limit.mk _ (λ s, pullback.lift s.fst s.snd s.condition) (by simp) (by simp) (by tidy) /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ by simp [← pullback.condition, reassoc_of h]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ by simp [pullback.condition, reassoc_of h]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ by simp [← pushout.condition_assoc, h] ⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ by simp [pushout.condition_assoc, h]) h⟩ section variables {D : Type u₂} [category.{v} D] (G : C ⥤ D) /-- The comparison morphism for the pullback of `f,g`. This is an isomorphism iff `G` preserves the pullback of `f,g`; see `category_theory/limits/preserves/shapes/pullbacks.lean` -/ def pullback_comparison (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : G.obj (pullback f g) ⟶ pullback (G.map f) (G.map g) := pullback.lift (G.map pullback.fst) (G.map pullback.snd) (by simp only [←G.map_comp, pullback.condition]) @[simp, reassoc] lemma pullback_comparison_comp_fst (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : pullback_comparison G f g ≫ pullback.fst = G.map pullback.fst := pullback.lift_fst _ _ _ @[simp, reassoc] lemma pullback_comparison_comp_snd (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : pullback_comparison G f g ≫ pullback.snd = G.map pullback.snd := pullback.lift_snd _ _ _ @[simp, reassoc] lemma map_lift_pullback_comparison (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] {W : C} {h : W ⟶ X} {k : W ⟶ Y} (w : h ≫ f = k ≫ g) : G.map (pullback.lift _ _ w) ≫ pullback_comparison G f g = pullback.lift (G.map h) (G.map k) (by simp only [←G.map_comp, w]) := by { ext; simp [← G.map_comp] } end variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms See https://stacks.math.columbia.edu/tag/001W. -/ abbreviation has_pullbacks := has_limits_of_shape walking_cospan C /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ abbreviation has_pushouts := has_colimits_of_shape walking_span C /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ lemma has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks C := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ lemma has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } end category_theory.limits
930c013cc3ff757b4c2fb62ad999fab9c83a3d58
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/multiset/locally_finite.lean
78d3b6f2d0a1d38d77a272424b85f9c6a61c189c
[ "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
8,626
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite /-! # Intervals as multisets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides basic results about all the `multiset.Ixx`, which are defined in `order.locally_finite`. Note that intervals of multisets themselves (`multiset.locally_finite_order`) are defined elsewhere. -/ variables {α : Type*} namespace multiset section preorder variables [preorder α] [locally_finite_order α] {a b c : α} lemma nodup_Icc : (Icc a b).nodup := finset.nodup _ lemma nodup_Ico : (Ico a b).nodup := finset.nodup _ lemma nodup_Ioc : (Ioc a b).nodup := finset.nodup _ lemma nodup_Ioo : (Ioo a b).nodup := finset.nodup _ @[simp] lemma Icc_eq_zero_iff : Icc a b = 0 ↔ ¬a ≤ b := by rw [Icc, finset.val_eq_zero, finset.Icc_eq_empty_iff] @[simp] lemma Ico_eq_zero_iff : Ico a b = 0 ↔ ¬a < b := by rw [Ico, finset.val_eq_zero, finset.Ico_eq_empty_iff] @[simp] lemma Ioc_eq_zero_iff : Ioc a b = 0 ↔ ¬a < b := by rw [Ioc, finset.val_eq_zero, finset.Ioc_eq_empty_iff] @[simp] lemma Ioo_eq_zero_iff [densely_ordered α] : Ioo a b = 0 ↔ ¬a < b := by rw [Ioo, finset.val_eq_zero, finset.Ioo_eq_empty_iff] alias Icc_eq_zero_iff ↔ _ Icc_eq_zero alias Ico_eq_zero_iff ↔ _ Ico_eq_zero alias Ioc_eq_zero_iff ↔ _ Ioc_eq_zero @[simp] lemma Ioo_eq_zero (h : ¬a < b) : Ioo a b = 0 := eq_zero_iff_forall_not_mem.2 $ λ x hx, h ((mem_Ioo.1 hx).1.trans (mem_Ioo.1 hx).2) @[simp] lemma Icc_eq_zero_of_lt (h : b < a) : Icc a b = 0 := Icc_eq_zero h.not_le @[simp] lemma Ico_eq_zero_of_le (h : b ≤ a) : Ico a b = 0 := Ico_eq_zero h.not_lt @[simp] lemma Ioc_eq_zero_of_le (h : b ≤ a) : Ioc a b = 0 := Ioc_eq_zero h.not_lt @[simp] lemma Ioo_eq_zero_of_le (h : b ≤ a) : Ioo a b = 0 := Ioo_eq_zero h.not_lt variables (a) @[simp] lemma Ico_self : Ico a a = 0 := by rw [Ico, finset.Ico_self, finset.empty_val] @[simp] lemma Ioc_self : Ioc a a = 0 := by rw [Ioc, finset.Ioc_self, finset.empty_val] @[simp] lemma Ioo_self : Ioo a a = 0 := by rw [Ioo, finset.Ioo_self, finset.empty_val] variables {a b c} lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := finset.left_mem_Icc lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := finset.left_mem_Ico lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := finset.right_mem_Icc lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := finset.right_mem_Ioc @[simp] lemma left_not_mem_Ioc : a ∉ Ioc a b := finset.left_not_mem_Ioc @[simp] lemma left_not_mem_Ioo : a ∉ Ioo a b := finset.left_not_mem_Ioo @[simp] lemma right_not_mem_Ico : b ∉ Ico a b := finset.right_not_mem_Ico @[simp] lemma right_not_mem_Ioo : b ∉ Ioo a b := finset.right_not_mem_Ioo lemma Ico_filter_lt_of_le_left [decidable_pred (< c)] (hca : c ≤ a) : (Ico a b).filter (λ x, x < c) = ∅ := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_le_left hca], refl } lemma Ico_filter_lt_of_right_le [decidable_pred (< c)] (hbc : b ≤ c) : (Ico a b).filter (λ x, x < c) = Ico a b := by rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_right_le hbc] lemma Ico_filter_lt_of_le_right [decidable_pred (< c)] (hcb : c ≤ b) : (Ico a b).filter (λ x, x < c) = Ico a c := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_le_right hcb], refl } lemma Ico_filter_le_of_le_left [decidable_pred ((≤) c)] (hca : c ≤ a) : (Ico a b).filter (λ x, c ≤ x) = Ico a b := by rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_le_left hca] lemma Ico_filter_le_of_right_le [decidable_pred ((≤) b)] : (Ico a b).filter (λ x, b ≤ x) = ∅ := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_right_le], refl } lemma Ico_filter_le_of_left_le [decidable_pred ((≤) c)] (hac : a ≤ c) : (Ico a b).filter (λ x, c ≤ x) = Ico c b := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_left_le hac], refl } end preorder section partial_order variables [partial_order α] [locally_finite_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := by rw [Icc, finset.Icc_self, finset.singleton_val] lemma Ico_cons_right (h : a ≤ b) : b ::ₘ (Ico a b) = Icc a b := by { classical, rw [Ico, ←finset.insert_val_of_not_mem right_not_mem_Ico, finset.Ico_insert_right h], refl } lemma Ioo_cons_left (h : a < b) : a ::ₘ (Ioo a b) = Ico a b := by { classical, rw [Ioo, ←finset.insert_val_of_not_mem left_not_mem_Ioo, finset.Ioo_insert_left h], refl } lemma Ico_disjoint_Ico {a b c d : α} (h : b ≤ c) : (Ico a b).disjoint (Ico c d) := λ x hab hbc, by { rw mem_Ico at hab hbc, exact hab.2.not_le (h.trans hbc.1) } @[simp] lemma Ico_inter_Ico_of_le [decidable_eq α] {a b c d : α} (h : b ≤ c) : Ico a b ∩ Ico c d = 0 := multiset.inter_eq_zero_iff_disjoint.2 $ Ico_disjoint_Ico h lemma Ico_filter_le_left {a b : α} [decidable_pred (≤ a)] (hab : a < b) : (Ico a b).filter (λ x, x ≤ a) = {a} := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_left hab], refl } lemma card_Ico_eq_card_Icc_sub_one (a b : α) : (Ico a b).card = (Icc a b).card - 1 := finset.card_Ico_eq_card_Icc_sub_one _ _ lemma card_Ioc_eq_card_Icc_sub_one (a b : α) : (Ioc a b).card = (Icc a b).card - 1 := finset.card_Ioc_eq_card_Icc_sub_one _ _ lemma card_Ioo_eq_card_Ico_sub_one (a b : α) : (Ioo a b).card = (Ico a b).card - 1 := finset.card_Ioo_eq_card_Ico_sub_one _ _ lemma card_Ioo_eq_card_Icc_sub_two (a b : α) : (Ioo a b).card = (Icc a b).card - 2 := finset.card_Ioo_eq_card_Icc_sub_two _ _ end partial_order section linear_order variables [linear_order α] [locally_finite_order α] {a b c d : α} lemma Ico_subset_Ico_iff {a₁ b₁ a₂ b₂ : α} (h : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := finset.Ico_subset_Ico_iff h lemma Ico_add_Ico_eq_Ico {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) : Ico a b + Ico b c = Ico a c := by rw [add_eq_union_iff_disjoint.2 (Ico_disjoint_Ico le_rfl), Ico, Ico, Ico, ←finset.union_val, finset.Ico_union_Ico_eq_Ico hab hbc] lemma Ico_inter_Ico : Ico a b ∩ Ico c d = Ico (max a c) (min b d) := by rw [Ico, Ico, Ico, ←finset.inter_val, finset.Ico_inter_Ico] @[simp] lemma Ico_filter_lt (a b c : α) : (Ico a b).filter (λ x, x < c) = Ico a (min b c) := by rw [Ico, Ico, ←finset.filter_val, finset.Ico_filter_lt] @[simp] lemma Ico_filter_le (a b c : α) : (Ico a b).filter (λ x, c ≤ x) = Ico (max a c) b := by rw [Ico, Ico, ←finset.filter_val, finset.Ico_filter_le] @[simp] lemma Ico_sub_Ico_left (a b c : α) : Ico a b - Ico a c = Ico (max a c) b := by rw [Ico, Ico, Ico, ←finset.sdiff_val, finset.Ico_diff_Ico_left] @[simp] lemma Ico_sub_Ico_right (a b c : α) : Ico a b - Ico c b = Ico a (min b c) := by rw [Ico, Ico, Ico, ←finset.sdiff_val, finset.Ico_diff_Ico_right] end linear_order section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] [locally_finite_order α] lemma map_add_left_Icc (a b c : α) : (Icc a b).map ((+) c) = Icc (c + a) (c + b) := by { classical, rw [Icc, Icc, ←finset.image_add_left_Icc, finset.image_val, ((finset.nodup _).map $ add_right_injective c).dedup] } lemma map_add_left_Ico (a b c : α) : (Ico a b).map ((+) c) = Ico (c + a) (c + b) := by { classical, rw [Ico, Ico, ←finset.image_add_left_Ico, finset.image_val, ((finset.nodup _).map $ add_right_injective c).dedup] } lemma map_add_left_Ioc (a b c : α) : (Ioc a b).map ((+) c) = Ioc (c + a) (c + b) := by { classical, rw [Ioc, Ioc, ←finset.image_add_left_Ioc, finset.image_val, ((finset.nodup _).map $ add_right_injective c).dedup] } lemma map_add_left_Ioo (a b c : α) : (Ioo a b).map ((+) c) = Ioo (c + a) (c + b) := by { classical, rw [Ioo, Ioo, ←finset.image_add_left_Ioo, finset.image_val, ((finset.nodup _).map $ add_right_injective c).dedup] } lemma map_add_right_Icc (a b c : α) : (Icc a b).map (λ x, x + c) = Icc (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Icc _ _ _ } lemma map_add_right_Ico (a b c : α) : (Ico a b).map (λ x, x + c) = Ico (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ico _ _ _ } lemma map_add_right_Ioc (a b c : α) : (Ioc a b).map (λ x, x + c) = Ioc (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ioc _ _ _ } lemma map_add_right_Ioo (a b c : α) : (Ioo a b).map (λ x, x + c) = Ioo (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ioo _ _ _ } end ordered_cancel_add_comm_monoid end multiset
72c0c97bd721a3b429a992244b888d79119edefb
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_45.lean
ae24fe2090e2cdad1cb6c73981bbb069dde98c5a
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
126
lean
import data.real.basic example (a b c : ℝ) : (a * b) * c = b * (a * c) := begin rw mul_comm a b, rw mul_assoc b a c end
a3204b74adc3971f6fabad3224d950a57b2353ff
80746c6dba6a866de5431094bf9f8f841b043d77
/src/data/pfun.lean
6af4742325913e3c5e999d178454d8a6757b5e4c
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
16,850
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.set.basic data.option.basic data.equiv.basic /-- `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 -/ def 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 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 -/ def 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 _⟩ @[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 : relator.left_unique ((∈) : α → roption α → Prop) | _ ⟨p, f⟩ _ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl 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)⟩ @[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]⟩ 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 roption.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)⟩ /-- `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 | _ _ ⟨h, rfl⟩ := ⟨⟨_, _⟩, 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⟩ theorem mem_bind {f : roption α} {g : α → roption β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g | _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨_, _⟩, 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 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 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)⟩ /-- `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*} /-- The domain of a partial function -/ def dom (f : α →. β) : set α := λ a, (f a).dom /-- 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 -/ def 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) def 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 : {x // f.dom x}) : β := f.fn s.1 s.2 def equiv_subtype : (α →. β) ≃ (Σ p : α → Prop, subtype p → β) := ⟨λ f, ⟨f.dom, as_subtype f⟩, λ ⟨p, f⟩ x, ⟨p x, λ h, f ⟨x, h⟩⟩, λ f, funext $ λ a, roption.eta _, λ ⟨p, f⟩, by dsimp; congr; funext a; cases a; refl⟩ /-- 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} /-- 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 (p x) (f x) (@H x) 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] theorem 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
97270c4b70e349a4ef42a57e85ada7c5536d223b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/uniform_space/separation.lean
9568058cb194736c94251861084e96d38da36f31
[ "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
23,295
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, Patrick Massot -/ import tactic.apply_fun import data.set.pairwise import topology.uniform_space.basic import topology.separation /-! # Hausdorff properties of uniform spaces. Separation quotient. This file studies uniform spaces whose underlying topological spaces are separated (also known as Hausdorff or T₂). This turns out to be equivalent to asking that the intersection of all entourages is the diagonal only. This condition actually implies the stronger separation property that the space is regular (T₃), hence those conditions are equivalent for topologies coming from a uniform structure. More generally, the intersection `𝓢 X` of all entourages of `X`, which has type `set (X × X)` is an equivalence relation on `X`. Points which are equivalent under the relation are basically undistinguishable from the point of view of the uniform structure. For instance any uniformly continuous function will send equivalent points to the same value. The quotient `separation_quotient X` of `X` by `𝓢 X` has a natural uniform structure which is separated, and satisfies a universal property: every uniformly continuous function from `X` to a separated uniform space uniquely factors through `separation_quotient X`. As usual, this allows to turn `separation_quotient` into a functor (but we don't use the category theory library in this file). These notions admit relative versions, one can ask that `s : set X` is separated, this is equivalent to asking that the uniform structure induced on `s` is separated. ## Main definitions * `separation_relation X : set (X × X)`: the separation relation * `separated_space X`: a predicate class asserting that `X` is separated * `is_separated s`: a predicate asserting that `s : set X` is separated * `separation_quotient X`: the maximal separated quotient of `X`. * `separation_quotient.lift f`: factors a map `f : X → Y` through the separation quotient of `X`. * `separation_quotient.map f`: turns a map `f : X → Y` into a map between the separation quotients of `X` and `Y`. ## Main results * `separated_iff_t2`: the equivalence between being separated and being Hausdorff for uniform spaces. * `separation_quotient.uniform_continuous_lift`: factoring a uniformly continuous map through the separation quotient gives a uniformly continuous map. * `separation_quotient.uniform_continuous_map`: maps induced between separation quotients are uniformly continuous. ## Notations Localized in `uniformity`, we have the notation `𝓢 X` for the separation relation on a uniform space `X`, ## Implementation notes The separation setoid `separation_setoid` is not declared as a global instance. It is made a local instance while building the theory of `separation_quotient`. The factored map `separation_quotient.lift f` is defined without imposing any condition on `f`, but returns junk if `f` is not uniformly continuous (constant junk hence it is always uniformly continuous). -/ open filter topological_space set classical function uniform_space open_locale classical topological_space uniformity filter noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] /-! ### Separated uniform spaces -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets localized "notation `𝓢` := separation_rel" in uniformity lemma separated_equiv : equivalence (λx y, (x, y) ∈ 𝓢 α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ 𝓢 α) (hyz : (y, z) ∈ 𝓢 α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ /-- A uniform space is separated if its separation relation is trivial (each point is related only to itself). -/ class separated_space (α : Type u) [uniform_space α] : Prop := (out : 𝓢 α = id_rel) theorem separated_space_iff {α : Type u} [uniform_space α] : separated_space α ↔ 𝓢 α = id_rel := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem separated_def {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated_space_iff, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall₂_congr $ λ x y, by rw ← not_imp_not; simp [not_forall] lemma eq_of_uniformity {α : Type*} [uniform_space α] [separated_space α] {x y : α} (h : ∀ {V}, V ∈ 𝓤 α → (x, y) ∈ V) : x = y := separated_def.mp ‹separated_space α› x y (λ _, h) lemma eq_of_uniformity_basis {α : Type*} [uniform_space α] [separated_space α] {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (hs : (𝓤 α).has_basis p s) {x y : α} (h : ∀ {i}, p i → (x, y) ∈ s i) : x = y := eq_of_uniformity (λ V V_in, let ⟨i, hi, H⟩ := hs.mem_iff.mp V_in in H (h hi)) lemma eq_of_forall_symmetric {α : Type*} [uniform_space α] [separated_space α] {x y : α} (h : ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (x, y) ∈ V) : x = y := eq_of_uniformity_basis has_basis_symmetric (by simpa [and_imp] using λ _, h) lemma id_rel_sub_separation_relation (α : Type*) [uniform_space α] : id_rel ⊆ 𝓢 α := begin unfold separation_rel, rw id_rel_subset, intros x, suffices : ∀ t ∈ 𝓤 α, (x, x) ∈ t, by simpa only [refl_mem_uniformity], exact λ t, refl_mem_uniformity, end lemma separation_rel_comap {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓢 α = (prod.map f f) ⁻¹' 𝓢 β := begin dsimp [separation_rel], simp_rw [uniformity_comap h, (filter.comap_has_basis (prod.map f f) (𝓤 β)).sInter_sets, ← preimage_Inter, sInter_eq_bInter], refl, end protected lemma filter.has_basis.separation_rel {ι : Sort*} {p : ι → Prop} {s : ι → set (α × α)} (h : has_basis (𝓤 α) p s) : 𝓢 α = ⋂ i (hi : p i), s i := by { unfold separation_rel, rw h.sInter_sets } lemma separation_rel_eq_inter_closure : 𝓢 α = ⋂₀ (closure '' (𝓤 α).sets) := by simp [uniformity_has_basis_closure.separation_rel] lemma is_closed_separation_rel : is_closed (𝓢 α) := begin rw separation_rel_eq_inter_closure, apply is_closed_sInter, rintros _ ⟨t, t_in, rfl⟩, exact is_closed_closure, end lemma separated_iff_t2 : separated_space α ↔ t2_space α := begin classical, split ; introI h, { rw [t2_iff_is_closed_diagonal, ← show 𝓢 α = diagonal α, from h.1], exact is_closed_separation_rel }, { rw separated_def', intros x y hxy, rcases t2_separation hxy with ⟨u, v, uo, vo, hx, hy, h⟩, rcases is_open_iff_ball_subset.1 uo x hx with ⟨r, hrU, hr⟩, exact ⟨r, hrU, λ H, disjoint_iff.2 h ⟨hr H, hy⟩⟩ } end @[priority 100] -- see Note [lower instance priority] instance separated_regular [separated_space α] : regular_space α := { t0 := by { haveI := separated_iff_t2.mp ‹_›, exact t1_space.t0_space.t0 }, regular := λs a hs ha, have sᶜ ∈ 𝓝 a, from is_open.mem_nhds hs.is_open_compl ha, have {p : α × α | p.1 = a → p.2 ∈ sᶜ} ∈ 𝓤 α, from mem_nhds_uniformity_iff_right.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have closure e ×ˢ closure e ⊆ comp_rel d (comp_rel (e ×ˢ e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_rfl) end, have e_subset : closure e ⊆ sᶜ, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ 𝓟 (closure e)ᶜ = ⊥, from (is_compl_principal (closure e)).inf_right_eq_bot_iff.2 (le_principal_iff.2 this), ⟨(closure e)ᶜ, is_closed_closure.is_open_compl, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..@t2_space.t1_space _ _ (separated_iff_t2.mp ‹_›) } lemma is_closed_of_spaced_out [separated_space α] {V₀ : set (α × α)} (V₀_in : V₀ ∈ 𝓤 α) {s : set α} (hs : s.pairwise (λ x y, (x, y) ∉ V₀)) : is_closed s := begin rcases comp_symm_mem_uniformity_sets V₀_in with ⟨V₁, V₁_in, V₁_symm, h_comp⟩, apply is_closed_of_closure_subset, intros x hx, rw mem_closure_iff_ball at hx, rcases hx V₁_in with ⟨y, hy, hy'⟩, suffices : x = y, by rwa this, apply eq_of_forall_symmetric, intros V V_in V_symm, rcases hx (inter_mem V₁_in V_in) with ⟨z, hz, hz'⟩, obtain rfl : z = y, { by_contra hzy, exact hs hz' hy' hzy (h_comp $ mem_comp_of_mem_ball V₁_symm (ball_inter_left x _ _ hz) hy) }, exact ball_inter_right x _ _ hz end lemma is_closed_range_of_spaced_out {ι} [separated_space α] {V₀ : set (α × α)} (V₀_in : V₀ ∈ 𝓤 α) {f : ι → α} (hf : pairwise (λ x y, (f x, f y) ∉ V₀)) : is_closed (range f) := is_closed_of_spaced_out V₀_in $ by { rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ h, exact hf x y (ne_of_apply_ne f h) } /-! ### Separated sets -/ /-- A set `s` in a uniform space `α` is separated if the separation relation `𝓢 α` induces the trivial relation on `s`. -/ def is_separated (s : set α) : Prop := ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y lemma is_separated_def (s : set α) : is_separated s ↔ ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y := iff.rfl lemma is_separated_def' (s : set α) : is_separated s ↔ (s ×ˢ s) ∩ 𝓢 α ⊆ id_rel := begin rw is_separated_def, split, { rintros h ⟨x, y⟩ ⟨⟨x_in, y_in⟩, H⟩, simp [h x x_in y y_in H] }, { intros h x x_in y y_in xy_in, rw ← mem_id_rel, exact h ⟨mk_mem_prod x_in y_in, xy_in⟩ } end lemma is_separated.mono {s t : set α} (hs : is_separated s) (hts : t ⊆ s) : is_separated t := λ x hx y hy, hs x (hts hx) y (hts hy) lemma univ_separated_iff : is_separated (univ : set α) ↔ separated_space α := begin simp only [is_separated, mem_univ, true_implies_iff, separated_space_iff], split, { intro h, exact subset.antisymm (λ ⟨x, y⟩ xy_in, h x y xy_in) (id_rel_sub_separation_relation α), }, { intros h x y xy_in, rwa h at xy_in }, end lemma is_separated_of_separated_space [separated_space α] (s : set α) : is_separated s := begin rw [is_separated, separated_space.out], tauto, end lemma is_separated_iff_induced {s : set α} : is_separated s ↔ separated_space s := begin rw separated_space_iff, change _ ↔ 𝓢 {x // x ∈ s} = _, rw [separation_rel_comap rfl, is_separated_def'], split; intro h, { ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, suffices : (x, y) ∈ 𝓢 α ↔ x = y, by simpa only [mem_id_rel], refine ⟨λ H, h ⟨mk_mem_prod x_in y_in, H⟩, _⟩, rintro rfl, exact id_rel_sub_separation_relation α rfl }, { rintros ⟨x, y⟩ ⟨⟨x_in, y_in⟩, hS⟩, have A : (⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩ : ↥s × ↥s) ∈ prod.map (coe : s → α) (coe : s → α) ⁻¹' 𝓢 α, from hS, simpa using h.subset A } end lemma eq_of_uniformity_inf_nhds_of_is_separated {s : set α} (hs : is_separated s) : ∀ {x y : α}, x ∈ s → y ∈ s → cluster_pt (x, y) (𝓤 α) → x = y := begin intros x y x_in y_in H, have : ∀ V ∈ 𝓤 α, (x, y) ∈ closure V, { intros V V_in, rw mem_closure_iff_cluster_pt, have : 𝓤 α ≤ 𝓟 V, by rwa le_principal_iff, exact H.mono this }, apply hs x x_in y y_in, simpa [separation_rel_eq_inter_closure], end lemma eq_of_uniformity_inf_nhds [separated_space α] : ∀ {x y : α}, cluster_pt (x, y) (𝓤 α) → x = y := begin have : is_separated (univ : set α), { rw univ_separated_iff, assumption }, introv, simpa using eq_of_uniformity_inf_nhds_of_is_separated this, end /-! ### Separation quotient -/ namespace uniform_space /-- The separation relation of a uniform space seen as a setoid. -/ def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ 𝓢 α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ 𝓢 α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_rfl lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ 𝓢 α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ 𝓢 α → (c, d) ∈ 𝓢 β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated_space (quotient (separation_setoid α)) := ⟨set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated_space β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h lemma _root_.is_separated.eq_of_uniform_continuous {f : α → β} {x y : α} {s : set β} (hs : is_separated s) (hxs : f x ∈ s) (hys : f y ∈ s) (H : uniform_continuous f) (h : x ≈ y) : f x = f y := (is_separated_def _).mp hs _ hxs _ hys $ λ _ h', h _ (H h') /-- The maximal separated quotient of a uniform space `α`. -/ def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance [inhabited α] : inhabited (separation_quotient α) := by unfold separation_quotient; apply_instance /-- Factoring functions to a separated space through the separation quotient. -/ def lift [separated_space β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (nonempty.some ⟨x.out⟩) lemma lift_mk [separated_space β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated_space β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end /-- The separation quotient functor acting on functions. -/ def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, rfl⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated_space α] [separated_space β] : separated_space (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) lemma _root_.is_separated.prod {s : set α} {t : set β} (hs : is_separated s) (ht : is_separated t) : is_separated (s ×ˢ t) := (is_separated_def _).mpr $ λ x hx y hy H, prod.ext (hs.eq_of_uniform_continuous hx.1 hy.1 uniform_continuous_fst H) (ht.eq_of_uniform_continuous hx.2 hy.2 uniform_continuous_snd H) end uniform_space
a265cf40e72a36feabcc4640e49a279c54292d83
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/src/Lean/PrettyPrinter/Delaborator/Basic.lean
df6d19261a9aedff0f4907a4428b80e71777f996
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,375
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.KeyedDeclsAttribute import Lean.ProjFns import Lean.Syntax import Lean.Meta.Match.Match import Lean.Elab.Term import Lean.PrettyPrinter.Delaborator.Options import Lean.PrettyPrinter.Delaborator.SubExpr import Lean.PrettyPrinter.Delaborator.TopDownAnalyze /-! The delaborator is the first stage of the pretty printer, and the inverse of the elaborator: it turns fully elaborated `Expr` core terms back into surface-level `Syntax`, omitting some implicit information again and using higher-level syntax abstractions like notations where possible. The exact behavior can be customized using pretty printer options; activating `pp.all` should guarantee that the delaborator is injective and that re-elaborating the resulting `Syntax` round-trips. Pretty printer options can be given not only for the whole term, but also specific subterms. This is used both when automatically refining pp options until round-trip and when interactively selecting pp options for a subterm (both TBD). The association of options to subterms is done by assigning a unique, synthetic Nat position to each subterm derived from its position in the full term. This position is added to the corresponding Syntax object so that elaboration errors and interactions with the pretty printer output can be traced back to the subterm. The delaborator is extensible via the `[delab]` attribute. -/ namespace Lean.PrettyPrinter.Delaborator open Lean.Meta SubExpr open Lean.Elab (Info TermInfo Info.ofTermInfo) structure Context where defaultOptions : Options optionsPerPos : OptionsPerPos currNamespace : Name openDecls : List OpenDecl inPattern : Bool := false -- true when delaborating `match` patterns subExpr : SubExpr structure State where /-- We attach `Elab.Info` at various locations in the `Syntax` output in order to convey its semantics. While the elaborator emits `InfoTree`s, here we have no real text location tree to traverse, so we use a flattened map. -/ infos : Std.RBMap Pos Info compare := {} /-- See `SubExpr.nextExtraPos`. -/ holeIter : SubExpr.HoleIterator := {} -- Exceptions from delaborators are not expected. We use an internal exception to signal whether -- the delaborator was able to produce a Syntax object. builtin_initialize delabFailureId : InternalExceptionId ← registerInternalExceptionId `delabFailure abbrev DelabM := ReaderT Context (StateRefT State MetaM) abbrev Delab := DelabM Syntax instance : Inhabited (DelabM α) where default := throw arbitrary @[inline] protected def orElse (d₁ : DelabM α) (d₂ : Unit → DelabM α) : DelabM α := do catchInternalId delabFailureId d₁ fun _ => d₂ () protected def failure : DelabM α := throw $ Exception.internal delabFailureId instance : Alternative DelabM where orElse := Delaborator.orElse failure := Delaborator.failure -- HACK: necessary since it would otherwise prefer the instance from MonadExcept instance {α} : OrElse (DelabM α) := ⟨Delaborator.orElse⟩ -- Low priority instances so `read`/`get`/etc default to the whole `Context`/`State` instance (priority := low) : MonadReaderOf SubExpr DelabM where read := Context.subExpr <$> read instance (priority := low) : MonadWithReaderOf SubExpr DelabM where withReader f x := fun ctx => x { ctx with subExpr := f ctx.subExpr } instance (priority := low) : MonadStateOf SubExpr.HoleIterator DelabM where get := State.holeIter <$> get set iter := modify fun ⟨infos, _⟩ => ⟨infos, iter⟩ modifyGet f := modifyGet fun ⟨infos, iter⟩ => let (ret, iter') := f iter; (ret, ⟨infos, iter'⟩) -- Macro scopes in the delaborator output are ultimately ignored by the pretty printer, -- so give a trivial implementation. instance : MonadQuotation DelabM := { getCurrMacroScope := pure arbitrary, getMainModule := pure arbitrary, withFreshMacroScope := fun x => x } unsafe def mkDelabAttribute : IO (KeyedDeclsAttribute Delab) := KeyedDeclsAttribute.init { builtinName := `builtinDelab, name := `delab, descr := "Register a delaborator. [delab k] registers a declaration of type `Lean.PrettyPrinter.Delaborator.Delab` for the `Lean.Expr` constructor `k`. Multiple delaborators for a single constructor are tried in turn until the first success. If the term to be delaborated is an application of a constant `c`, elaborators for `app.c` are tried first; this is also done for `Expr.const`s (\"nullary applications\") to reduce special casing. If the term is an `Expr.mdata` with a single key `k`, `mdata.k` is tried first.", valueTypeName := `Lean.PrettyPrinter.Delaborator.Delab } `Lean.PrettyPrinter.Delaborator.delabAttribute @[builtinInit mkDelabAttribute] constant delabAttribute : KeyedDeclsAttribute Delab def getExprKind : DelabM Name := do let e ← getExpr pure $ match e with | Expr.bvar _ _ => `bvar | Expr.fvar _ _ => `fvar | Expr.mvar _ _ => `mvar | Expr.sort _ _ => `sort | Expr.const c _ _ => -- we identify constants as "nullary applications" to reduce special casing `app ++ c | Expr.app fn _ _ => match fn.getAppFn with | Expr.const c _ _ => `app ++ c | _ => `app | Expr.lam _ _ _ _ => `lam | Expr.forallE _ _ _ _ => `forallE | Expr.letE _ _ _ _ _ => `letE | Expr.lit _ _ => `lit | Expr.mdata m _ _ => match m.entries with | [(key, _)] => `mdata ++ key | _ => `mdata | Expr.proj _ _ _ _ => `proj def getOptionsAtCurrPos : DelabM Options := do let ctx ← read let mut opts := ctx.defaultOptions if let some opts' ← ctx.optionsPerPos.find? (← getPos) then for (k, v) in opts' do opts := opts.insert k v opts /-- Evaluate option accessor, using subterm-specific options if set. -/ def getPPOption (opt : Options → Bool) : DelabM Bool := do return opt (← getOptionsAtCurrPos) def whenPPOption (opt : Options → Bool) (d : Delab) : Delab := do let b ← getPPOption opt if b then d else failure def whenNotPPOption (opt : Options → Bool) (d : Delab) : Delab := do let b ← getPPOption opt if b then failure else d partial def annotatePos (pos : Nat) : Syntax → Syntax | stx@(Syntax.ident _ _ _ _) => stx.setInfo (SourceInfo.synthetic pos pos) -- app => annotate function | stx@(Syntax.node `Lean.Parser.Term.app args) => stx.modifyArg 0 (annotatePos pos) -- otherwise, annotate first direct child token if any | stx => match stx.getArgs.findIdx? Syntax.isAtom with | some idx => stx.modifyArg idx (Syntax.setInfo (SourceInfo.synthetic pos pos)) | none => stx def annotateCurPos (stx : Syntax) : Delab := do annotatePos (← getPos) stx def getUnusedName (suggestion : Name) (body : Expr) : DelabM Name := do -- Use a nicer binder name than `[anonymous]`. We probably shouldn't do this in all LocalContext use cases, so do it here. let suggestion := if suggestion.isAnonymous then `a else suggestion; let suggestion := suggestion.eraseMacroScopes let lctx ← getLCtx if !lctx.usesUserName suggestion then return suggestion else if (← getPPOption getPPSafeShadowing) && !bodyUsesSuggestion lctx suggestion then return suggestion else return lctx.getUnusedName suggestion where bodyUsesSuggestion (lctx : LocalContext) (suggestion' : Name) : Bool := Option.isSome <| body.find? fun | Expr.fvar fvarId _ => match lctx.find? fvarId with | none => false | some decl => decl.userName == suggestion' | _ => false def withBindingBodyUnusedName {α} (d : Syntax → DelabM α) : DelabM α := do let n ← getUnusedName (← getExpr).bindingName! (← getExpr).bindingBody! let stxN ← annotateCurPos (mkIdent n) withBindingBody n $ d stxN @[inline] def liftMetaM {α} (x : MetaM α) : DelabM α := liftM x def addTermInfo (pos : Pos) (stx : Syntax) (e : Expr) (isBinder : Bool := false) : DelabM Unit := do let info ← mkTermInfo stx e isBinder modify fun s => { s with infos := s.infos.insert pos info } where mkTermInfo stx e isBinder := do Info.ofTermInfo { elaborator := `Delab, stx := stx, lctx := (← getLCtx), expectedType? := none, expr := e, isBinder := isBinder } def addFieldInfo (pos : Pos) (projName fieldName : Name) (stx : Syntax) (val : Expr) : DelabM Unit := do let info ← mkFieldInfo projName fieldName stx val modify fun s => { s with infos := s.infos.insert pos info } where mkFieldInfo projName fieldName stx val := do Info.ofFieldInfo { projName := projName, fieldName := fieldName, lctx := (← getLCtx), val := val, stx := stx } partial def delabFor : Name → Delab | Name.anonymous => failure | k => (do let stx ← (delabAttribute.getValues (← getEnv) k).firstM id let stx ← annotateCurPos stx addTermInfo (← getPos) stx (← getExpr) stx) -- have `app.Option.some` fall back to `app` etc. <|> delabFor k.getRoot partial def delab : Delab := do checkMaxHeartbeats "delab" let e ← getExpr -- no need to hide atomic proofs if ← !e.isAtomic <&&> !(← getPPOption getPPProofs) <&&> (try Meta.isProof e catch ex => false) then if ← getPPOption getPPProofsWithType then let stx ← withType delab return ← ``((_ : $stx)) else return ← ``(_) let k ← getExprKind let stx ← delabFor k <|> (liftM $ show MetaM Syntax from throwError "don't know how to delaborate '{k}'") if ← getPPOption getPPAnalyzeTypeAscriptions <&&> getPPOption getPPAnalysisNeedsType <&&> !e.isMData then let typeStx ← withType delab `(($stx:term : $typeStx:term)) >>= annotateCurPos else stx unsafe def mkAppUnexpanderAttribute : IO (KeyedDeclsAttribute Unexpander) := KeyedDeclsAttribute.init { name := `appUnexpander, descr := "Register an unexpander for applications of a given constant. [appUnexpander c] registers a `Lean.PrettyPrinter.Unexpander` for applications of the constant `c`. The unexpander is passed the result of pre-pretty printing the application *without* implicitly passed arguments. If `pp.explicit` is set to true or `pp.notation` is set to false, it will not be called at all.", valueTypeName := `Lean.PrettyPrinter.Unexpander evalKey := fun _ stx => do resolveGlobalConstNoOverloadCore (← Attribute.Builtin.getId stx) } `Lean.PrettyPrinter.Delaborator.appUnexpanderAttribute @[builtinInit mkAppUnexpanderAttribute] constant appUnexpanderAttribute : KeyedDeclsAttribute Unexpander end Delaborator open Delaborator (OptionsPerPos topDownAnalyze Pos) def delabCore (currNamespace : Name) (openDecls : List OpenDecl) (e : Expr) (optionsPerPos : OptionsPerPos := {}) : MetaM (Syntax × Std.RBMap Pos Elab.Info compare) := do trace[PrettyPrinter.delab.input] "{Std.format e}" let mut opts ← MonadOptions.getOptions -- default `pp.proofs` to `true` if `e` is a proof if pp.proofs.get? opts == none then try if ← Meta.isProof e then opts := pp.proofs.set opts true catch _ => pure () let e ← if getPPInstantiateMVars opts then ← Meta.instantiateMVars e else e let optionsPerPos ← if !getPPAll opts && getPPAnalyze opts && optionsPerPos.isEmpty then withTheReader Core.Context (fun ctx => { ctx with options := opts }) do topDownAnalyze e else optionsPerPos let (stx, {infos := infos, ..}) ← catchInternalId Delaborator.delabFailureId (Delaborator.delab { defaultOptions := opts optionsPerPos := optionsPerPos currNamespace := currNamespace openDecls := openDecls subExpr := Delaborator.SubExpr.mkRoot e } |>.run { : Delaborator.State }) (fun _ => unreachable!) return (stx, infos) /-- "Delaborate" the given term into surface-level syntax using the default and given subterm-specific options. -/ def delab (currNamespace : Name) (openDecls : List OpenDecl) (e : Expr) (optionsPerPos : OptionsPerPos := {}) : MetaM Syntax := do let (stx, _) ← delabCore currNamespace openDecls e optionsPerPos stx builtin_initialize registerTraceClass `PrettyPrinter.delab end Lean.PrettyPrinter
ad36397e61cab0d57157f32d02e2a9fa5c749cc4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/real/hyperreal.lean
fc7dcc328ccfb94dcf655455ad62176a8f2ce9d9
[ "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
38,026
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir -/ import order.filter.filter_product import analysis.specific_limits.basic /-! # Construction of the hyperreal numbers as an ultraproduct of real sequences. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open filter filter.germ open_locale topology classical /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ @[derive [linear_ordered_field, inhabited]] def hyperreal : Type := germ (hyperfilter ℕ : filter ℕ) ℝ namespace hyperreal notation `ℝ*` := hyperreal noncomputable instance : has_coe_t ℝ ℝ* := ⟨λ x, (↑x : germ _ _)⟩ @[simp, norm_cast] lemma coe_eq_coe {x y : ℝ} : (x : ℝ*) = y ↔ x = y := germ.const_inj lemma coe_ne_coe {x y : ℝ} : (x : ℝ*) ≠ y ↔ x ≠ y := coe_eq_coe.not @[simp, norm_cast] lemma coe_eq_zero {x : ℝ} : (x : ℝ*) = 0 ↔ x = 0 := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one {x : ℝ} : (x : ℝ*) = 1 ↔ x = 1 := coe_eq_coe @[norm_cast] lemma coe_ne_zero {x : ℝ} : (x : ℝ*) ≠ 0 ↔ x ≠ 0 := coe_ne_coe @[norm_cast] lemma coe_ne_one {x : ℝ} : (x : ℝ*) ≠ 1 ↔ x ≠ 1 := coe_ne_coe @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ) = (1 : ℝ*) := rfl @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ) = (0 : ℝ*) := rfl @[simp, norm_cast] lemma coe_inv (x : ℝ) : ↑(x⁻¹) = (x⁻¹ : ℝ*) := rfl @[simp, norm_cast] lemma coe_neg (x : ℝ) : ↑(-x) = (-x : ℝ*) := rfl @[simp, norm_cast] lemma coe_add (x y : ℝ) : ↑(x + y) = (x + y : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit0 (x : ℝ) : ↑(bit0 x) = (bit0 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit1 (x : ℝ) : ↑(bit1 x) = (bit1 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ) : ↑(x * y) = (x * y : ℝ*) := rfl @[simp, norm_cast] lemma coe_div (x y : ℝ) : ↑(x / y) = (x / y : ℝ*) := rfl @[simp, norm_cast] lemma coe_sub (x y : ℝ) : ↑(x - y) = (x - y : ℝ*) := rfl @[simp, norm_cast] lemma coe_le_coe {x y : ℝ} : (x : ℝ*) ≤ y ↔ x ≤ y := germ.const_le_iff @[simp, norm_cast] lemma coe_lt_coe {x y : ℝ} : (x : ℝ*) < y ↔ x < y := germ.const_lt_iff @[simp, norm_cast] lemma coe_nonneg {x : ℝ} : 0 ≤ (x : ℝ*) ↔ 0 ≤ x := coe_le_coe @[simp, norm_cast] lemma coe_pos {x : ℝ} : 0 < (x : ℝ*) ↔ 0 < x := coe_lt_coe @[simp, norm_cast] lemma coe_abs (x : ℝ) : ((|x| : ℝ) : ℝ*) = |x| := const_abs x @[simp, norm_cast] lemma coe_max (x y : ℝ) : ((max x y : ℝ) : ℝ*) = max x y := germ.const_max _ _ @[simp, norm_cast] lemma coe_min (x y : ℝ) : ((min x y : ℝ) : ℝ*) = min x y := germ.const_min _ _ /-- Construct a hyperreal number from a sequence of real numbers. -/ noncomputable def of_seq (f : ℕ → ℝ) : ℝ* := (↑f : germ (hyperfilter ℕ : filter ℕ) ℝ) /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := of_seq $ λ n, n⁻¹ /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := of_seq coe localized "notation (name := hyperreal.epsilon) `ε` := hyperreal.epsilon" in hyperreal localized "notation (name := hyperreal.omega) `ω` := hyperreal.omega" in hyperreal @[simp] lemma inv_omega : ω⁻¹ = ε := rfl @[simp] lemma inv_epsilon : ε⁻¹ = ω := @inv_inv _ _ ω lemma omega_pos : 0 < ω := germ.coe_pos.2 $ mem_hyperfilter_of_finite_compl $ begin convert set.finite_singleton 0, simp [set.eq_singleton_iff_unique_mem], end lemma epsilon_pos : 0 < ε := inv_pos_of_pos omega_pos lemma epsilon_ne_zero : ε ≠ 0 := epsilon_pos.ne' lemma omega_ne_zero : ω ≠ 0 := omega_pos.ne' theorem epsilon_mul_omega : ε * ω = 1 := @inv_mul_cancel _ _ ω omega_ne_zero lemma lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → of_seq f < (r : ℝ*) := begin simp only [metric.tendsto_at_top, real.dist_eq, sub_zero, lt_def] at hf ⊢, intros r hr, cases hf r hr with N hf', have hs : {i : ℕ | f i < r}ᶜ ⊆ {i : ℕ | i ≤ N} := λ i hi1, le_of_lt (by simp only [lt_iff_not_ge]; exact λ hi2, hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N), exact mem_hyperfilter_of_finite_compl ((set.finite_le_nat N).subset hs) end lemma neg_lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → (-r : ℝ*) < of_seq f := λ r hr, have hg : _ := hf.neg, neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr) lemma gt_of_tendsto_zero_of_neg {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r < 0 → (r : ℝ*) < of_seq f := λ r hr, by rw [←neg_neg r, coe_neg]; exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) lemma epsilon_lt_pos (x : ℝ) : 0 < x → ε < x := lt_of_tendsto_zero_of_pos tendsto_inverse_at_top_nhds_0_nat /-- Standard part predicate -/ def is_st (x : ℝ*) (r : ℝ) := ∀ δ : ℝ, 0 < δ → (r - δ : ℝ*) < x ∧ x < r + δ /-- Standard part function: like a "round" to ℝ instead of ℤ -/ noncomputable def st : ℝ* → ℝ := λ x, if h : ∃ r, is_st x r then classical.some h else 0 /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def infinitesimal (x : ℝ*) := is_st x 0 /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def infinite_pos (x : ℝ*) := ∀ r : ℝ, ↑r < x /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def infinite_neg (x : ℝ*) := ∀ r : ℝ, x < r /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def infinite (x : ℝ*) := infinite_pos x ∨ infinite_neg x /-! ### Some facts about `st` -/ private lemma is_st_unique' (x : ℝ*) (r s : ℝ) (hr : is_st x r) (hs : is_st x s) (hrs : r < s) : false := have hrs' : _ := half_pos $ sub_pos_of_lt hrs, have hr' : _ := (hr _ hrs').2, have hs' : _ := (hs _ hrs').1, have h : s - ((s - r) / 2) = r + (s - r) / 2 := by linarith, begin norm_cast at *, rw h at hs', exact not_lt_of_lt hs' hr' end theorem is_st_unique {x : ℝ*} {r s : ℝ} (hr : is_st x r) (hs : is_st x s) : r = s := begin rcases lt_trichotomy r s with h | h | h, { exact false.elim (is_st_unique' x r s hr hs h) }, { exact h }, { exact false.elim (is_st_unique' x s r hs hr h) } end theorem not_infinite_of_exists_st {x : ℝ*} : (∃ r : ℝ, is_st x r) → ¬ infinite x := λ he hi, Exists.dcases_on he $ λ r hr, hi.elim (λ hip, not_lt_of_lt (hr 2 zero_lt_two).2 (hip $ r + 2)) (λ hin, not_lt_of_lt (hr 2 zero_lt_two).1 (hin $ r - 2)) theorem is_st_Sup {x : ℝ*} (hni : ¬ infinite x) : is_st x (Sup {y : ℝ | (y : ℝ*) < x}) := let S : set ℝ := {y : ℝ | (y : ℝ*) < x} in let R : _ := Sup S in have hnile : _ := not_forall.mp (not_or_distrib.mp hni).1, have hnige : _ := not_forall.mp (not_or_distrib.mp hni).2, Exists.dcases_on hnile $ Exists.dcases_on hnige $ λ r₁ hr₁ r₂ hr₂, have HR₁ : S.nonempty := ⟨r₁ - 1, lt_of_lt_of_le (coe_lt_coe.2 $ sub_one_lt _) (not_lt.mp hr₁) ⟩, have HR₂ : bdd_above S := ⟨ r₂, λ y hy, le_of_lt (coe_lt_coe.1 (lt_of_lt_of_le hy (not_lt.mp hr₂))) ⟩, λ δ hδ, ⟨ lt_of_not_le $ λ c, have hc : ∀ y ∈ S, y ≤ R - δ := λ y hy, coe_le_coe.1 $ le_of_lt $ lt_of_lt_of_le hy c, not_lt_of_le (cSup_le HR₁ hc) $ sub_lt_self R hδ, lt_of_not_le $ λ c, have hc : ↑(R + δ / 2) < x := lt_of_lt_of_le (add_lt_add_left (coe_lt_coe.2 (half_lt_self hδ)) R) c, not_lt_of_le (le_cSup HR₂ hc) $ (lt_add_iff_pos_right _).mpr $ half_pos hδ⟩ theorem exists_st_of_not_infinite {x : ℝ*} (hni : ¬ infinite x) : ∃ r : ℝ, is_st x r := ⟨Sup {y : ℝ | (y : ℝ*) < x}, is_st_Sup hni⟩ theorem st_eq_Sup {x : ℝ*} : st x = Sup {y : ℝ | (y : ℝ*) < x} := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) (is_st_Sup (not_infinite_of_exists_st h)) }, { cases not_imp_comm.mp exists_st_of_not_infinite h with H H, { rw (set.ext (λ i, ⟨λ hi, set.mem_univ i, λ hi, H i⟩) : {y : ℝ | (y : ℝ*) < x} = set.univ), exact real.Sup_univ.symm }, { rw (set.ext (λ i, ⟨λ hi, false.elim (not_lt_of_lt (H i) hi), λ hi, false.elim (set.not_mem_empty i hi)⟩) : {y : ℝ | (y : ℝ*) < x} = ∅), exact real.Sup_empty.symm } } end theorem exists_st_iff_not_infinite {x : ℝ*} : (∃ r : ℝ, is_st x r) ↔ ¬ infinite x := ⟨ not_infinite_of_exists_st, exists_st_of_not_infinite ⟩ theorem infinite_iff_not_exists_st {x : ℝ*} : infinite x ↔ ¬ ∃ r : ℝ, is_st x r := iff_not_comm.mp exists_st_iff_not_infinite theorem st_infinite {x : ℝ*} (hi : infinite x) : st x = 0 := begin unfold st, split_ifs, { exact false.elim ((infinite_iff_not_exists_st.mp hi) h) }, { refl } end lemma st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : st x = r := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) hxr }, { exact false.elim (h ⟨r, hxr⟩) } end lemma is_st_st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st x (st x) := by rwa [st_of_is_st hxr] lemma is_st_st_of_exists_st {x : ℝ*} (hx : ∃ r : ℝ, is_st x r) : is_st x (st x) := Exists.dcases_on hx (λ r, is_st_st_of_is_st) lemma is_st_st {x : ℝ*} (hx : st x ≠ 0) : is_st x (st x) := begin unfold st, split_ifs, { exact classical.some_spec h }, { exact false.elim (hx (by unfold st; split_ifs; refl)) } end lemma is_st_st' {x : ℝ*} (hx : ¬ infinite x) : is_st x (st x) := is_st_st_of_exists_st $ exists_st_of_not_infinite hx lemma is_st_refl_real (r : ℝ) : is_st r r := λ δ hδ, ⟨ sub_lt_self _ (coe_lt_coe.2 hδ), (lt_add_of_pos_right _ (coe_lt_coe.2 hδ)) ⟩ lemma st_id_real (r : ℝ) : st r = r := st_of_is_st (is_st_refl_real r) lemma eq_of_is_st_real {r s : ℝ} : is_st r s → r = s := is_st_unique (is_st_refl_real r) lemma is_st_real_iff_eq {r s : ℝ} : is_st r s ↔ r = s := ⟨eq_of_is_st_real, λ hrs, by rw [hrs]; exact is_st_refl_real s⟩ lemma is_st_symm_real {r s : ℝ} : is_st r s ↔ is_st s r := by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm] lemma is_st_trans_real {r s t : ℝ} : is_st r s → is_st s t → is_st r t := by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq]; exact eq.trans lemma is_st_inj_real {r₁ r₂ s : ℝ} (h1 : is_st r₁ s) (h2 : is_st r₂ s) : r₁ = r₂ := eq.trans (eq_of_is_st_real h1) (eq_of_is_st_real h2).symm lemma is_st_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : is_st x r ↔ ∀ (δ : ℝ), 0 < δ → |x - r| < δ := by simp only [abs_sub_lt_iff, sub_lt_iff_lt_add, is_st, and_comm, add_comm] lemma is_st_add {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x + y) (r + s) := λ hxr hys d hd, have hxr' : _ := hxr (d / 2) (half_pos hd), have hys' : _ := hys (d / 2) (half_pos hd), ⟨by convert add_lt_add hxr'.1 hys'.1 using 1; norm_cast; linarith, by convert add_lt_add hxr'.2 hys'.2 using 1; norm_cast; linarith⟩ lemma is_st_neg {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st (-x) (-r) := λ d hd, show -(r : ℝ*) - d < -x ∧ -x < -r + d, by cases (hxr d hd); split; linarith lemma is_st_sub {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x - y) (r - s) := λ hxr hys, by rw [sub_eq_add_neg, sub_eq_add_neg]; exact is_st_add hxr (is_st_neg hys) /- (st x < st y) → (x < y) → (x ≤ y) → (st x ≤ st y) -/ lemma lt_of_is_st_lt {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : r < s → x < y := λ hrs, have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs), have hxr' : _ := (hxr _ hrs').2, have hys' : _ := (hys _ hrs').1, have H1 : r + ((s - r) / 2) = (r + s) / 2 := by linarith, have H2 : s - ((s - r) / 2) = (r + s) / 2 := by linarith, begin norm_cast at *, rw H1 at hxr', rw H2 at hys', exact lt_trans hxr' hys' end lemma is_st_le_of_le {x y : ℝ*} {r s : ℝ} (hrx : is_st x r) (hsy : is_st y s) : x ≤ y → r ≤ s := by rw [←not_lt, ←not_lt, not_imp_not]; exact lt_of_is_st_lt hsy hrx lemma st_le_of_le {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : x ≤ y → st x ≤ st y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, is_st_le_of_le hx' hy' lemma lt_of_st_lt {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : st x < st y → x < y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, lt_of_is_st_lt hx' hy' /-! ### Basic lemmas about infinite -/ lemma infinite_pos_def {x : ℝ*} : infinite_pos x ↔ ∀ r : ℝ, ↑r < x := by rw iff_eq_eq; refl lemma infinite_neg_def {x : ℝ*} : infinite_neg x ↔ ∀ r : ℝ, x < r := by rw iff_eq_eq; refl lemma ne_zero_of_infinite {x : ℝ*} : infinite x → x ≠ 0 := λ hI h0, or.cases_on hI (λ hip, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_pos 0) 0)) (λ hin, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_neg 0) 0)) lemma not_infinite_zero : ¬ infinite 0 := λ hI, ne_zero_of_infinite hI rfl lemma pos_of_infinite_pos {x : ℝ*} : infinite_pos x → 0 < x := λ hip, hip 0 lemma neg_of_infinite_neg {x : ℝ*} : infinite_neg x → x < 0 := λ hin, hin 0 lemma not_infinite_pos_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinite_pos x := λ hn hp, not_lt_of_lt (hn 1) (hp 1) lemma not_infinite_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinite_neg x := imp_not_comm.mp not_infinite_pos_of_infinite_neg lemma infinite_neg_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → infinite_neg (-x) := λ hp r, neg_lt.mp (hp (-r)) lemma infinite_pos_neg_of_infinite_neg {x : ℝ*} : infinite_neg x → infinite_pos (-x) := λ hp r, lt_neg.mp (hp (-r)) lemma infinite_pos_iff_infinite_neg_neg {x : ℝ*} : infinite_pos x ↔ infinite_neg (-x) := ⟨ infinite_neg_neg_of_infinite_pos, λ hin, neg_neg x ▸ infinite_pos_neg_of_infinite_neg hin ⟩ lemma infinite_neg_iff_infinite_pos_neg {x : ℝ*} : infinite_neg x ↔ infinite_pos (-x) := ⟨ infinite_pos_neg_of_infinite_neg, λ hin, neg_neg x ▸ infinite_neg_neg_of_infinite_pos hin ⟩ lemma infinite_iff_infinite_neg {x : ℝ*} : infinite x ↔ infinite (-x) := ⟨ λ hi, or.cases_on hi (λ hip, or.inr (infinite_neg_neg_of_infinite_pos hip)) (λ hin, or.inl (infinite_pos_neg_of_infinite_neg hin)), λ hi, or.cases_on hi (λ hipn, or.inr (infinite_neg_iff_infinite_pos_neg.mpr hipn)) (λ hinp, or.inl (infinite_pos_iff_infinite_neg_neg.mpr hinp))⟩ lemma not_infinite_of_infinitesimal {x : ℝ*} : infinitesimal x → ¬ infinite x := λ hi hI, have hi' : _ := (hi 2 zero_lt_two), or.dcases_on hI (λ hip, have hip' : _ := hip 2, not_lt_of_lt hip' (by convert hi'.2; exact (zero_add 2).symm)) (λ hin, have hin' : _ := hin (-2), not_lt_of_lt hin' (by convert hi'.1; exact (zero_sub 2).symm)) lemma not_infinitesimal_of_infinite {x : ℝ*} : infinite x → ¬ infinitesimal x := imp_not_comm.mp not_infinite_of_infinitesimal lemma not_infinitesimal_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinitesimal x := λ hp, not_infinitesimal_of_infinite (or.inl hp) lemma not_infinitesimal_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinitesimal x := λ hn, not_infinitesimal_of_infinite (or.inr hn) lemma infinite_pos_iff_infinite_and_pos {x : ℝ*} : infinite_pos x ↔ (infinite x ∧ 0 < x) := ⟨ λ hip, ⟨or.inl hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hip, hip) (λ hin, false.elim (not_lt_of_lt hp (hin 0))) ⟩ lemma infinite_neg_iff_infinite_and_neg {x : ℝ*} : infinite_neg x ↔ (infinite x ∧ x < 0) := ⟨ λ hip, ⟨or.inr hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hin, false.elim (not_lt_of_lt hp (hin 0))) (λ hip, hip) ⟩ lemma infinite_pos_iff_infinite_of_pos {x : ℝ*} (hp : 0 < x) : infinite_pos x ↔ infinite x := by rw [infinite_pos_iff_infinite_and_pos]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hp⟩⟩ lemma infinite_pos_iff_infinite_of_nonneg {x : ℝ*} (hp : 0 ≤ x) : infinite_pos x ↔ infinite x := or.cases_on (lt_or_eq_of_le hp) (infinite_pos_iff_infinite_of_pos) (λ h, by rw h.symm; exact ⟨λ hIP, false.elim (not_infinite_zero (or.inl hIP)), λ hI, false.elim (not_infinite_zero hI)⟩) lemma infinite_neg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : infinite_neg x ↔ infinite x := by rw [infinite_neg_iff_infinite_and_neg]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hn⟩⟩ lemma infinite_pos_abs_iff_infinite_abs {x : ℝ*} : infinite_pos (|x|) ↔ infinite (|x|) := infinite_pos_iff_infinite_of_nonneg (abs_nonneg _) lemma infinite_iff_infinite_pos_abs {x : ℝ*} : infinite x ↔ infinite_pos (|x|) := ⟨ λ hi d, or.cases_on hi (λ hip, by rw [abs_of_pos (hip 0)]; exact hip d) (λ hin, by rw [abs_of_neg (hin 0)]; exact lt_neg.mp (hin (-d))), λ hipa, by { rcases (lt_trichotomy x 0) with h | h | h, { exact or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa abs_of_neg h at hipa)) }, { exact false.elim (ne_zero_of_infinite (or.inl (by rw [h]; rwa [h, abs_zero] at hipa)) h) }, { exact or.inl (by rwa abs_of_pos h at hipa) } } ⟩ lemma infinite_iff_infinite_abs {x : ℝ*} : infinite x ↔ infinite (|x|) := by rw [←infinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs] lemma infinite_iff_abs_lt_abs {x : ℝ*} : infinite x ↔ ∀ r : ℝ, (|r| : ℝ*) < |x| := ⟨ λ hI r, (coe_abs r) ▸ infinite_iff_infinite_pos_abs.mp hI (|r|), λ hR, or.cases_on (max_choice x (-x)) (λ h, or.inl $ λ r, lt_of_le_of_lt (le_abs_self _) (h ▸ (hR r))) (λ h, or.inr $ λ r, neg_lt_neg_iff.mp $ lt_of_le_of_lt (neg_le_abs_self _) (h ▸ (hR r)))⟩ lemma infinite_pos_add_not_infinite_neg {x y : ℝ*} : infinite_pos x → ¬ infinite_neg y → infinite_pos (x + y) := begin intros hip hnin r, cases not_forall.mp hnin with r₂ hr₂, convert add_lt_add_of_lt_of_le (hip (r + -r₂)) (not_lt.mp hr₂) using 1, simp end lemma not_infinite_neg_add_infinite_pos {x y : ℝ*} : ¬ infinite_neg x → infinite_pos y → infinite_pos (x + y) := λ hx hy, by rw [add_comm]; exact infinite_pos_add_not_infinite_neg hy hx lemma infinite_neg_add_not_infinite_pos {x y : ℝ*} : infinite_neg x → ¬ infinite_pos y → infinite_neg (x + y) := by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y, @infinite_neg_iff_infinite_pos_neg (x + y), neg_add]; exact infinite_pos_add_not_infinite_neg lemma not_infinite_pos_add_infinite_neg {x y : ℝ*} : ¬ infinite_pos x → infinite_neg y → infinite_neg (x + y) := λ hx hy, by rw [add_comm]; exact infinite_neg_add_not_infinite_pos hy hx lemma infinite_pos_add_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_infinite_neg_of_infinite_pos hy) lemma infinite_neg_add_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_infinite_pos_of_infinite_neg hy) lemma infinite_pos_add_not_infinite {x y : ℝ*} : infinite_pos x → ¬ infinite y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_or_distrib.mp hy).2 lemma infinite_neg_add_not_infinite {x y : ℝ*} : infinite_neg x → ¬ infinite y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_or_distrib.mp hy).1 theorem infinite_pos_of_tendsto_top {f : ℕ → ℝ} (hf : tendsto f at_top at_top) : infinite_pos (of_seq f) := λ r, have hf' : _ := tendsto_at_top_at_top.mp hf, Exists.cases_on (hf' (r + 1)) $ λ i hi, have hi' : ∀ (a : ℕ), f a < (r + 1) → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | r < f a}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))), germ.coe_lt.2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS theorem infinite_neg_of_tendsto_bot {f : ℕ → ℝ} (hf : tendsto f at_top at_bot) : infinite_neg (of_seq f) := λ r, have hf' : _ := tendsto_at_top_at_bot.mp hf, Exists.cases_on (hf' (r - 1)) $ λ i hi, have hi' : ∀ (a : ℕ), r - 1 < f a → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | f a < r}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)), germ.coe_lt.2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS lemma not_infinite_neg {x : ℝ*} : ¬ infinite x → ¬ infinite (-x) := not_imp_not.mpr infinite_iff_infinite_neg.mpr lemma not_infinite_add {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x + y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s + r, is_st_add hs hr⟩ theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : ¬ infinite x ↔ ∃ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨ λ hni, Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).1) $ Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).2) $ λ r hr s hs, by rw [not_lt] at hr hs; exact ⟨r - 1, s + 1, ⟨ lt_of_lt_of_le (by rw sub_eq_add_neg; norm_num) hr, lt_of_le_of_lt hs (by norm_num)⟩ ⟩, λ hrs, Exists.dcases_on hrs $ λ r hr, Exists.dcases_on hr $ λ s hs, not_or_distrib.mpr ⟨not_forall.mpr ⟨s, lt_asymm (hs.2)⟩, not_forall.mpr ⟨r, lt_asymm (hs.1) ⟩⟩⟩ theorem not_infinite_real (r : ℝ) : ¬ infinite r := by rw not_infinite_iff_exist_lt_gt; exact ⟨ r - 1, r + 1, coe_lt_coe.2 $ sub_one_lt r, coe_lt_coe.2 $ lt_add_one r⟩ theorem not_real_of_infinite {x : ℝ*} : infinite x → ∀ r : ℝ, x ≠ r := λ hi r hr, not_infinite_real r $ @eq.subst _ infinite _ _ hr hi /-! ### Facts about `st` that require some infinite machinery -/ private lemma is_st_mul' {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) (hs : s ≠ 0) : is_st (x * y) (r * s) := have hxr' : _ := is_st_iff_abs_sub_lt_delta.mp hxr, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys, have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, is_st_iff_abs_sub_lt_delta.mpr $ λ d hd, calc |x * y - r * s| = |x * (y - s) + (x - r) * s| : by rw [mul_sub, sub_mul, add_sub, sub_add_cancel] ... ≤ |x * (y - s)| + |(x - r) * s| : abs_add _ _ ... ≤ |x| * |y - s| + |x - r| * |s| : by simp only [abs_mul] ... ≤ |x| * ((d / t) / 2 : ℝ) + ((d / |s|) / 2 : ℝ) * |s| : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt $ hys' _ $ half_pos $ div_pos hd $ coe_pos.1 $ lt_of_le_of_lt (abs_nonneg x) ht) $ abs_nonneg _) (mul_le_mul_of_nonneg_right (le_of_lt $ hxr' _ $ half_pos $ div_pos hd $ abs_pos.2 hs) $ abs_nonneg _) ... = (d / 2 * (|x| / t) + d / 2 : ℝ*) : by { push_cast [-filter.germ.const_div], -- TODO: Why wasn't `hyperreal.coe_div` used? have : (|s| : ℝ*) ≠ 0, by simpa, have : (2 : ℝ*) ≠ 0 := two_ne_zero, field_simp [*, add_mul, mul_add, mul_assoc, mul_comm, mul_left_comm] } ... < (d / 2 * 1 + d / 2 : ℝ*) : add_lt_add_right (mul_lt_mul_of_pos_left ((div_lt_one $ lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) $ half_pos $ coe_pos.2 hd) _ ... = (d : ℝ*) : by rw [mul_one, add_halves] lemma is_st_mul {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : is_st (x * y) (r * s) := have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, begin by_cases hs : s = 0, { apply is_st_iff_abs_sub_lt_delta.mpr, intros d hd, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t) (div_pos hd (coe_pos.1 (lt_of_le_of_lt (abs_nonneg x) ht))), rw [hs, coe_zero, sub_zero] at hys', rw [hs, mul_zero, coe_zero, sub_zero, abs_mul, mul_comm, ←div_mul_cancel (d : ℝ*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)), ←coe_div], exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) }, exact is_st_mul' hxr hys hs, end --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY lemma not_infinite_mul {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x * y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s * r, is_st_mul hs hr⟩ --- lemma st_add {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x + y) = st x + st y := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_add hx hy), have hxy' : _ := is_st_add hx' hy', is_st_unique hxy hxy' lemma st_neg (x : ℝ*) : st (-x) = - st x := if h : infinite x then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero] else is_st_unique (is_st_st' (not_infinite_neg h)) (is_st_neg (is_st_st' h)) lemma st_mul {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x * y) = (st x) * (st y) := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_mul hx hy), have hxy' : _ := is_st_mul hx' hy', is_st_unique hxy hxy' /-! ### Basic lemmas about infinitesimal -/ theorem infinitesimal_def {x : ℝ*} : infinitesimal x ↔ (∀ r : ℝ, 0 < r → -(r : ℝ*) < x ∧ x < r) := ⟨ λ hi r hr, by { convert (hi r hr); simp }, λ hi d hd, by { convert (hi d hd); simp } ⟩ theorem lt_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, 0 < r → x < r := λ hi r hr, ((infinitesimal_def.mp hi) r hr).2 theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, 0 < r → -↑r < x := λ hi r hr, ((infinitesimal_def.mp hi) r hr).1 theorem gt_of_neg_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r < 0 → ↑r < x := λ hi r hr, by convert ((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1; exact (neg_neg ↑r).symm theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : infinitesimal x ↔ ∀ r : ℝ, r ≠ 0 → |x| < |r| := ⟨ λ hi r hr, abs_lt.mpr (by rw ←coe_abs; exact infinitesimal_def.mp hi (|r|) (abs_pos.2 hr)), λ hR, infinitesimal_def.mpr $ λ r hr, abs_lt.mp $ (abs_of_pos $ coe_pos.2 hr) ▸ hR r $ ne_of_gt hr ⟩ lemma infinitesimal_zero : infinitesimal 0 := is_st_refl_real 0 lemma zero_of_infinitesimal_real {r : ℝ} : infinitesimal r → r = 0 := eq_of_is_st_real lemma zero_iff_infinitesimal_real {r : ℝ} : infinitesimal r ↔ r = 0 := ⟨zero_of_infinitesimal_real, λ hr, by rw hr; exact infinitesimal_zero⟩ lemma infinitesimal_add {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x + y) := by simpa only [add_zero] using is_st_add hx hy lemma infinitesimal_neg {x : ℝ*} (hx : infinitesimal x) : infinitesimal (-x) := by simpa only [neg_zero] using is_st_neg hx lemma infinitesimal_neg_iff {x : ℝ*} : infinitesimal x ↔ infinitesimal (-x) := ⟨infinitesimal_neg, λ h, (neg_neg x) ▸ @infinitesimal_neg (-x) h⟩ lemma infinitesimal_mul {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x * y) := by simpa only [mul_zero] using is_st_mul hx hy theorem infinitesimal_of_tendsto_zero {f : ℕ → ℝ} : tendsto f at_top (𝓝 0) → infinitesimal (of_seq f) := λ hf d hd, by rw [sub_eq_add_neg, ←coe_neg, ←coe_add, ←coe_add, zero_add, zero_add]; exact ⟨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hd⟩ theorem infinitesimal_epsilon : infinitesimal ε := infinitesimal_of_tendsto_zero tendsto_inverse_at_top_nhds_0_nat lemma not_real_of_infinitesimal_ne_zero (x : ℝ*) : infinitesimal x → x ≠ 0 → ∀ r : ℝ, x ≠ r := λ hi hx r hr, hx $ hr.trans $ coe_eq_zero.2 $ is_st_unique (hr.symm ▸ is_st_refl_real r : is_st x r) hi theorem infinitesimal_sub_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : infinitesimal (x - r) := show is_st (x - r) 0, by { rw [sub_eq_add_neg, ← add_neg_self r], exact is_st_add hxr (is_st_refl_real (-r)) } theorem infinitesimal_sub_st {x : ℝ*} (hx : ¬infinite x) : infinitesimal (x - st x) := infinitesimal_sub_is_st $ is_st_st' hx lemma infinite_pos_iff_infinitesimal_inv_pos {x : ℝ*} : infinite_pos x ↔ (infinitesimal x⁻¹ ∧ 0 < x⁻¹) := ⟨ λ hip, ⟨ infinitesimal_def.mpr $ λ r hr, ⟨ lt_trans (coe_lt_coe.2 (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)), (inv_lt (coe_lt_coe.2 hr) (hip 0)).mp (by convert hip r⁻¹) ⟩, inv_pos.2 $ hip 0 ⟩, λ ⟨hi, hp⟩ r, @classical.by_cases (r = 0) (↑r < x) (λ h, eq.substr h (inv_pos.mp hp)) $ λ h, lt_of_le_of_lt (coe_le_coe.2 (le_abs_self r)) ((inv_lt_inv (inv_pos.mp hp) (coe_lt_coe.2 (abs_pos.2 h))).mp ((infinitesimal_def.mp hi) ((|r|)⁻¹) (inv_pos.2 (abs_pos.2 h))).2) ⟩ lemma infinite_neg_iff_infinitesimal_inv_neg {x : ℝ*} : infinite_neg x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ < 0) := ⟨ λ hin, have hin' : _ := infinite_pos_iff_infinitesimal_inv_pos.mp (infinite_pos_neg_of_infinite_neg hin), by rwa [infinitesimal_neg_iff, ←neg_pos, neg_inv], λ hin, by rwa [←neg_pos, infinitesimal_neg_iff, neg_inv, ←infinite_pos_iff_infinitesimal_inv_pos, ←infinite_neg_iff_infinite_pos_neg] at hin ⟩ theorem infinitesimal_inv_of_infinite {x : ℝ*} : infinite x → infinitesimal x⁻¹ := λ hi, or.cases_on hi (λ hip, (infinite_pos_iff_infinitesimal_inv_pos.mp hip).1) (λ hin, (infinite_neg_iff_infinitesimal_inv_neg.mp hin).1) theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) (hi : infinitesimal x⁻¹ ) : infinite x := begin cases (lt_or_gt_of_ne h0) with hn hp, { exact or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_lt_zero.mpr hn⟩) }, { exact or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos.mpr hp⟩) } end theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) : infinite x ↔ infinitesimal x⁻¹ := ⟨ infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0 ⟩ lemma infinitesimal_pos_iff_infinite_pos_inv {x : ℝ*} : infinite_pos x⁻¹ ↔ (infinitesimal x ∧ 0 < x) := by convert infinite_pos_iff_infinitesimal_inv_pos; simp only [inv_inv] lemma infinitesimal_neg_iff_infinite_neg_inv {x : ℝ*} : infinite_neg x⁻¹ ↔ (infinitesimal x ∧ x < 0) := by convert infinite_neg_iff_infinitesimal_inv_neg; simp only [inv_inv] theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x ≠ 0) : infinitesimal x ↔ infinite x⁻¹ := by convert (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm; simp only [inv_inv] /-! ### `st` stuff that requires infinitesimal machinery -/ theorem is_st_of_tendsto {f : ℕ → ℝ} {r : ℝ} (hf : tendsto f at_top (𝓝 r)) : is_st (of_seq f) r := have hg : tendsto (λ n, f n - r) at_top (𝓝 0) := (sub_self r) ▸ (hf.sub tendsto_const_nhds), by rw [←(zero_add r), ←(sub_add_cancel f (λ n, r))]; exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r) lemma is_st_inv {x : ℝ*} {r : ℝ} (hi : ¬ infinitesimal x) : is_st x r → is_st x⁻¹ r⁻¹ := λ hxr, have h : x ≠ 0 := (λ h, hi (h.symm ▸ infinitesimal_zero)), have H : _ := exists_st_of_not_infinite $ not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi, Exists.cases_on H $ λ s hs, have H' : is_st 1 (r * s) := mul_inv_cancel h ▸ is_st_mul hxr hs, have H'' : s = r⁻¹ := one_div r ▸ eq_one_div_of_mul_eq_one_right (eq_of_is_st_real H').symm, H'' ▸ hs lemma st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := begin by_cases h0 : x = 0, rw [h0, inv_zero, ←coe_zero, st_id_real, inv_zero], by_cases h1 : infinitesimal x, rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero], by_cases h2 : infinite x, rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero], exact st_of_is_st (is_st_inv h1 (is_st_st' h2)), end /-! ### Infinite stuff that requires infinitesimal machinery -/ lemma infinite_pos_omega : infinite_pos ω := infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ lemma infinite_omega : infinite ω := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon lemma infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → 0 < y → infinite_pos (x * y) := λ hx hy₁ hy₂ r, have hy₁' : _ := not_forall.mp (by rw infinitesimal_def at hy₁; exact hy₁), Exists.dcases_on hy₁' $ λ r₁ hy₁'', have hyr : _ := by rw [not_imp, ←abs_lt, not_lt, abs_of_pos hy₂] at hy₁''; exact hy₁'', by rw [←div_mul_cancel r (ne_of_gt hyr.1), coe_mul]; exact mul_lt_mul (hx (r / r₁)) hyr.2 (coe_lt_coe.2 hyr.1) (le_of_lt (hx 0)) lemma infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_pos y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → y < 0 → infinite_pos (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, ←neg_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_neg y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → y < 0 → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_pos y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → 0 < y → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_neg y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_neg_mul_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_pos_mul_infinite_neg {x y : ℝ*} : infinite_pos x → infinite_neg y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_neg_mul_infinite_pos {x y : ℝ*} : infinite_neg x → infinite_pos y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : infinite x → ¬ infinitesimal y → infinite (x * y) := λ hx hy, have h0 : y < 0 ∨ 0 < y := lt_or_gt_of_ne (λ H0, hy (eq.substr H0 (is_st_refl_real 0))), or.dcases_on hx (or.dcases_on h0 (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hx hy H0))) (or.dcases_on h0 (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hx hy H0))) lemma infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : ¬ infinitesimal x → infinite y → infinite (x * y) := λ hx hy, by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx lemma infinite.mul {x y : ℝ*} : infinite x → infinite y → infinite (x * y) := λ hx hy, infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy) end hyperreal namespace tactic open positivity private lemma hyperreal_coe_ne_zero {r : ℝ} : r ≠ 0 → (r : ℝ*) ≠ 0 := hyperreal.coe_ne_zero.2 private lemma hyperreal_coe_nonneg {r : ℝ} : 0 ≤ r → 0 ≤ (r : ℝ*) := hyperreal.coe_nonneg.2 private lemma hyperreal_coe_pos {r : ℝ} : 0 < r → 0 < (r : ℝ*) := hyperreal.coe_pos.2 /-- Extension for the `positivity` tactic: cast from `ℝ` to `ℝ*`. -/ @[positivity] meta def positivity_coe_real_hyperreal : expr → tactic strictness | `(@coe _ _ %%inst %%a) := do unify inst `(@coe_to_lift _ _ hyperreal.has_coe_t), strictness_a ← core a, match strictness_a with | positive p := positive <$> mk_app ``hyperreal_coe_pos [p] | nonnegative p := nonnegative <$> mk_app ``hyperreal_coe_nonneg [p] | nonzero p := nonzero <$> mk_app ``hyperreal_coe_ne_zero [p] end | e := pp e >>= fail ∘ format.bracket "The expression " " is not of the form `(r : ℝ*)` for `r : ℝ`" end tactic
0bd84e6e6d1f6ebf15099b3e5c60b7d5375295f5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/unreachable.lean
97731acb7f5627ea829f2b25c2118448e60d47e5
[ "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
84
lean
def False.elim' {C : Sort u} (h : False) : C := h.rec def main: IO Unit := pure ()
11c75b42f7e78a6ae5ade80c48ce8a197f3219c5
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/linear_algebra/basic.lean
1dea3d8d32dd35e563f99fd871a9f5460cc0ab45
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
57,927
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 Basics of linear algebra. This sets up the "categorical/lattice structure" of modules, submodules, and linear maps. -/ import algebra.pi_instances data.finsupp order.order_iso open function lattice reserve infix `≃ₗ` : 50 universes u v w x y z variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type y} {ε : Type z} {ι : Type x} namespace finset lemma smul_sum [ring γ] [add_comm_group β] [module γ β] {s : finset α} {a : γ} {f : α → β} : a • (s.sum f) = s.sum (λc, a • f c) := (finset.sum_hom ((•) a)).symm end finset namespace finsupp lemma smul_sum [has_zero β] [ring γ] [add_comm_group δ] [module γ δ] {v : α →₀ β} {c : γ} {h : α → β → δ} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp namespace linear_map section variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] [add_comm_group ε] variables [module α β] [module α γ] [module α δ] [module α ε] variables (f g : β →ₗ[α] γ) include α @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl theorem comp_assoc (g : γ →ₗ[α] δ) (h : δ →ₗ[α] ε) : (h.comp g).comp f = h.comp (g.comp f) := rfl def cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (h : ∀c, f c ∈ p) : γ →ₗ[α] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule α β) (f : γ →ₗ[α] β) {h} (x : γ) : (cod_restrict p f h x : β) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule α γ) (h : ∀b, f b ∈ p) (g : δ →ₗ[α] β) : (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 α γ) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl def inverse (g : γ → β) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : γ →ₗ[α] β := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂], λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩ instance : has_zero (β →ₗ[α] γ) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ @[simp] lemma zero_apply (x : β) : (0 : β →ₗ[α] γ) x = 0 := rfl instance : has_neg (β →ₗ[α] γ) := ⟨λ f, ⟨λ b, - f b, by simp, by simp⟩⟩ @[simp] lemma neg_apply (x : β) : (- f) x = - f x := rfl instance : has_add (β →ₗ[α] γ) := ⟨λ f g, ⟨λ b, f b + g b, by simp, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : β) : (f + g) x = f x + g x := rfl instance : add_comm_group (β →ₗ[α] γ) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp instance linear_map.is_add_group_hom : is_add_group_hom f := by refine_struct {..}; simp instance linear_map_apply_is_add_group_hom (a : β) : is_add_group_hom (λ f : β →ₗ[α] γ, f a) := by refine_struct {..}; simp lemma sum_apply [decidable_eq δ] (t : finset δ) (f : δ → β →ₗ[α] γ) (b : β) : t.sum f b = t.sum (λd, f d b) := (@finset.sum_hom _ _ _ t f _ _ (λ g : β →ₗ[α] γ, g b) _).symm @[simp] lemma sub_apply (x : β) : (f - g) x = f x - g x := rfl def smul_right (f : γ →ₗ[α] α) (x : β) : γ →ₗ[α] β := ⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩. @[simp] theorem smul_right_apply (f : γ →ₗ[α] α) (x : β) (c : γ) : (smul_right f x : γ → β) c = f c • x := rfl instance : has_one (β →ₗ[α] β) := ⟨linear_map.id⟩ instance : has_mul (β →ₗ[α] β) := ⟨linear_map.comp⟩ @[simp] lemma one_app (x : β) : (1 : β →ₗ[α] β) x = x := rfl @[simp] lemma mul_app (A B : β →ₗ[α] β) (x : β) : (A * B) x = A (B x) := rfl @[simp] theorem comp_zero : f.comp (0 : δ →ₗ[α] β) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : γ →ₗ[α] δ).comp f = 0 := rfl section variables (α β) include β instance endomorphism_ring : ring (β →ₗ[α] β) := by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..}; { intros, apply linear_map.ext, simp } /-- The group of invertible linear maps from `β` to itself -/ def general_linear_group := units (β →ₗ[α] β) end section variables (α β γ) def fst : β × γ →ₗ[α] β := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩ def snd : β × γ →ₗ[α] γ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩ end @[simp] theorem fst_apply (x : β × γ) : fst α β γ x = x.1 := rfl @[simp] theorem snd_apply (x : β × γ) : snd α β γ x = x.2 := rfl def pair (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) : β →ₗ[α] γ × δ := ⟨λ x, (f x, g x), λ x y, by simp, λ x y, by simp⟩ @[simp] theorem pair_apply (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) (x : β) : pair f g x = (f x, g x) := rfl @[simp] theorem fst_pair (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) : (fst α γ δ).comp (pair f g) = f := by ext; refl @[simp] theorem snd_pair (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) : (snd α γ δ).comp (pair f g) = g := by ext; refl @[simp] theorem pair_fst_snd : pair (fst α β γ) (snd α β γ) = linear_map.id := by ext; refl section variables (α β γ) def inl : β →ₗ[α] β × γ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl] def inr : γ →ₗ[α] β × γ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr] end @[simp] theorem inl_apply (x : β) : inl α β γ x = (x, 0) := rfl @[simp] theorem inr_apply (x : γ) : inr α β γ x = (0, x) := rfl def copair (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) : β × γ →ₗ[α] δ := ⟨λ x, f x.1 + g x.2, λ x y, by simp, λ x y, by simp [smul_add]⟩ @[simp] theorem copair_apply (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) (x : β) (y : γ) : copair f g (x, y) = f x + g y := rfl @[simp] theorem copair_inl (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) : (copair f g).comp (inl α β γ) = f := by ext; simp @[simp] theorem copair_inr (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) : (copair f g).comp (inr α β γ) = g := by ext; simp @[simp] theorem copair_inl_inr : copair (inl α β γ) (inr α β γ) = linear_map.id := by ext ⟨x, y⟩; simp theorem fst_eq_copair : fst α β γ = copair linear_map.id 0 := by ext ⟨x, y⟩; simp theorem snd_eq_copair : snd α β γ = copair 0 linear_map.id := by ext ⟨x, y⟩; simp theorem inl_eq_pair : inl α β γ = pair linear_map.id 0 := rfl theorem inr_eq_pair : inr α β γ = pair 0 linear_map.id := rfl end section comm_ring variables [comm_ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variables (f g : β →ₗ[α] γ) include α instance : has_scalar α (β →ₗ[α] γ) := ⟨λ a f, ⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (a : α) (x : β) : (a • f) x = a • f x := rfl instance : module α (β →ₗ[α] γ) := module.of_core $ by refine { smul := (•), ..}; intros; ext; simp [smul_add, add_smul, smul_smul] def congr_right (f : γ →ₗ[α] δ) : (β →ₗ[α] γ) →ₗ[α] (β →ₗ[α] δ) := ⟨linear_map.comp f, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ theorem smul_comp (g : γ →ₗ[α] δ) (a : α) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul (g : γ →ₗ[α] δ) (a : α) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl end comm_ring end linear_map namespace submodule variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variables (p p' : submodule α β) (q q' : submodule α γ) variables {r : α} {x y : β} open set lattice instance : partial_order (submodule α β) := partial_order.lift (coe : submodule α β → set β) $ λ a b, ext' lemma le_def {p p' : submodule α β} : p ≤ p' ↔ (p : set β) ⊆ p' := iff.rfl lemma le_def' {p p' : submodule α β} : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl def of_le {p p' : submodule α β} (h : p ≤ p') : p →ₗ[α] p' := linear_map.cod_restrict _ p.subtype $ λ ⟨x, hx⟩, h hx @[simp] theorem of_le_apply {p p' : submodule α β} (h : p ≤ p') (x : p) : (of_le h x : β) = x := rfl lemma subtype_comp_of_le (p q : submodule α β) (h : p ≤ q) : (submodule.subtype q).comp (of_le h) = submodule.subtype p := by ext ⟨b, hb⟩; simp instance : has_bot (submodule α β) := ⟨by split; try {exact {0}}; simp {contextual := tt}⟩ @[simp] lemma bot_coe : ((⊥ : submodule α β) : set β) = {0} := rfl section variables (α) @[simp] lemma mem_bot : x ∈ (⊥ : submodule α β) ↔ x = 0 := mem_singleton_iff end instance : order_bot (submodule α β) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..submodule.partial_order } instance : has_top (submodule α β) := ⟨by split; try {exact set.univ}; simp⟩ @[simp] lemma top_coe : ((⊤ : submodule α β) : set β) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule α β) := trivial instance : order_top (submodule α β) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } instance : has_Inf (submodule α β) := ⟨λ S, { carrier := ⋂ s ∈ S, ↑s, zero := by simp, add := by simp [add_mem] {contextual := tt}, smul := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule α β)} {p} : p ∈ S → Inf S ≤ p := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule α β)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule α β) := ⟨λ p p', { carrier := p ∩ p', zero := by simp, add := by simp [add_mem] {contextual := tt}, smul := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule α β) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, subset_inter, inf_le_left := λ a b, inter_subset_left _ _, inf_le_right := λ a b, inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.lattice.order_top, ..submodule.lattice.order_bot } instance : add_comm_monoid (submodule α β) := { 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 (M N : submodule α β) : M + N = M ⊔ N := rfl @[simp] lemma zero_eq_bot : (0 : submodule α β) = ⊥ := rfl lemma eq_top_iff' {p : submodule α β} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ @[simp] theorem inf_coe : (p ⊓ p' : set β) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule α β} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[simp] theorem Inf_coe (P : set (submodule α β)) : (↑(Inf P) : set β) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule α β) : (↑⨅ i, p i : set β) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] theorem mem_infi {ι} (p : ι → submodule α β) : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule α β} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:β) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set β)) ↔ _, by simp /-- The pushforward -/ def map (f : β →ₗ[α] γ) (p : submodule α β) : submodule α γ := { carrier := f '' p, zero := ⟨0, p.zero_mem, f.map_zero⟩, add := by rintro _ _ ⟨b₁, hb₁, rfl⟩ ⟨b₂, hb₂, rfl⟩; exact ⟨_, p.add_mem hb₁ hb₂, f.map_add _ _⟩, smul := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩ } lemma map_coe (f : β →ₗ[α] γ) (p : submodule α β) : (map f p : set γ) = f '' p := rfl @[simp] lemma mem_map {f : β →ₗ[α] γ} {p : submodule α β} {x : γ} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : β →ₗ[α] γ} {p : submodule α β} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) (p : submodule α β) : map (g.comp f) p = map g (map f p) := submodule.ext' $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : β →ₗ[α] γ} {p p' : submodule α β} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : β →ₗ[α] γ) p = ⊥ := have ∃ (x : β), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] /-- The pullback -/ def comap (f : β →ₗ[α] γ) (p : submodule α γ) : submodule α β := { carrier := f ⁻¹' p, zero := by simp, add := λ x y h₁ h₂, by simp [p.add_mem h₁ h₂], smul := λ a x h, by simp [p.smul_mem _ h] } @[simp] lemma comap_coe (f : β →ₗ[α] γ) (p : submodule α γ) : (comap f p : set β) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : β →ₗ[α] γ} {p : submodule α γ} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.ext' rfl lemma comap_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) (p : submodule α δ) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : β →ₗ[α] γ} {q q' : submodule α γ} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : β →ₗ[α] γ} {p : submodule α β} {q : submodule α γ} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : β →ₗ[α] γ) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : β →ₗ[α] γ) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : β →ₗ[α] γ) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : β →ₗ[α] γ) (p : ι → submodule α β) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : β →ₗ[α] γ) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : β →ₗ[α] γ) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : β →ₗ[α] γ) (p : ι → submodule α γ) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : β →ₗ[α] γ) q = ⊤ := ext $ by simp lemma map_comap_le (f : β →ₗ[α] γ) (q : submodule α γ) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : β →ₗ[α] γ) (p : submodule α β) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : β →ₗ[α] γ} {p : submodule α β} {p' : submodule α γ} : 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 α β)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot α).1 hb section variables (α) def span (s : set β) : submodule α β := Inf {p | s ⊆ p} end variables {s t : set β} lemma mem_span : x ∈ span α s ↔ ∀ p : submodule α β, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span α s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span α s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span α s ≤ span α t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span α s) : span α s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span α (p : set β) = p := span_eq_of_le _ (subset.refl _) subset_span @[elab_as_eliminator] lemma span_induction {p : β → Prop} (h : x ∈ span α s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:α) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (α β) protected def gi : galois_insertion (@span α β _ _ _) coe := { choice := λ s _, span α s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span α (∅ : set β) = ⊥ := (submodule.gi α β).gc.l_bot @[simp] lemma span_univ : span α (univ : set β) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set β) : span α (s ∪ t) = span α s ⊔ span α t := (submodule.gi α β).gc.l_sup lemma span_Union {ι} (s : ι → set β) : span α (⋃ i, s i) = ⨆ i, span α (s i) := (submodule.gi α β).gc.l_supr @[simp] theorem Union_coe_of_directed {ι} (hι : nonempty ι) (S : ι → submodule α β) (H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) : ((supr S : submodule α β) : set β) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), rw [show supr S = ⨆ i, span α (S i), by simp, ← span_Union], unfreezeI, refine λ x hx, span_induction hx (λ _, id) _ _ _, { cases hι with i, exact mem_Union.2 ⟨i, by simp⟩ }, { simp, intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { simp [-mem_coe]; exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma mem_supr_of_mem {ι : Sort*} {b : β} (p : ι → submodule α β) (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h @[simp] theorem mem_supr_of_directed {ι} (hι : nonempty ι) (S : ι → submodule α β) (H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by rw [← mem_coe, Union_coe_of_directed hι S H, mem_Union]; refl theorem mem_Sup_of_directed {s : set (submodule α β)} {z} (hzs : z ∈ Sup s) (x ∈ s) (hdir : ∀ i ∈ s, ∀ j ∈ s, ∃ k ∈ s, i ≤ k ∧ j ≤ k) : ∃ y ∈ s, z ∈ y := begin haveI := classical.dec, rw Sup_eq_supr at hzs, have : ∃ (i : submodule α β), z ∈ ⨆ (H : i ∈ s), i, { refine (mem_supr_of_directed ⟨⊥⟩ _ (λ i j, _)).1 hzs, by_cases his : i ∈ s; by_cases hjs : j ∈ s, { rcases hdir i his j hjs with ⟨k, hks, hik, hjk⟩, exact ⟨k, le_supr_of_le hks (supr_le $ λ _, hik), le_supr_of_le hks (supr_le $ λ _, hjk)⟩ }, { exact ⟨i, le_refl _, supr_le $ hjs.elim⟩ }, { exact ⟨j, supr_le $ his.elim, le_refl _⟩ }, { exact ⟨⊥, supr_le $ his.elim, supr_le $ hjs.elim⟩ } }, cases this with N hzn, by_cases hns : N ∈ s, { have : (⨆ (H : N ∈ s), N) ≤ N := supr_le (λ _, le_refl _), exact ⟨N, hns, this hzn⟩ }, { have : (⨆ (H : N ∈ s), N) ≤ ⊥ := supr_le hns.elim, cases (mem_bot α).1 (this hzn), exact ⟨x, H, x.zero_mem⟩ } end 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⟩ }, { 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)⟩ end lemma mem_span_singleton {y : β} : x ∈ span α ({y} : set β) ↔ ∃ a:α, 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 span_singleton_eq_range (y : β) : (span α ({y} : set β) : set β) = range ((• y) : α → β) := set.ext $ λ x, mem_span_singleton lemma mem_span_insert {y} : x ∈ span α (insert y s) ↔ ∃ (a:α) (z ∈ span α s), x = a • y + z := begin rw [← union_singleton, span_union, mem_sup], simp [mem_span_singleton], split, { rintro ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩, exact ⟨a, z, hz, rfl⟩ }, { rintro ⟨a, z, hz, rfl⟩, exact ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩ } end lemma mem_span_insert' {y} : x ∈ span α (insert y s) ↔ ∃(a:α), x + a • y ∈ span α s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp⟩ } end lemma span_insert_eq_span (h : x ∈ span α s) : span α (insert x s) = span α s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span α (span α s : set β) = span α s := span_eq _ lemma span_eq_bot : span α (s : set β) = ⊥ ↔ ∀ x ∈ s, (x:β) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot α).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot α).2 $ H x h)⟩ lemma span_singleton_eq_bot : span α ({x} : set β) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_image (f : β →ₗ[α] γ) : span α (f '' s) = map f (span α s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span def prod : submodule α (β × γ) := { carrier := set.prod p q, zero := ⟨zero_mem _, zero_mem _⟩, add := by rintro ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ ⟨hx₁, hy₁⟩ ⟨hx₂, hy₂⟩; exact ⟨add_mem _ hx₁ hx₂, add_mem _ hy₁ hy₂⟩, smul := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩ } @[simp] lemma prod_coe : (prod p q : set (β × γ)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule α β} {q : submodule α γ} {x : β × γ} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set β) (t : set γ) : span α (set.prod s t) ≤ prod (span α s) (span α t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule α (β × γ)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule α (β × γ)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule α β} {q q' : submodule α γ} : 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') := ext' 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 [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 -- TODO(Mario): Factor through add_subgroup def quotient_rel : setoid β := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa using add_mem _ h₁ h₂⟩ def quotient : Type* := quotient (quotient_rel p) namespace quotient def mk {p : submodule α β} : β → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule α β} (x : β) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule α β} (x : β) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule α β} (x : β) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : β} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 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 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 : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm] instance : has_scalar α (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_add] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : module α (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] instance {α β} {R:discrete_field α} [add_comm_group β] [vector_space α β] (p : submodule α β) : vector_space α (quotient p) := {} end quotient end submodule namespace submodule variables [discrete_field α] variables [add_comm_group β] [vector_space α β] variables [add_comm_group γ] [vector_space α γ] lemma comap_smul (f : β →ₗ[α] γ) (p : submodule α γ) (a : α) (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 : β →ₗ[α] γ) (p : submodule α β) (a : α) (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 set_option class.instance_max_depth 40 lemma comap_smul' (f : β →ₗ[α] γ) (p : submodule α γ) (a : α) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : β →ₗ[α] γ) (p : submodule α β) (a : α) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by by_cases a = 0; simp [h, map_smul] end submodule namespace linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] include α open submodule @[simp] lemma finsupp_sum {α β γ δ} [ring α] [add_comm_group β] [module α β] [add_comm_group γ] [module α γ] [has_zero δ] (f : β →ₗ[α] γ) {t : ι →₀ δ} {g : ι → δ → β} : f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum theorem map_cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext] theorem comap_cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (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⟩ def range (f : β →ₗ[α] γ) : submodule α γ := map f ⊤ theorem range_coe (f : β →ₗ[α] γ) : (range f : set γ) = set.range f := set.image_univ @[simp] theorem mem_range {f : β →ₗ[α] γ} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := (set.ext_iff _ _).1 (range_coe f). @[simp] theorem range_id : range (linear_map.id : β →ₗ[α] β) = ⊤ := map_id _ theorem range_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : β →ₗ[α] γ} : range f = ⊤ ↔ surjective f := by rw [← submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : β →ₗ[α] γ} {p : submodule α γ} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] def ker (f : β →ₗ[α] γ) : submodule α β := comap f ⊥ @[simp] theorem mem_ker {f : β →ₗ[α] γ} {y} : y ∈ ker f ↔ f y = 0 := mem_bot α @[simp] theorem ker_id : ker (linear_map.id : β →ₗ[α] β) = ⊥ := rfl theorem ker_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem sub_mem_ker_iff {f : β →ₗ[α] γ} {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker {f : β →ₗ[α] γ} {p : submodule α β} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem disjoint_ker' {f : β →ₗ[α] γ} {p : submodule α β} : 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 {f : β →ₗ[α] γ} {p : submodule α β} {s : set β} (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 {f : β →ₗ[α] γ} : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ lemma le_ker_iff_map {f : β →ₗ[α] γ} {p : submodule α β} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma map_comap_eq (f : β →ₗ[α] γ) (q : submodule α γ) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : β →ₗ[α] γ} {q : submodule α γ} (h : q ≤ range f) : map f (comap f q) = q := by rw [map_comap_eq, inf_of_le_right h] lemma comap_map_eq (f : β →ₗ[α] γ) (p : submodule α β) : 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 : β →ₗ[α] γ} {p : submodule α β} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] @[simp] theorem ker_zero : ker (0 : β →ₗ[α] γ) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : β →ₗ[α] γ) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : β →ₗ[α] γ} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : β →ₗ[α] γ) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem map_le_map_iff {f : β →ₗ[α] γ} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := ⟨λ H x hx, let ⟨y, hy, e⟩ := H ⟨x, hx, rfl⟩ in ker_eq_bot.1 hf e ▸ hy, map_mono⟩ theorem map_injective {f : β →ₗ[α] γ} (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 comap_le_comap_iff {f : β →ₗ[α] γ} (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 : β →ₗ[α] γ} (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 map_copair_prod (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) (p : submodule α β) (q : submodule α γ) : map (copair f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_pair_prod (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) (p : submodule α γ) (q : submodule α δ) : comap (pair f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule α β) (q : submodule α γ) : p.prod q = p.comap (linear_map.fst α β γ) ⊓ q.comap (linear_map.snd α β γ) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule α β) (q : submodule α γ) : p.prod q = p.map (linear_map.inl α β γ) ⊔ q.map (linear_map.inr α β γ) := by rw [← map_copair_prod, copair_inl_inr, map_id] lemma span_inl_union_inr {s : set β} {t : set γ} : span α (prod.inl '' s ∪ prod.inr '' t) = (span α s).prod (span α t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl lemma ker_pair (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) : ker (pair f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_pair_prod]; refl end linear_map namespace linear_map variables [discrete_field α] variables [add_comm_group β] [vector_space α β] variables [add_comm_group γ] [vector_space α γ] lemma ker_smul (f : β →ₗ[α] γ) (a : α) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : β →ₗ[α] γ) (a : α) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : β →ₗ[α] γ) (a : α) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : β →ₗ[α] γ) (a : α) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a end linear_map namespace is_linear_map lemma is_linear_map_add {α β : Type*} [ring α] [add_comm_group β] [module α β]: is_linear_map α (λ (x : β × β), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {α β : Type*} [ring α] [add_comm_group β] [module α β]: is_linear_map α (λ (x : β × β), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp }, { intros x y, simp [smul_add] } end end is_linear_map namespace submodule variables {R:ring α} [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] variables (p p' : submodule α β) (q : submodule α γ) include R open linear_map @[simp] theorem map_top (f : β →ₗ[α] γ) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : β →ₗ[α] γ) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot.2 $ λ x y, subtype.eq' @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule α p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) @[simp] theorem ker_of_le (p p' : submodule α β) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule α β) (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] lemma disjoint_iff_comap_eq_bot (p q : submodule α β) : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff p.ker_subtype, map_bot, map_comap_subtype]; refl /-- If N ⊆ M then submodules of N are the same as submodules of M contained in N -/ def map_subtype.order_iso : ((≤) : submodule α p → submodule α p → Prop) ≃o ((≤) : {p' : submodule α β // p' ≤ p} → {p' : submodule α β // p' ≤ p} → Prop) := { 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.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq], ord := λ p₁ p₂, (map_le_map_iff $ ker_subtype _).symm } def map_subtype.le_order_embedding : ((≤) : submodule α p → submodule α p → Prop) ≼o ((≤) : submodule α β → submodule α β → Prop) := (order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule α p) : map_subtype.le_order_embedding p p' = map p.subtype p' := rfl def map_subtype.lt_order_embedding : ((<) : submodule α p → submodule α p → Prop) ≼o ((<) : submodule α β → submodule α β → Prop) := (map_subtype.le_order_embedding p).lt_embedding_of_le_embedding @[simp] theorem map_inl : p.map (inl α β γ) = prod p ⊥ := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem map_inr : q.map (inr α β γ) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst α β γ) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd α β γ) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl α β γ) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr α β γ) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst α β γ) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd α β γ) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl α β γ).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr α β γ).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst α β γ).range = ⊤ := by rw [range, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd α β γ).range = ⊤ := by rw [range, ← prod_top, prod_map_snd] def mkq : β →ₗ[α] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : β) : p.mkq x = quotient.mk x := rfl def liftq (f : β →ₗ[α] γ) (h : p ≤ f.ker) : p.quotient →ₗ[α] γ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : β →ₗ[α] γ) {h} (x : β) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : β →ₗ[α] γ) (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, trivial, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule α 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] def mapq (f : β →ₗ[α] γ) (h : p ≤ comap f q) : p.quotient →ₗ[α] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : β →ₗ[α] γ) {h} (x : β) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : β →ₗ[α] γ) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : β →ₗ[α] γ) (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 : β →ₗ[α] γ) (h) (q : submodule α (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 : β →ₗ[α] γ) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : β →ₗ[α] γ) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : β →ₗ[α] γ) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- Correspondence Theorem -/ def comap_mkq.order_iso : ((≤) : submodule α p.quotient → submodule α p.quotient → Prop) ≃o ((≤) : {p' : submodule α β // p ≤ p'} → {p' : submodule α β // p ≤ p'} → Prop) := { 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.eq' $ by simp [comap_map_mkq p, sup_of_le_right hq], ord := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm } def comap_mkq.le_order_embedding : ((≤) : submodule α p.quotient → submodule α p.quotient → Prop) ≼o ((≤) : submodule α β → submodule α β → Prop) := (order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule α p.quotient) : comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl def comap_mkq.lt_order_embedding : ((<) : submodule α p.quotient → submodule α p.quotient → Prop) ≼o ((<) : submodule α β → submodule α β → Prop) := (comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding end submodule section set_option old_structure_cmd true structure linear_equiv (α : Type u) (β : Type v) (γ : Type w) [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] extends β →ₗ[α] γ, β ≃ γ end infix ` ≃ₗ ` := linear_equiv _ notation β ` ≃ₗ[`:50 α `] ` γ := linear_equiv α β γ namespace linear_equiv section ring variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] include α section variable (β) def refl : β ≃ₗ[α] β := { .. linear_map.id, .. equiv.refl β } end def symm (e : β ≃ₗ[α] γ) : γ ≃ₗ[α] β := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } def trans (e₁ : β ≃ₗ[α] γ) (e₂ : γ ≃ₗ[α] δ) : β ≃ₗ[α] δ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } instance : has_coe (β ≃ₗ[α] γ) (β →ₗ[α] γ) := ⟨to_linear_map⟩ @[simp] theorem apply_symm_apply (e : β ≃ₗ[α] γ) (c : γ) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (e : β ≃ₗ[α] γ) (b : β) : e.symm (e b) = b := e.5 b @[simp] theorem coe_apply (e : β ≃ₗ[α] γ) (b : β) : (e : β →ₗ[α] γ) b = e b := rfl noncomputable def of_bijective (f : β →ₗ[α] γ) (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : β ≃ₗ[α] γ := { ..f, ..@equiv.of_bijective _ _ f ⟨linear_map.ker_eq_bot.1 hf₁, linear_map.range_eq_top.1 hf₂⟩ } @[simp] theorem of_bijective_apply (f : β →ₗ[α] γ) {hf₁ hf₂} (x : β) : of_bijective f hf₁ hf₂ x = f x := rfl def of_linear (f : β →ₗ[α] γ) (g : γ →ₗ[α] β) (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : β ≃ₗ[α] γ := { 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 (f : β →ₗ[α] γ) (g : γ →ₗ[α] β) {h₁ h₂} (x : β) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply (f : β →ₗ[α] γ) (g : γ →ₗ[α] β) {h₁ h₂} (x : γ) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem ker (f : β ≃ₗ[α] γ) : (f : β →ₗ[α] γ).ker = ⊥ := linear_map.ker_eq_bot.2 f.to_equiv.injective @[simp] protected theorem range (f : β ≃ₗ[α] γ) : (f : β →ₗ[α] γ).range = ⊤ := linear_map.range_eq_top.2 f.to_equiv.surjective def of_top (p : submodule α β) (h : p = ⊤) : p ≃ₗ[α] β := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply (p : submodule α β) {h} (x : p) : of_top p h x = x := rfl @[simp] theorem of_top_symm_apply (p : submodule α β) {h} (x : β) : ↑((of_top p h).symm x) = x := rfl lemma eq_bot_of_equiv (p : submodule α β) (e : p ≃ₗ[α] (⊥ : submodule α γ)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot α).2 _), have := e.symm_apply_apply ⟨b, hb⟩, rw [← e.coe_apply, submodule.eq_zero_of_bot_submodule ((e : p →ₗ[α] (⊥ : submodule α γ)) ⟨b, hb⟩), ← e.symm.coe_apply, linear_map.map_zero] at this, exact congr_arg (coe : p → β) this.symm end end ring section comm_ring variables [comm_ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] include α open linear_map set_option class.instance_max_depth 39 def smul_of_unit (a : units α) : β ≃ₗ[α] β := of_linear ((a:α) • 1 : β →ₗ β) (((a⁻¹ : units α) : α) • 1 : β →ₗ β) (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) def congr_right (f : γ ≃ₗ[α] δ) : (β →ₗ[α] γ) ≃ₗ (β →ₗ δ) := of_linear f.to_linear_map.congr_right f.symm.to_linear_map.congr_right (linear_map.ext $ λ _, linear_map.ext $ λ _, f.6 _) (linear_map.ext $ λ _, linear_map.ext $ λ _, f.5 _) end comm_ring section field variables [field α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variable (β) open linear_map def smul_of_ne_zero (a : α) (ha : a ≠ 0) : β ≃ₗ[α] β := smul_of_unit $ units.mk0 a ha end field end linear_equiv namespace equiv variables [ring α] [add_comm_group β] [module α β] [add_comm_group γ] [module α γ] def to_linear_equiv (e : β ≃ γ) (h : is_linear_map α (e : β → γ)) : β ≃ₗ[α] γ := { add := h.add, smul := h.smul, .. e} end equiv namespace linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variables (f : β →ₗ[α] γ) /-- First Isomorphism Law -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[α] f.range := have hr : ∀ x : f.range, ∃ y, f y = ↑x := λ x, x.2.imp $ λ _, and.right, let F : f.ker.quotient →ₗ[α] f.range := f.ker.liftq (cod_restrict f.range f $ λ x, ⟨x, trivial, rfl⟩) (λ x hx, by simp; apply subtype.coe_ext.2; simpa using hx) in { inv_fun := λx, submodule.quotient.mk (classical.some (hr x)), left_inv := by rintro ⟨x⟩; exact (submodule.quotient.eq _).2 (sub_mem_ker_iff.2 $ classical.some_spec $ hr $ F $ submodule.quotient.mk x), right_inv := λ x : range f, subtype.eq $ classical.some_spec (hr x), .. F } open submodule def sup_quotient_to_quotient_inf (p p' : submodule α β) : (comap p.subtype (p ⊓ p')).quotient →ₗ[α] (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 le_sup_left (le_refl _)) end set_option class.instance_max_depth 41 /-- Second Isomorphism Law -/ noncomputable def sup_quotient_equiv_quotient_inf (p p' : submodule α β) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[α] (comap (p ⊔ p').subtype p').quotient := { .. sup_quotient_to_quotient_inf p p', .. show (comap p.subtype (p ⊓ p')).quotient ≃ (comap (p ⊔ p').subtype p').quotient, from @equiv.of_bijective _ _ (sup_quotient_to_quotient_inf p p') begin constructor, { rw [← ker_eq_bot, sup_quotient_to_quotient_inf, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], rintros ⟨x, hx1⟩ hx2, exact ⟨hx1, hx2⟩ }, rw [← range_eq_top, sup_quotient_to_quotient_inf, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end } section pi universe i variables {φ : ι → Type i} variables [∀i, add_comm_group (φ i)] [∀i, module α (φ i)] /-- `pi` construction for linear functions. From a family of linear functions it produces a linear function into a family of modules. -/ def pi (f : Πi, γ →ₗ[α] φ i) : γ →ₗ[α] (Πi, φ i) := ⟨λc i, f i c, assume c d, funext $ assume i, (f i).add _ _, assume c d, funext $ assume i, (f i).smul _ _⟩ @[simp] lemma pi_apply (f : Πi, γ →ₗ[α] φ i) (c : γ) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, γ →ₗ[α] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, γ →ₗ[α] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, γ →ₗ[α] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, γ →ₗ[α] φ i) (g : δ →ₗ[α] γ) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- Linear projection -/ def proj (i : ι) : (Πi, φ i) →ₗ[α] φ i := ⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[α] φ i) b = b i := rfl lemma proj_pi (f : Πi, γ →ₗ[α] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule α (Πi, φ i)) = ⊥ := bot_unique $ submodule.le_def'.2 $ assume a h, begin simp only [mem_infi, mem_ker, proj_apply] at h, exact (mem_bot _).2 (funext $ assume i, h i) end section variables (α φ) def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule α (Πi, φ i)) ≃ₗ[α] (Πi:I, φ i) := begin refine linear_equiv.of_linear (pi $ λi, (proj (i:ι)).comp (submodule.subtype _)) (cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _, { assume b, simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply], assume j hjJ, have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩, rw [dif_neg this, zero_apply] }, { simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.val_prop'], ext b ⟨j, hj⟩, refl }, { ext ⟨b, hb⟩, apply subtype.coe_ext.2, ext j, have hb : ∀i ∈ J, b i = 0, { simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb }, simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply], split_ifs, { rw [dif_pos h], refl }, { rw [dif_neg h], exact (hb _ $ (hu trivial).resolve_left h).symm } } end end section variable [decidable_eq ι] /-- `diag i j` is the identity map if `i = j` otherwise it is the constant 0 map. -/ def diag (i j : ι) : φ i →ₗ[α] φ j := @function.update ι (λj, φ i →ₗ[α] φ j) _ 0 i id j lemma update_apply (f : Πi, γ →ₗ[α] φ i) (c : γ) (i j : ι) (b : γ →ₗ[α] φ i) : (update f i b j) c = update (λi, f i c) i (b c) j := begin by_cases j = i, { rw [h, update_same, update_same] }, { rw [update_noteq h, update_noteq h] } end end section variable [decidable_eq ι] variables (α φ) /-- Standard basis -/ def std_basis (i : ι) : φ i →ₗ[α] (Πi, φ i) := pi (diag i) lemma std_basis_apply (i : ι) (b : φ i) : std_basis α φ i b = update 0 i b := by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis α φ i b i = b := by rw [std_basis_apply, update_same] lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis α φ i b j = 0 := by rw [std_basis_apply, update_noteq h]; refl lemma ker_std_basis (i : ι) : ker (std_basis α φ i) = ⊥ := ker_eq_bot.2 $ assume f g hfg, have std_basis α φ i f i = std_basis α φ i g i := hfg ▸ rfl, by simpa only [std_basis_same] lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis α φ j) = diag j i := by rw [std_basis, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis α φ i) = id := by ext b; simp lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis α φ j) = 0 := by ext b; simp [std_basis_ne α φ _ _ h] lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis α φ i)) ≤ (⨅i∈J, ker (proj i)) := begin refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb j hj, have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩, rw [proj_std_basis_ne α φ j i this.symm, zero_apply] end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis α φ i)) := submodule.le_def'.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show I.sum (λi, std_basis α φ i (b i)) = b, { ext i, rw [pi.finset_sum_apply, ← std_basis_same α φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $ linear_map.mem_range.2 ⟨_, rfl⟩) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis α φ i)) = (⨅i∈J, ker (proj i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [finset.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis α φ this) (supr_le_supr $ assume i, _), rw [← finset.mem_coe, finset.coe_to_finset], exact le_refl _ end lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis α φ i)) = ⊤ := have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty], begin apply top_unique, convert (infi_ker_proj_le_supr_range_std_basis α φ this), exact infi_emptyset.symm, exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis α φ i)) $ finset.mem_univ i).symm) end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis α φ i)) (⨆i∈J, range (std_basis α φ i)) := begin refine disjoint_mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _, simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end end end pi end linear_map
7ec73f8d42701b1a2b34ba40e2e480f307925d13
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/power_series/basic.lean
dc01dd91072314507bc0c6d0e93e19b90698c53f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
64,455
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.mv_polynomial import linear_algebra.std_basis import ring_theory.ideal.operations import ring_theory.multiplicity import ring_theory.algebra_tower import tactic.linarith import algebra.big_operators.nat_antidiagonal /-! # Formal power series 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 /-- 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_scalar 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 : 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, nat_add_sub_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, nat_add_sub_cancel], exact le_add_left le_rfl 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.has_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₂, nat_sub_add_cancel h₁] at h₃, exact (h₃ rfl).elim }, { rw [h₃, nat_add_sub_cancel] 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], split_ifs; refl } @[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 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 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_monomial_mul, if_neg this] end 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' (constant_coeff σ R) @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := rfl 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, ← finset.sum_hom _ f, 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 [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 Iic_finset 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 : 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 _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (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, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_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 [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_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, nat_add_sub_cancel_left, add_comm], }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.sub_add_cancel 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 comm_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 : units R) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : units 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 : units 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 : units 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_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, 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_refl _), 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 is_local_ring [local_ring R] : local_ring (mv_power_series σ R) := { is_local := by { intro φ, rcases local_ring.is_local (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⟩ variables [local_ring R] [local_ring S] instance : local_ring (mv_power_series σ R) := { is_local := local_ring.is_local } 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, 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 (φ : 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 (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv 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 _ h], λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv _ 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] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring 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 φ⟩ @[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ R) (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_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ R) : ((φ * ψ : 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_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ -- TODO as an algebra 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 } end mv_polynomial /-- 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_scalar 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], split_ifs; refl } 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 () @[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] 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 (n : ℕ) (φ : power_series R) (a : R) : coeff R n (a • φ) = a * coeff R n φ := rfl @[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 /-- 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 end map end semiring section comm_semiring variables [comm_semiring R] 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 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], } section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : polynomial R := ∑ m in Ico 0 (n + 1), 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 : 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 _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : R) : trunc n (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 : units R) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : units 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 : units 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 : units 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_neg_one_X : rescale (-1 : A) X = -X := begin ext, simp only [linear_map.map_neg, coeff_rescale, coeff_X], split_ifs with h; simp [h] end /-- 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 integral_domain variable [integral_domain R] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : 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, have : i = m := le_antisymm hne hi, subst i, clear 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 : integral_domain (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nontrivial, .. power_series.comm_ring } /-- 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 integral_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, 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 (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ 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 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 [comm_semiring R] /-- The order of a formal power series `φ` is the greatest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series R) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series R) (h : ∃ n, coeff R n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, dsimp only, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series R) (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} 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 (φ : power_series R) (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this 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 (φ : power_series R) (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := multiplicity.zero _ /-- 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 := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, 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 : enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply nat_le_order, simpa only [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 simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, 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 {φ : power_series R} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [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 (φ + ψ) := multiplicity.min_le_multiplicity_add 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_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ 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 [← enat.coe_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 [enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] }, { rw [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 end order_basic section order_zero_ne_one variables [comm_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 := 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_integral_domain variables [integral_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 ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial R) (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, norm_cast] lemma coeff_coe (φ : polynomial R) (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 : polynomial R) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : polynomial R) : 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 (φ ψ : polynomial R) : ((φ + ψ : polynomial R) : power_series R) = φ + ψ := by { ext, simp } @[simp, norm_cast] lemma coe_mul (φ ψ : polynomial R) : ((φ * ψ : polynomial R) : 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 : polynomial R) : 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_X : ((X : polynomial R) : power_series R) = power_series.X := coe_monomial _ _ /-- The coercion from polynomials to power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_power_series.ring_hom : polynomial R →+* power_series R := { to_fun := (coe : polynomial R → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end polynomial
b5f28da7a2e305e73a7cc618403451df814a4cbc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/sub/defs.lean
e65e0290ed91913fbe2f97c7ef4dbec5c3b15dbe
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
13,280
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.covariant_and_contravariant import algebra.group.basic import algebra.order.monoid.lemmas import order.lattice /-! # Ordered Subtraction > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves lemmas relating (truncated) subtraction with an order. We provide a class `has_ordered_sub` stating that `a - b ≤ c ↔ a ≤ c + b`. The subtraction discussed here could both be normal subtraction in an additive group or truncated subtraction on a canonically ordered monoid (`ℕ`, `multiset`, `part_enat`, `ennreal`, ...) ## Implementation details `has_ordered_sub` is a mixin type-class, so that we can use the results in this file even in cases where we don't have a `canonically_ordered_add_monoid` instance (even though that is our main focus). Conversely, this means we can use `canonically_ordered_add_monoid` without necessarily having to define a subtraction. The results in this file are ordered by the type-class assumption needed to prove it. This means that similar results might not be close to each other. Furthermore, we don't prove implications if a bi-implication can be proven under the same assumptions. Lemmas using this class are named using `tsub` instead of `sub` (short for "truncated subtraction"). This is to avoid naming conflicts with similar lemmas about ordered groups. We provide a second version of most results that require `[contravariant_class α α (+) (≤)]`. In the second version we replace this type-class assumption by explicit `add_le_cancellable` assumptions. TODO: maybe we should make a multiplicative version of this, so that we can replace some identical lemmas about subtraction/division in `ordered_[add_]comm_group` with these. TODO: generalize `nat.le_of_le_of_sub_le_sub_right`, `nat.sub_le_sub_right_iff`, `nat.mul_self_sub_mul_self_eq` -/ variables {α β : Type*} /-- `has_ordered_sub α` means that `α` has a subtraction characterized by `a - b ≤ c ↔ a ≤ c + b`. In other words, `a - b` is the least `c` such that `a ≤ b + c`. This is satisfied both by the subtraction in additive ordered groups and by truncated subtraction in canonically ordered monoids on many specific types. -/ class has_ordered_sub (α : Type*) [has_le α] [has_add α] [has_sub α] : Prop := (tsub_le_iff_right : ∀ a b c : α, a - b ≤ c ↔ a ≤ c + b) section has_add variables [preorder α] [has_add α] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma tsub_le_iff_right : a - b ≤ c ↔ a ≤ c + b := has_ordered_sub.tsub_le_iff_right a b c /-- See `add_tsub_cancel_right` for the equality if `contravariant_class α α (+) (≤)`. -/ lemma add_tsub_le_right : a + b - b ≤ a := tsub_le_iff_right.mpr le_rfl lemma le_tsub_add : b ≤ (b - a) + a := tsub_le_iff_right.mp le_rfl end has_add /-! ### Preorder -/ section ordered_add_comm_semigroup section preorder variables [preorder α] section add_comm_semigroup variables [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_le_iff_left : a - b ≤ c ↔ a ≤ b + c := by rw [tsub_le_iff_right, add_comm] lemma le_add_tsub : a ≤ b + (a - b) := tsub_le_iff_left.mp le_rfl /-- See `add_tsub_cancel_left` for the equality if `contravariant_class α α (+) (≤)`. -/ lemma add_tsub_le_left : a + b - a ≤ b := tsub_le_iff_left.mpr le_rfl lemma tsub_le_tsub_right (h : a ≤ b) (c : α) : a - c ≤ b - c := tsub_le_iff_left.mpr $ h.trans le_add_tsub lemma tsub_le_iff_tsub_le : a - b ≤ c ↔ a - c ≤ b := by rw [tsub_le_iff_left, tsub_le_iff_right] /-- See `tsub_tsub_cancel_of_le` for the equality. -/ lemma tsub_tsub_le : b - (b - a) ≤ a := tsub_le_iff_right.mpr le_add_tsub section cov variable [covariant_class α α (+) (≤)] lemma tsub_le_tsub_left (h : a ≤ b) (c : α) : c - b ≤ c - a := tsub_le_iff_left.mpr $ le_add_tsub.trans $ add_le_add_right h _ lemma tsub_le_tsub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := (tsub_le_tsub_right hab _).trans $ tsub_le_tsub_left hcd _ lemma antitone_const_tsub : antitone (λ x, c - x) := λ x y hxy, tsub_le_tsub rfl.le hxy /-- See `add_tsub_assoc_of_le` for the equality. -/ lemma add_tsub_le_assoc : a + b - c ≤ a + (b - c) := by { rw [tsub_le_iff_left, add_left_comm], exact add_le_add_left le_add_tsub a } /-- See `tsub_add_eq_add_tsub` for the equality. -/ lemma add_tsub_le_tsub_add : a + b - c ≤ a - c + b := by { rw [add_comm, add_comm _ b], exact add_tsub_le_assoc } lemma add_le_add_add_tsub : a + b ≤ (a + c) + (b - c) := by { rw [add_assoc], exact add_le_add_left le_add_tsub a } lemma le_tsub_add_add : a + b ≤ (a - c) + (b + c) := by { rw [add_comm a, add_comm (a - c)], exact add_le_add_add_tsub } lemma tsub_le_tsub_add_tsub : a - c ≤ (a - b) + (b - c) := begin rw [tsub_le_iff_left, ← add_assoc, add_right_comm], exact le_add_tsub.trans (add_le_add_right le_add_tsub _), end lemma tsub_tsub_tsub_le_tsub : (c - a) - (c - b) ≤ b - a := begin rw [tsub_le_iff_left, tsub_le_iff_left, add_left_comm], exact le_tsub_add.trans (add_le_add_left le_add_tsub _), end lemma tsub_tsub_le_tsub_add {a b c : α} : a - (b - c) ≤ a - b + c := tsub_le_iff_right.2 $ calc a ≤ a - b + b : le_tsub_add ... ≤ a - b + (c + (b - c)) : add_le_add_left le_add_tsub _ ... = a - b + c + (b - c) : (add_assoc _ _ _).symm /-- See `tsub_add_tsub_comm` for the equality. -/ lemma add_tsub_add_le_tsub_add_tsub : a + b - (c + d) ≤ a - c + (b - d) := begin rw [add_comm c, tsub_le_iff_left, add_assoc, ←tsub_le_iff_left, ←tsub_le_iff_left], refine (tsub_le_tsub_right add_tsub_le_assoc c).trans _, rw [add_comm a, add_comm (a - c)], exact add_tsub_le_assoc, end /-- See `add_tsub_add_eq_tsub_left` for the equality. -/ lemma add_tsub_add_le_tsub_left : a + b - (a + c) ≤ b - c := by { rw [tsub_le_iff_left, add_assoc], exact add_le_add_left le_add_tsub _ } /-- See `add_tsub_add_eq_tsub_right` for the equality. -/ lemma add_tsub_add_le_tsub_right : a + c - (b + c) ≤ a - b := by { rw [tsub_le_iff_left, add_right_comm], exact add_le_add_right le_add_tsub c } end cov /-! #### Lemmas that assume that an element is `add_le_cancellable` -/ namespace add_le_cancellable protected lemma le_add_tsub_swap (hb : add_le_cancellable b) : a ≤ b + a - b := hb le_add_tsub protected lemma le_add_tsub (hb : add_le_cancellable b) : a ≤ a + b - b := by { rw add_comm, exact hb.le_add_tsub_swap } protected lemma le_tsub_of_add_le_left (ha : add_le_cancellable a) (h : a + b ≤ c) : b ≤ c - a := ha $ h.trans le_add_tsub protected lemma le_tsub_of_add_le_right (hb : add_le_cancellable b) (h : a + b ≤ c) : a ≤ c - b := hb.le_tsub_of_add_le_left $ by rwa add_comm end add_le_cancellable /-! ### Lemmas where addition is order-reflecting -/ section contra variable [contravariant_class α α (+) (≤)] lemma le_add_tsub_swap : a ≤ b + a - b := contravariant.add_le_cancellable.le_add_tsub_swap lemma le_add_tsub' : a ≤ a + b - b := contravariant.add_le_cancellable.le_add_tsub lemma le_tsub_of_add_le_left (h : a + b ≤ c) : b ≤ c - a := contravariant.add_le_cancellable.le_tsub_of_add_le_left h lemma le_tsub_of_add_le_right (h : a + b ≤ c) : a ≤ c - b := contravariant.add_le_cancellable.le_tsub_of_add_le_right h end contra end add_comm_semigroup variables [add_comm_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_nonpos : a - b ≤ 0 ↔ a ≤ b := by rw [tsub_le_iff_left, add_zero] alias tsub_nonpos ↔ _ tsub_nonpos_of_le end preorder /-! ### Partial order -/ variables [partial_order α] [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_tsub (b a c : α) : b - a - c = b - (a + c) := begin apply le_antisymm, { rw [tsub_le_iff_left, tsub_le_iff_left, ← add_assoc, ← tsub_le_iff_left] }, { rw [tsub_le_iff_left, add_assoc, ← tsub_le_iff_left, ← tsub_le_iff_left] } end lemma tsub_add_eq_tsub_tsub (a b c : α) : a - (b + c) = a - b - c := (tsub_tsub _ _ _).symm lemma tsub_add_eq_tsub_tsub_swap (a b c : α) : a - (b + c) = a - c - b := by { rw [add_comm], apply tsub_add_eq_tsub_tsub } lemma tsub_right_comm : a - b - c = a - c - b := by simp_rw [← tsub_add_eq_tsub_tsub, add_comm] /-! ### Lemmas that assume that an element is `add_le_cancellable`. -/ namespace add_le_cancellable protected lemma tsub_eq_of_eq_add (hb : add_le_cancellable b) (h : a = c + b) : a - b = c := le_antisymm (tsub_le_iff_right.mpr h.le) $ by { rw h, exact hb.le_add_tsub } protected lemma eq_tsub_of_add_eq (hc : add_le_cancellable c) (h : a + c = b) : a = b - c := (hc.tsub_eq_of_eq_add h.symm).symm protected theorem tsub_eq_of_eq_add_rev (hb : add_le_cancellable b) (h : a = b + c) : a - b = c := hb.tsub_eq_of_eq_add $ by rw [add_comm, h] @[simp] protected lemma add_tsub_cancel_right (hb : add_le_cancellable b) : a + b - b = a := hb.tsub_eq_of_eq_add $ by rw [add_comm] @[simp] protected lemma add_tsub_cancel_left (ha : add_le_cancellable a) : a + b - a = b := ha.tsub_eq_of_eq_add $ add_comm a b protected lemma lt_add_of_tsub_lt_left (hb : add_le_cancellable b) (h : a - b < c) : a < b + c := begin rw [lt_iff_le_and_ne, ← tsub_le_iff_left], refine ⟨h.le, _⟩, rintro rfl, simpa [hb] using h, end protected lemma lt_add_of_tsub_lt_right (hc : add_le_cancellable c) (h : a - c < b) : a < b + c := begin rw [lt_iff_le_and_ne, ← tsub_le_iff_right], refine ⟨h.le, _⟩, rintro rfl, simpa [hc] using h, end protected lemma lt_tsub_of_add_lt_right (hc : add_le_cancellable c) (h : a + c < b) : a < b - c := (hc.le_tsub_of_add_le_right h.le).lt_of_ne $ by { rintro rfl, exact h.not_le le_tsub_add } protected lemma lt_tsub_of_add_lt_left (ha : add_le_cancellable a) (h : a + c < b) : c < b - a := ha.lt_tsub_of_add_lt_right $ by rwa add_comm end add_le_cancellable /-! #### Lemmas where addition is order-reflecting. -/ section contra variable [contravariant_class α α (+) (≤)] lemma tsub_eq_of_eq_add (h : a = c + b) : a - b = c := contravariant.add_le_cancellable.tsub_eq_of_eq_add h lemma eq_tsub_of_add_eq (h : a + c = b) : a = b - c := contravariant.add_le_cancellable.eq_tsub_of_add_eq h lemma tsub_eq_of_eq_add_rev (h : a = b + c) : a - b = c := contravariant.add_le_cancellable.tsub_eq_of_eq_add_rev h @[simp] lemma add_tsub_cancel_right (a b : α) : a + b - b = a := contravariant.add_le_cancellable.add_tsub_cancel_right @[simp] lemma add_tsub_cancel_left (a b : α) : a + b - a = b := contravariant.add_le_cancellable.add_tsub_cancel_left lemma lt_add_of_tsub_lt_left (h : a - b < c) : a < b + c := contravariant.add_le_cancellable.lt_add_of_tsub_lt_left h lemma lt_add_of_tsub_lt_right (h : a - c < b) : a < b + c := contravariant.add_le_cancellable.lt_add_of_tsub_lt_right h /-- This lemma (and some of its corollaries) also holds for `ennreal`, but this proof doesn't work for it. Maybe we should add this lemma as field to `has_ordered_sub`? -/ lemma lt_tsub_of_add_lt_left : a + c < b → c < b - a := contravariant.add_le_cancellable.lt_tsub_of_add_lt_left lemma lt_tsub_of_add_lt_right : a + c < b → a < b - c := contravariant.add_le_cancellable.lt_tsub_of_add_lt_right end contra section both variables [covariant_class α α (+) (≤)] [contravariant_class α α (+) (≤)] lemma add_tsub_add_eq_tsub_right (a c b : α) : (a + c) - (b + c) = a - b := begin refine add_tsub_add_le_tsub_right.antisymm (tsub_le_iff_right.2 $ le_of_add_le_add_right _), swap, rw add_assoc, exact le_tsub_add, end lemma add_tsub_add_eq_tsub_left (a b c : α) : (a + b) - (a + c) = b - c := by rw [add_comm a b, add_comm a c, add_tsub_add_eq_tsub_right] end both end ordered_add_comm_semigroup /-! ### Lemmas in a linearly ordered monoid. -/ section linear_order variables {a b c d : α} [linear_order α] [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] /-- See `lt_of_tsub_lt_tsub_right_of_le` for a weaker statement in a partial order. -/ lemma lt_of_tsub_lt_tsub_right (h : a - c < b - c) : a < b := lt_imp_lt_of_le_imp_le (λ h, tsub_le_tsub_right h c) h /-- See `lt_tsub_iff_right_of_le` for a weaker statement in a partial order. -/ lemma lt_tsub_iff_right : a < b - c ↔ a + c < b := lt_iff_lt_of_le_iff_le tsub_le_iff_right /-- See `lt_tsub_iff_left_of_le` for a weaker statement in a partial order. -/ lemma lt_tsub_iff_left : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le tsub_le_iff_left lemma lt_tsub_comm : a < b - c ↔ c < b - a := lt_tsub_iff_left.trans lt_tsub_iff_right.symm section cov variable [covariant_class α α (+) (≤)] /-- See `lt_of_tsub_lt_tsub_left_of_le` for a weaker statement in a partial order. -/ lemma lt_of_tsub_lt_tsub_left (h : a - b < a - c) : c < b := lt_imp_lt_of_le_imp_le (λ h, tsub_le_tsub_left h a) h end cov end linear_order section ordered_add_comm_monoid variables [partial_order α] [add_comm_monoid α] [has_sub α] [has_ordered_sub α] @[simp] lemma tsub_zero (a : α) : a - 0 = a := add_le_cancellable.tsub_eq_of_eq_add add_le_cancellable_zero (add_zero _).symm end ordered_add_comm_monoid
1000ef9f5e0fb37ae0ed57474d77bb02b7c3605c
b328e8ebb2ba923140e5137c83f09fa59516b793
/src/Lean/Util.lean
e15f1cbdafc444efcf2d16779885e196f0a35ce1
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
650
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.CollectFVars import Lean.Util.CollectLevelParams import Lean.Util.CollectMVars import Lean.Util.FindMVar import Lean.Util.MonadCache import Lean.Util.PPExt import Lean.Util.Path import Lean.Util.Profile import Lean.Util.RecDepth import Lean.Util.Sorry import Lean.Util.Trace import Lean.Util.FindExpr import Lean.Util.ReplaceExpr import Lean.Util.ForEachExpr import Lean.Util.ReplaceLevel import Lean.Util.FoldConsts import Lean.Util.Constructions import Lean.Util.SCC
5346299673e31cf406616912ed2ca9e290080ae0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/group_action/default.lean
f64b8ea3262f6aac0403a1e6f29a7d9ddb3cc338
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
39
lean
import group_theory.group_action.basic
0219725cd5befdd0c5143557f92b901f0e641977
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tactic20.lean
9f7e5ac0a9e90af206a048e99620dfa4cf61f62c
[ "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
166
lean
import logic open tactic definition assump := eassumption theorem tst {A : Type} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c := by apply eq.trans; assump; assump
699de398d66d97dd608a358b29dd23a29c874231
92b50235facfbc08dfe7f334827d47281471333b
/hott/algebra/category/constructions/comma.hlean
2d3dd637c00bc32d3100c7cb400a4f39430e2a19
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
6,840
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Comma category -/ import ..functor ..strict ..category open eq functor equiv sigma sigma.ops is_trunc iso is_equiv namespace category structure comma_object {A B C : Precategory} (S : A ⇒ C) (T : B ⇒ C) := (a : A) (b : B) (f : S a ⟶ T b) abbreviation ob1 [unfold 6] := @comma_object.a abbreviation ob2 [unfold 6] := @comma_object.b abbreviation mor [unfold 6] := @comma_object.f variables {A B C : Precategory} (S : A ⇒ C) (T : B ⇒ C) definition comma_object_sigma_char : (Σ(a : A) (b : B), S a ⟶ T b) ≃ comma_object S T := begin fapply equiv.MK, { intro u, exact comma_object.mk u.1 u.2.1 u.2.2}, { intro x, cases x with a b f, exact ⟨a, b, f⟩}, { intro x, cases x, reflexivity}, { intro u, cases u with u1 u2, cases u2, reflexivity}, end theorem is_trunc_comma_object (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B] [H : Π(s d : C), is_trunc n (hom s d)] : is_trunc n (comma_object S T) := by apply is_trunc_equiv_closed;apply comma_object_sigma_char variables {S T} definition comma_object_eq' {x y : comma_object S T} (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : x = y := begin cases x with a b f, cases y with a' b' f', cases p, cases q, esimp [ap011,congr,ap,subst] at r, eapply (idp_rec_on r), reflexivity end --TODO: remove. This is a different version where Hq is not in square brackets definition eq_comp_inverse_of_comp_eq' {ob : Type} {C : precategory ob} {d c b : ob} {r : hom c d} {q : hom b c} {x : hom b d} {Hq : is_iso q} (p : r ∘ q = x) : r = x ∘ q⁻¹ʰ := sorry --eq_inverse_comp_of_comp_eq p definition comma_object_eq {x y : comma_object S T} (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : T (hom_of_eq q) ∘ mor x ∘ S (inv_of_eq p) = mor y) : x = y := begin cases x with a b f, cases y with a' b' f', cases p, cases q, have r' : f = f', begin rewrite [▸* at r, -r, respect_id, id_left, respect_inv'], apply eq_comp_inverse_of_comp_eq', rewrite [respect_id,id_right] end, rewrite r' end definition ap_ob1_comma_object_eq' (x y : comma_object S T) (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : ap ob1 (comma_object_eq' p q r) = p := begin cases x with a b f, cases y with a' b' f', cases p, cases q, eapply (idp_rec_on r), reflexivity end definition ap_ob2_comma_object_eq' (x y : comma_object S T) (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : ap ob2 (comma_object_eq' p q r) = q := begin cases x with a b f, cases y with a' b' f', cases p, cases q, eapply (idp_rec_on r), reflexivity end structure comma_morphism (x y : comma_object S T) := mk' :: (g : ob1 x ⟶ ob1 y) (h : ob2 x ⟶ ob2 y) (p : T h ∘ mor x = mor y ∘ S g) (p' : mor y ∘ S g = T h ∘ mor x) abbreviation mor1 := @comma_morphism.g abbreviation mor2 := @comma_morphism.h abbreviation coh := @comma_morphism.p abbreviation coh' := @comma_morphism.p' protected definition comma_morphism.mk [constructor] [reducible] {x y : comma_object S T} (g h p) : comma_morphism x y := comma_morphism.mk' g h p p⁻¹ variables (x y z w : comma_object S T) definition comma_morphism_sigma_char : (Σ(g : ob1 x ⟶ ob1 y) (h : ob2 x ⟶ ob2 y), T h ∘ mor x = mor y ∘ S g) ≃ comma_morphism x y := begin fapply equiv.MK, { intro u, exact (comma_morphism.mk u.1 u.2.1 u.2.2)}, { intro f, cases f with g h p p', exact ⟨g, h, p⟩}, { intro f, cases f with g h p p', esimp, apply ap (comma_morphism.mk' g h p), apply is_hprop.elim}, { intro u, cases u with u1 u2, cases u2 with u2 u3, reflexivity}, end theorem is_trunc_comma_morphism (n : trunc_index) [H1 : is_trunc n (ob1 x ⟶ ob1 y)] [H2 : is_trunc n (ob2 x ⟶ ob2 y)] [Hp : Πm1 m2, is_trunc n (T m2 ∘ mor x = mor y ∘ S m1)] : is_trunc n (comma_morphism x y) := by apply is_trunc_equiv_closed; apply comma_morphism_sigma_char variables {x y z w} definition comma_morphism_eq {f f' : comma_morphism x y} (p : mor1 f = mor1 f') (q : mor2 f = mor2 f') : f = f' := begin cases f with g h p₁ p₁', cases f' with g' h' p₂ p₂', cases p, cases q, apply ap011 (comma_morphism.mk' g' h'), apply is_hprop.elim, apply is_hprop.elim end definition comma_compose (g : comma_morphism y z) (f : comma_morphism x y) : comma_morphism x z := comma_morphism.mk (mor1 g ∘ mor1 f) (mor2 g ∘ mor2 f) (by rewrite [+respect_comp,-assoc,coh,assoc,coh,-assoc]) local infix `∘∘`:60 := comma_compose definition comma_id : comma_morphism x x := comma_morphism.mk id id (by rewrite [+respect_id,id_left,id_right]) theorem comma_assoc (h : comma_morphism z w) (g : comma_morphism y z) (f : comma_morphism x y) : h ∘∘ (g ∘∘ f) = (h ∘∘ g) ∘∘ f := comma_morphism_eq !assoc !assoc theorem comma_id_left (f : comma_morphism x y) : comma_id ∘∘ f = f := comma_morphism_eq !id_left !id_left theorem comma_id_right (f : comma_morphism x y) : f ∘∘ comma_id = f := comma_morphism_eq !id_right !id_right variables (S T) definition comma_category [constructor] : Precategory := precategory.MK (comma_object S T) comma_morphism (λa b, !is_trunc_comma_morphism) (@comma_compose _ _ _ _ _) (@comma_id _ _ _ _ _) (@comma_assoc _ _ _ _ _) (@comma_id_left _ _ _ _ _) (@comma_id_right _ _ _ _ _) --TODO: this definition doesn't use category structure of A and B definition strict_precategory_comma [HA : strict_precategory A] [HB : strict_precategory B] : strict_precategory (comma_object S T) := strict_precategory.mk (comma_category S T) !is_trunc_comma_object --set_option pp.notation false definition is_univalent_comma (HA : is_univalent A) (HB : is_univalent B) : is_univalent (comma_category S T) := begin intros c d, fapply adjointify, { intro i, cases i with f s, cases s with g l r, cases f with fA fB fp, cases g with gA gB gp, esimp at *, fapply comma_object_eq, {apply iso_of_eq⁻¹ᶠ, exact (iso.MK fA gA (ap mor1 l) (ap mor1 r))}, {apply iso_of_eq⁻¹ᶠ, exact (iso.MK fB gB (ap mor2 l) (ap mor2 r))}, { apply sorry /-rewrite hom_of_eq_eq_of_iso,-/ }}, { apply sorry}, { apply sorry}, end end category
6d74a3d71aefdefabf7540f824d7f19071fc9e13
367134ba5a65885e863bdc4507601606690974c1
/src/computability/partrec_code.lean
3000a296324fc8e630ee21e89af02e6587d87ad4
[ "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
38,585
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Godel numbering for partial recursive functions. -/ import computability.partrec open encodable denumerable namespace nat.partrec open nat (mkpair) theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) := partrec₂.unpaired'.2 $ begin refine partrec.map ((@partrec₂.unpaired' (λ (a b : ℕ), nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + b))))).1 _) (primrec.nat_add.comp primrec.snd $ primrec.snd.comp primrec.fst).to_comp.to₂, have := rfind (partrec₂.unpaired'.2 ((partrec.nat_iff.2 hf).comp (primrec₂.mkpair.comp (primrec.fst.comp $ primrec.unpair.comp primrec.fst) (primrec.nat_add.comp primrec.snd (primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).to₂), simp at this, exact this end inductive code : Type | zero : code | succ : code | left : code | right : code | pair : code → code → code | comp : code → code → code | prec : code → code → code | rfind' : code → code end nat.partrec namespace nat.partrec.code open nat (mkpair unpair) open nat.partrec (code) instance : inhabited code := ⟨zero⟩ protected def const : ℕ → code | 0 := zero | (n+1) := comp succ (const n) theorem const_inj : Π {n₁ n₂}, nat.partrec.code.const n₁ = nat.partrec.code.const n₂ → n₁ = n₂ | 0 0 h := by simp | (n₁+1) (n₂+1) h := by { dsimp [nat.partrec.code.const] at h, injection h with h₁ h₂, simp only [const_inj h₂] } protected def id : code := pair left right def curry (c : code) (n : ℕ) : code := comp c (pair (code.const n) code.id) def encode_code : code → ℕ | zero := 0 | succ := 1 | left := 2 | right := 3 | (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4 def of_nat_code : ℕ → code | 0 := zero | 1 := succ | 2 := left | 3 := right | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, match n.bodd, n.div2.bodd with | ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, tt := rfind' (of_nat_code m) end private theorem encode_of_nat_code : ∀ n, encode_code (of_nat_code n) = n | 0 := rfl | 1 := rfl | 2 := rfl | 3 := rfl | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, have IH : _ := encode_of_nat_code m, have IH1 : _ := encode_of_nat_code m.unpair.1, have IH2 : _ := encode_of_nat_code m.unpair.2, begin transitivity, swap, rw [← nat.bit_decomp n, ← nat.bit_decomp n.div2], simp [encode_code, of_nat_code, -add_comm], cases n.bodd; cases n.div2.bodd; simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit] end instance : denumerable code := mk' ⟨encode_code, of_nat_code, λ c, by induction c; try {refl}; simp [ encode_code, of_nat_code, -add_comm, *], encode_of_nat_code⟩ theorem encode_code_eq : encode = encode_code := rfl theorem of_nat_code_eq : of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)), exact ⟨ lt_of_le_of_lt (nat.le_mkpair_left _ _) this, lt_of_le_of_lt (nat.le_mkpair_right _ _) this⟩ end theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code] end theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code], end theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, refine lt_of_le_of_lt (le_trans this _) (lt_add_of_pos_right _ (dec_trivial:0<4)), exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $ nat.bit0_lt_bit1 $ le_refl _), end section open primrec theorem pair_prim : primrec₂ pair := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem comp_prim : primrec₂ comp := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit1.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem prec_prim : primrec₂ prec := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem rfind_prim : primrec rfind' := of_nat_iff.2 $ encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit1.comp $ encode_iff.2 $ primrec.of_nat code) (const 4) theorem rec_prim' {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code × code × σ × σ → σ} (hpr : primrec₂ pr) {co : α → code × code × σ × σ → σ} (hco : primrec₂ co) {pc : α → code × code × σ × σ → σ} (hpc : primrec₂ pc) {rf : α → code × σ → σ} (hrf : primrec₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((primrec.of_nat code).comp m).pair s)) (hpc.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end theorem rec_prim {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code → code → σ → σ → σ} (hpr : primrec (λ a : α × code × code × σ × σ, pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {co : α → code → code → σ → σ → σ} (hco : primrec (λ a : α × code × code × σ × σ, co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {pc : α → code → code → σ → σ → σ} (hpc : primrec (λ a : α × code × code × σ × σ, pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {rf : α → code → σ → σ} (hrf : primrec (λ a : α × code × σ, rf a.1 a.2.1 a.2.2)) : let F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m) s) (pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)) (cond n.div2.bodd (co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂) (pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s)) (hpc.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end section open computable /- TODO(Mario): less copy-paste from previous proof -/ theorem rec_computable {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : computable c) {z : α → σ} (hz : computable z) {s : α → σ} (hs : computable s) {l : α → σ} (hl : computable l) {r : α → σ} (hr : computable r) {pr : α → code × code × σ × σ → σ} (hpr : computable₂ pr) {co : α → code × code × σ × σ → σ} (hco : computable₂ co) {pc : α → code × code × σ × σ → σ} (hpc : computable₂ pc) {rf : α → code × σ → σ} (hrf : computable₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in computable (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : computable G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (computable.unpair.comp m), have m₂ := snd.comp (computable.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((computable.of_nat code).comp m).pair s)) (hpc.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) (computable.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : computable₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp computable.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end def eval : code → ℕ →. ℕ | zero := pure 0 | succ := nat.succ | left := ↑(λ n : ℕ, n.unpair.1) | right := ↑(λ n : ℕ, n.unpair.2) | (pair cf cg) := λ n, mkpair <$> eval cf n <*> eval cg n | (comp cf cg) := λ n, eval cg n >>= eval cf | (prec cf cg) := nat.unpaired (λ a n, n.elim (eval cf a) (λ y IH, do i ← IH, eval cg (mkpair a (mkpair y i)))) | (rfind' cf) := nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> eval cf (mkpair a (n + m)))).map (+ m)) instance : has_mem (ℕ →. ℕ) code := ⟨λ f c, eval c = f⟩ @[simp] theorem eval_const : ∀ n m, eval (code.const n) m = roption.some n | 0 m := rfl | (n+1) m := by simp! * @[simp] theorem eval_id (n) : eval code.id n = roption.some n := by simp! [(<*>)] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) := by simp! [(<*>)] theorem const_prim : primrec code.const := (primrec.id.nat_iterate (primrec.const zero) (comp_prim.comp (primrec.const succ) primrec.snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, code.const, function.iterate_succ'] theorem curry_prim : primrec₂ curry := comp_prim.comp primrec.fst $ pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id) theorem curry_inj {c₁ c₂ n₁ n₂} (h : curry c₁ n₁ = curry c₂ n₂) : c₁ = c₂ ∧ n₁ = n₂ := ⟨by injection h, by { injection h, injection h with h₁ h₂, injection h₂ with h₃ h₄, exact const_inj h₃ }⟩ theorem smn : ∃ f : code → ℕ → code, computable₂ f ∧ ∀ c n x, eval (f c n) x = eval c (mkpair n x) := ⟨curry, primrec₂.to_comp curry_prim, eval_curry⟩ theorem exists_code {f : ℕ →. ℕ} : nat.partrec f ↔ ∃ c : code, eval c = f := ⟨λ h, begin induction h, case nat.partrec.zero { exact ⟨zero, rfl⟩ }, case nat.partrec.succ { exact ⟨succ, rfl⟩ }, case nat.partrec.left { exact ⟨left, rfl⟩ }, case nat.partrec.right { exact ⟨right, rfl⟩ }, case nat.partrec.pair : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨pair cf cg, rfl⟩ }, case nat.partrec.comp : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨comp cf cg, rfl⟩ }, case nat.partrec.prec : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨prec cf cg, rfl⟩ }, case nat.partrec.rfind : f pf hf { rcases hf with ⟨cf, rfl⟩, refine ⟨comp (rfind' cf) (pair code.id zero), _⟩, simp [eval, (<*>), pure, pfun.pure, roption.map_id'] }, end, λ h, begin rcases h with ⟨c, rfl⟩, induction c, case nat.partrec.code.zero { exact nat.partrec.zero }, case nat.partrec.code.succ { exact nat.partrec.succ }, case nat.partrec.code.left { exact nat.partrec.left }, case nat.partrec.code.right { exact nat.partrec.right }, case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg }, case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg }, case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg }, case nat.partrec.code.rfind' : cf pf { exact pf.rfind' }, end⟩ def evaln : ∀ k : ℕ, code → ℕ → option ℕ | 0 _ := λ m, none | (k+1) zero := λ n, guard (n ≤ k) >> pure 0 | (k+1) succ := λ n, guard (n ≤ k) >> pure (nat.succ n) | (k+1) left := λ n, guard (n ≤ k) >> pure n.unpair.1 | (k+1) right := λ n, guard (n ≤ k) >> pure n.unpair.2 | (k+1) (pair cf cg) := λ n, guard (n ≤ k) >> mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n | (k+1) (comp cf cg) := λ n, guard (n ≤ k) >> do x ← evaln (k+1) cg n, evaln (k+1) cf x | (k+1) (prec cf cg) := λ n, guard (n ≤ k) >> n.unpaired (λ a n, n.cases (evaln (k+1) cf a) $ λ y, do i ← evaln k (prec cf cg) (mkpair a y), evaln (k+1) cg (mkpair a (mkpair y i))) | (k+1) (rfind' cf) := λ n, guard (n ≤ k) >> n.unpaired (λ a m, do x ← evaln (k+1) cf (mkpair a m), if x = 0 then pure m else evaln k (rfind' cf) (mkpair a (m+1))) theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k | 0 c n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin suffices : ∀ {o : option ℕ}, x ∈ guard (n ≤ k) >> o → n < k + 1, { cases c; rw [evaln] at h; exact this h }, simpa [(>>)] using nat.lt_succ_of_le end theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n | 0 k₂ c n x hl h := by simp [evaln] at h; cases h | (k+1) (k₂+1) c n x hl h := begin have hl' := nat.le_of_succ_le_succ hl, have : ∀ {k k₂ n x : ℕ} {o₁ o₂ : option ℕ}, k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) → x ∈ guard (n ≤ k) >> o₁ → x ∈ guard (n ≤ k₂) >> o₂, { simp [(>>)], introv h h₁ h₂ h₃, exact ⟨le_trans h₂ h, h₁ h₃⟩ }, simp at h ⊢, induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; rw [evaln] at h ⊢; refine this hl' (λ h, _) h, iterate 4 {exact h}, { -- pair cf cg simp [(<*>)] at h ⊢, exact h.imp (λ a, and.imp (hf _ _) $ Exists.imp $ λ b, and.imp_left (hg _ _)) }, { -- comp cf cg simp at h ⊢, exact h.imp (λ a, and.imp (hg _ _) (hf _ _)) }, { -- prec cf cg revert h, simp, induction n.unpair.2; simp, { apply hf }, { exact λ y h₁ h₂, ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩ } }, { -- rfind' cf simp at h ⊢, refine h.imp (λ x, and.imp (hf _ _) _), by_cases x0 : x = 0; simp [x0], exact evaln_mono hl' } end theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n | 0 _ n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; simp [eval, evaln, (>>), (<*>)] at h ⊢; cases h with _ h, iterate 4 {simpa [pure, pfun.pure, eq_comm] using h}, { -- pair cf cg rcases h with ⟨y, ef, z, eg, rfl⟩, exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ }, { --comp hf hg rcases h with ⟨y, eg, ef⟩, exact ⟨_, hg _ _ eg, hf _ _ ef⟩ }, { -- prec cf cg revert h, induction n.unpair.2 with m IH generalizing x; simp, { apply hf }, { refine λ y h₁ h₂, ⟨y, IH _ _, _⟩, { have := evaln_mono k.le_succ h₁, simp [evaln, (>>)] at this, exact this.2 }, { exact hg _ _ h₂ } } }, { -- rfind' cf rcases h with ⟨m, h₁, h₂⟩, by_cases m0 : m = 0; simp [m0] at h₂, { exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, λ m, (nat.not_lt_zero _).elim⟩, by injection h₂ with h₂; simp [h₂]⟩ }, { have := evaln_sound h₂, simp [eval] at this, rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, refine ⟨ y+1, ⟨by simpa [add_comm, add_left_comm] using hy₁, λ i im, _⟩, by simp [add_comm, add_left_comm] ⟩, cases i with i, { exact ⟨m, by simpa using hf _ _ h₁, m0⟩ }, { rcases hy₂ (nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩, exact ⟨z, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hz, z0⟩ } } } end theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := ⟨λ h, begin suffices : ∃ k, x ∈ evaln (k+1) c n, { exact let ⟨k, h⟩ := this in ⟨k+1, h⟩ }, induction c generalizing n x; simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h ⊢, iterate 4 { exact ⟨⟨_, le_refl _⟩, h.symm⟩ }, case nat.partrec.code.pair : cf cg hf hg { rcases h with ⟨x, hx, y, hy, rfl⟩, rcases hf hx with ⟨k₁, hk₁⟩, rcases hg hy with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, refine ⟨le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂, rfl⟩ }, case nat.partrec.code.comp : cf cg hf hg { rcases h with ⟨y, hy, hx⟩, rcases hg hy with ⟨k₁, hk₁⟩, rcases hf hx with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ }, case nat.partrec.code.prec : cf cg hf hg { revert h, generalize : n.unpair.1 = n₁, generalize : n.unpair.2 = n₂, induction n₂ with m IH generalizing x n; simp, { intro, rcases hf h with ⟨k, hk⟩, exact ⟨_, le_max_left _ _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk⟩ }, { intros y hy hx, rcases IH hy with ⟨k₁, nk₁, hk₁⟩, rcases hg hx with ⟨k₂, hk₂⟩, refine ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_left_of_le $ le_trans (le_max_left _ (mkpair n₁ m)) nk₁, y, evaln_mono (nat.succ_le_succ $ le_max_left _ _) _, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hk₂⟩, simp [evaln, (>>)], exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩ } }, case nat.partrec.code.rfind' : cf hf { rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, suffices : ∃ k, y + n.unpair.2 ∈ evaln (k+1) (rfind' cf) (mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]}, revert hy₁ hy₂, generalize : n.unpair.2 = m, intros, induction y with y IH generalizing m; simp [evaln, (>>)], { simp at hy₁, rcases hf hy₁ with ⟨k, hk⟩, exact ⟨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; refl⟩ }, { rcases hy₂ (nat.succ_pos _) with ⟨a, ha, a0⟩, rcases hf ha with ⟨k₁, hk₁⟩, rcases IH m.succ (by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₁) (λ i hi, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₂ (nat.succ_lt_succ hi)) with ⟨k₂, hk₂⟩, use (max k₁ k₂).succ, rw [zero_add] at hk₁, use (nat.le_succ_of_le $ le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁), use a, use evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hk₁, simpa [nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right, add_comm, add_left_comm] using evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂ } } end, λ ⟨k, h⟩, evaln_sound h⟩ section open primrec private def lup (L : list (list (option ℕ))) (p : ℕ × code) (n : ℕ) := do l ← L.nth (encode p), o ← l.nth n, o private lemma hlup : primrec (λ p:_×(_×_)×_, lup p.1 p.2.1 p.2.2) := option_bind (list_nth.comp fst (primrec.encode.comp $ fst.comp snd)) (option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd) private def G (L : list (list (option ℕ))) : option (list (option ℕ)) := option.some $ let a := of_nat (ℕ × code) L.length, k := a.1, c := a.2 in (list.range k).map (λ n, k.cases none $ λ k', nat.partrec.code.rec_on c (some 0) -- zero (some (nat.succ n)) (some n.unpair.1) (some n.unpair.2) (λ cf cg _ _, do x ← lup L (k, cf) n, y ← lup L (k, cg) n, some (mkpair x y)) (λ cf cg _ _, do x ← lup L (k, cg) n, lup L (k, cf) x) (λ cf cg _ _, let z := n.unpair.1 in n.unpair.2.cases (lup L (k, cf) z) (λ y, do i ← lup L (k', c) (mkpair z y), lup L (k, cg) (mkpair z (mkpair y i)))) (λ cf _, let z := n.unpair.1, m := n.unpair.2 in do x ← lup L (k, cf) (mkpair z m), x.cases (some m) (λ _, lup L (k', c) (mkpair z (m+1))))) private lemma hG : primrec G := begin have a := (primrec.of_nat (ℕ × code)).comp list_length, have k := fst.comp a, refine option_some.comp (list_map (list_range.comp k) (_ : primrec _)), replace k := k.comp fst, have n := snd, refine nat_cases k (const none) (_ : primrec _), have k := k.comp fst, have n := n.comp fst, have k' := snd, have c := snd.comp (a.comp $ fst.comp fst), apply rec_prim c (const (some 0)) (option_some.comp (primrec.succ.comp n)) (option_some.comp (fst.comp $ primrec.unpair.comp n)) (option_some.comp (snd.comp $ primrec.unpair.comp n)), { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cf).pair n) (option_map ((hlup.comp $ L.pair $ (k.pair cg).pair n).comp fst) (primrec₂.mkpair.comp (snd.comp fst) snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cg).pair n) (hlup.comp ((L.comp fst).pair $ ((k.pair cf).comp fst).pair snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, have z := fst.comp (primrec.unpair.comp n), refine nat_cases (snd.comp (primrec.unpair.comp n)) (hlup.comp $ L.pair $ (k.pair cf).pair z) (_ : primrec _), have L := L.comp fst, have z := z.comp fst, have y := snd, refine option_bind (hlup.comp $ L.pair $ (((k'.pair c).comp fst).comp fst).pair (primrec₂.mkpair.comp z y)) (_ : primrec _), have z := z.comp fst, have y := y.comp fst, have i := snd, exact hlup.comp ((L.comp fst).pair $ ((k.pair cg).comp $ fst.comp fst).pair $ primrec₂.mkpair.comp z $ primrec₂.mkpair.comp y i) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have z := fst.comp (primrec.unpair.comp n), have m := snd.comp (primrec.unpair.comp n), refine option_bind (hlup.comp $ L.pair $ (k.pair cf).pair (primrec₂.mkpair.comp z m)) (_ : primrec _), have m := m.comp fst, exact nat_cases snd (option_some.comp m) ((hlup.comp ((L.comp fst).pair $ ((k'.pair c).comp $ fst.comp fst).pair (primrec₂.mkpair.comp (z.comp fst) (primrec.succ.comp m)))).comp fst) } end private lemma evaln_map (k c n) : (((list.range k).nth n).map (evaln k c)).bind (λ b, b) = evaln k c n := begin by_cases kn : n < k, { simp [list.nth_range kn] }, { rw list.nth_len_le, { cases e : evaln k c n, {refl}, exact kn.elim (evaln_bound e) }, simpa using kn } end theorem evaln_prim : primrec (λ (a : (ℕ × code) × ℕ), evaln a.1.1 a.1.2 a.2) := have primrec₂ (λ (_:unit) (n : ℕ), let a := of_nat (ℕ × code) n in (list.range a.1).map (evaln a.1 a.2)), from primrec.nat_strong_rec _ (hG.comp snd).to₂ $ λ _ p, begin simp [G], rw (_ : (of_nat (ℕ × code) _).snd = of_nat code p.unpair.2), swap, {simp}, apply list.map_congr (λ n, _), rw (by simp : list.range p = list.range (mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))), generalize : p.unpair.1 = k, generalize : of_nat code p.unpair.2 = c, intro nk, cases k with k', {simp [evaln]}, let k := k'+1, change k'.succ with k, simp [nat.lt_succ_iff] at nk, have hg : ∀ {k' c' n}, mkpair k' (encode c') < mkpair k (encode c) → lup ((list.range (mkpair k (encode c))).map (λ n, (list.range n.unpair.1).map (evaln n.unpair.1 (of_nat code n.unpair.2)))) (k', c') n = evaln k' c' n, { intros k₁ c₁ n₁ hl, simp [lup, list.nth_range hl, evaln_map, (>>=)] }, cases c with cf cg cf cg cf cg cf; simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure], { cases encode_lt_pair cf cg with lf lg, rw [hg (nat.mkpair_lt_mkpair_right _ lf), hg (nat.mkpair_lt_mkpair_right _ lg)], cases evaln k cf n, {refl}, cases evaln k cg n; refl }, { cases encode_lt_comp cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lg), cases evaln k cg n, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lf)] }, { cases encode_lt_prec cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases n.unpair.2, {refl}, simp, rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self), cases evaln k' _ _, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lg)] }, { have lf := encode_lt_rfind' cf, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases evaln k cf n with x, {refl}, simp, cases x; simp [nat.succ_ne_zero], rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) } end, (option_bind (list_nth.comp (this.comp (const ()) (encode_iff.2 fst)) snd) snd.to₂).of_eq $ λ ⟨⟨k, c⟩, n⟩, by simp [evaln_map] end section open partrec computable theorem eval_eq_rfind_opt (c n) : eval c n = nat.rfind_opt (λ k, evaln k c n) := roption.ext $ λ x, begin refine evaln_complete.trans (nat.rfind_opt_mono _).symm, intros a m n hl, apply evaln_mono hl, end theorem eval_part : partrec₂ eval := (rfind_opt (evaln_prim.to_comp.comp ((snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq $ λ a, by simp [eval_eq_rfind_opt] theorem fixed_point {f : code → code} (hf : computable f) : ∃ c : code, eval (f c) = eval c := let g (x y : ℕ) : roption ℕ := eval (of_nat code x) x >>= λ b, eval (of_nat code b) y in have partrec₂ g := (eval_part.comp ((computable.of_nat _).comp fst) fst).bind (eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).to₂, let ⟨cg, eg⟩ := exists_code.1 this in have eg' : ∀ a n, eval cg (mkpair a n) = roption.map encode (g a n) := by simp [eg], let F (x : ℕ) : code := f (curry cg x) in have computable F := hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp, let ⟨cF, eF⟩ := exists_code.1 this in have eF' : eval cF (encode cF) = roption.some (encode (F (encode cF))), by simp [eF], ⟨curry cg (encode cF), funext (λ n, show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n, by simp [eg', eF', roption.map_id', g])⟩ theorem fixed_point₂ {f : code → ℕ →. ℕ} (hf : partrec₂ f) : ∃ c : code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf in (fixed_point (curry_prim.comp (primrec.const cf) primrec.encode).to_comp).imp $ λ c e, funext $ λ n, by simp [e.symm, ef, roption.map_id'] end end nat.partrec.code
fa62415844c4d5595914edef43251d63349fe6ec
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/linear_algebra/finsupp.lean
b185fced46f057d7ae3500d35f3971b0e8b5f83d
[ "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
30,172
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ 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*} {P : Type*} {R : Type*} {S : Type*} variables [semiring R] [semiring S] [add_comm_monoid M] [semimodule R M] variables [add_comm_monoid N] [semimodule R N] variables [add_comm_monoid P] [semimodule R P] /-- 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, set_like.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 [set_like.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 $ set_like.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) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (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 _ _ (set_like.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 section lsum variables (S) [semimodule S N] [smul_comm_class R S N] /-- 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`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ def lsum : (α → M →ₗ[R] N) ≃ₗ[S] ((α →₀ 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 }, map_smul' := λ F G, by { ext x y, simp } } @[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum S f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) : finsupp.lsum S f l = l.sum (λ b, f b) := rfl theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) : finsupp.lsum S 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 S).symm f x = f.comp (lsingle x) := rfl end lsum section variables (M) (R) (X : Type*) /-- A slight rearrangement from `lsum` gives us the bijection underlying the free-forgetful adjunction for R-modules. -/ noncomputable def lift : (X → M) ≃+ ((X →₀ R) →ₗ[R] M) := (add_equiv.arrow_congr (equiv.refl X) (ring_lmap_equiv_self R M ℕ).to_add_equiv.symm).trans (lsum _ : _ ≃ₗ[ℕ] _).to_add_equiv @[simp] lemma lift_symm_apply (f) (x) : ((lift M R X).symm f) x = f (single x 1) := rfl @[simp] lemma lift_apply (f) (g) : ((lift M R X) f) g = g.sum (λ x r, r • f x) := rfl end section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) /-- Interpret `finsupp.map_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 [set_like.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) →ₗ[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 [set_like.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) := by { ext, simp [total_apply] } 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. This is `finsupp.dom_congr` as a `linear_equiv`.-/ 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] lemma dom_lcongr_refl : finsupp.dom_lcongr (equiv.refl α) = linear_equiv.refl R (α →₀ M) := linear_equiv.ext $ λ _, map_domain_id lemma dom_lcongr_trans {α₁ α₂ α₃ : Type*} (f : α₁ ≃ α₂) (f₂ : α₂ ≃ α₃) : (finsupp.dom_lcongr f).trans (finsupp.dom_lcongr f₂) = (finsupp.dom_lcongr (f.trans f₂) : (_ →₀ M) ≃ₗ[R] _) := linear_equiv.ext $ λ _, map_domain_comp.symm @[simp] lemma dom_lcongr_symm {α₁ α₂ : Type*} (f : α₁ ≃ α₂) : ((finsupp.dom_lcongr f).symm : (_ →₀ M) ≃ₗ[R] _) = finsupp.dom_lcongr f.symm := linear_equiv.ext $ λ x, rfl @[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 /-- `finsupp.map_range` as a `linear_map`. -/ @[simps] def map_range.linear_map (f : M →ₗ[R] N) : (α →₀ M) →ₗ[R] (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_smul' := λ c v, map_range_smul c v (f.map_smul c), ..map_range.add_monoid_hom f.to_add_monoid_hom } @[simp] lemma map_range.linear_map_id : map_range.linear_map linear_map.id = (linear_map.id : (α →₀ M) →ₗ[R] _):= linear_map.ext map_range_id lemma map_range.linear_map_comp (f : N →ₗ[R] P) (f₂ : M →ₗ[R] N) : (map_range.linear_map (f.comp f₂) : (α →₀ _) →ₗ[R] _) = (map_range.linear_map f).comp (map_range.linear_map f₂) := linear_map.ext $ map_range_comp _ _ _ _ _ /-- `finsupp.map_range` as a `linear_equiv`. -/ @[simps apply] def map_range.linear_equiv (e : M ≃ₗ[R] N) : (α →₀ M) ≃ₗ[R] (α →₀ N) := { to_fun := map_range e e.map_zero, inv_fun := map_range e.symm e.symm.map_zero, ..map_range.linear_map e.to_linear_map, ..map_range.add_equiv e.to_add_equiv} @[simp] lemma map_range.linear_equiv_refl : map_range.linear_equiv (linear_equiv.refl R M) = linear_equiv.refl R (α →₀ M) := linear_equiv.ext map_range_id lemma map_range.linear_equiv_trans (f : M ≃ₗ[R] N) (f₂ : N ≃ₗ[R] P) : (map_range.linear_equiv (f.trans f₂) : linear_equiv R (α →₀ _) _) = (map_range.linear_equiv f).trans (map_range.linear_equiv f₂) := linear_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.linear_equiv_symm (f : M ≃ₗ[R] N) : ((map_range.linear_equiv f).symm : (α →₀ _) ≃ₗ[R] _) = map_range.linear_equiv f.symm := linear_equiv.ext $ λ x, rfl /-- 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 (map_range.linear_equiv e₂) @[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] @[simp] lemma lcongr_apply_apply {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (f : ι →₀ M) (k : κ) : lcongr e₁ e₂ f k = e₂ (f (e₁.symm k)) := begin apply finsupp.induction_linear f, { simp, }, { intros f g hf hg, simp [map_add, hf, hg], }, { intros i m, simp only [finsupp.lcongr_single], simp only [finsupp.single, equiv.eq_symm_apply, finsupp.coe_mk], split_ifs; simp, }, end theorem lcongr_symm_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (k : κ) (n : N) : (lcongr e₁ e₂).symm (finsupp.single k n) = finsupp.single (e₁.symm k) (e₂.symm n) := begin apply_fun lcongr e₁ e₂ using (lcongr e₁ e₂).injective, simp, end @[simp] lemma lcongr_symm {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (lcongr e₁ e₂).symm = lcongr e₁.symm e₂.symm := begin ext f i, simp only [equiv.symm_symm, finsupp.lcongr_apply_apply], apply finsupp.induction_linear f, { simp, }, { intros f g hf hg, simp [map_add, hf, hg], }, { intros k m, simp only [finsupp.lcongr_symm_single], simp only [finsupp.single, equiv.symm_apply_eq, finsupp.coe_mk], split_ifs; simp, }, end section sum variables (R) /-- The linear equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `linear_equiv` version of `finsupp.sum_finsupp_equiv_prod_finsupp`. -/ @[simps apply symm_apply] def sum_finsupp_lequiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃ₗ[R] (α →₀ M) × (β →₀ M) := { map_smul' := by { intros, ext; simp only [add_equiv.to_fun_eq_coe, prod.smul_fst, prod.smul_snd, smul_apply, snd_sum_finsupp_add_equiv_prod_finsupp, fst_sum_finsupp_add_equiv_prod_finsupp] }, .. sum_finsupp_add_equiv_prod_finsupp } lemma fst_sum_finsupp_lequiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_lequiv_prod_finsupp R f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_lequiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_lequiv_prod_finsupp R f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_lequiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : ((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_lequiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : ((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inr y) = fg.2 y := rfl end sum 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, ← set_like.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)⟩ /-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if `m` can be written as a finite `R`-linear combination of elements of `s`. The implementation uses `finsupp.sum`. -/ lemma mem_span_set {m : M} {s : set M} : m ∈ submodule.span R s ↔ ∃ c : M →₀ R, (c.support : set M) ⊆ s ∧ c.sum (λ mi r, r • mi) = m := begin conv_lhs { rw ←set.image_id s }, simp_rw ←exists_prop, exact finsupp.mem_span_iff_total R, end
1653092a005b1299471c28b05d1458d325fe6eea
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/ReduceJpArity.lean
5687267b66e8b73db35ae1de8940cde39d008324
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,430
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.CompilerM import Lean.Compiler.LCNF.InferType import Lean.Compiler.LCNF.PassManager namespace Lean.Compiler.LCNF /-! Join point arity reduction. -/ namespace ReduceJpArity abbrev ReduceM := ReaderT (FVarIdMap (Array Bool)) CompilerM partial def reduce (code : Code) : ReduceM Code := do match code with | .let decl k => return code.updateLet! decl (← reduce k) | .fun decl k => let value ← reduce decl.value let decl ← decl.update' decl.type value return code.updateFun! decl (← reduce k) | .jp decl k => let value ← reduce decl.value let mut used := value.collectUsed let mut mask := #[] let mut paramsNew := #[] for param in decl.params.reverse do if used.contains param.fvarId then used := collectUsedAtExpr used param.type mask := mask.push true paramsNew := paramsNew.push param else eraseParam param mask := mask.push false mask := mask.reverse paramsNew := paramsNew.reverse if paramsNew.size != decl.params.size then let type ← mkForallParams paramsNew (← value.inferType) let decl ← decl.update type paramsNew value let k ← withReader (·.insert decl.fvarId mask) (reduce k) return .jp decl k else let decl ← decl.update' decl.type value return code.updateFun! decl (← reduce k) | .cases c => let alts ← c.alts.mapMonoM fun alt => return alt.updateCode (← reduce alt.getCode) return code.updateAlts! alts | .return .. | .unreach .. => return code | .jmp fvarId args => if let some mask := (← read).find? fvarId then let mut argsNew := #[] for keep in mask, arg in args do if keep then argsNew := argsNew.push arg return .jmp fvarId argsNew else return code end ReduceJpArity open ReduceJpArity /-- Try to reduce arity of join points -/ def Decl.reduceJpArity (decl : Decl) : CompilerM Decl := do let value ← reduce decl.value |>.run {} return { decl with value } def reduceJpArity (phase := Phase.base) : Pass := .mkPerDeclaration `reduceJpArity Decl.reduceJpArity phase builtin_initialize registerTraceClass `Compiler.reduceJpArity (inherited := true) end Lean.Compiler.LCNF
e726b3ecd3246832c6d1b3a7f351f38adf7e8aa7
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/countable/defs.lean
8cb56fdef833bdeb8c6e80f460120251d9f69417
[ "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
3,218
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.finite.defs /-! # Countable types In this file we define a typeclass saying that a given `Sort*` is countable. See also `encodable` for a version that singles out a specific encoding of elements of `α` by natural numbers. This file also provides a few instances of this typeclass. More instances can be found in other files. -/ open function universes u v variables {α : Sort u} {β : Sort v} /-! ### Definition and basic properties -/ /-- A type `α` is countable if there exists an injective map `α → ℕ`. -/ @[mk_iff countable_iff_exists_injective] class countable (α : Sort u) : Prop := (exists_injective_nat [] : ∃ f : α → ℕ, injective f) instance : countable ℕ := ⟨⟨id, injective_id⟩⟩ export countable (exists_injective_nat) protected lemma function.injective.countable [countable β] {f : α → β} (hf : injective f) : countable α := let ⟨g, hg⟩ := exists_injective_nat β in ⟨⟨g ∘ f, hg.comp hf⟩⟩ protected lemma function.surjective.countable [countable α] {f : α → β} (hf : surjective f) : countable β := (injective_surj_inv hf).countable lemma exists_surjective_nat (α : Sort u) [nonempty α] [countable α] : ∃ f : ℕ → α, surjective f := let ⟨f, hf⟩ := exists_injective_nat α in ⟨inv_fun f, inv_fun_surjective hf⟩ lemma countable_iff_exists_surjective [nonempty α] : countable α ↔ ∃ f : ℕ → α, surjective f := ⟨@exists_surjective_nat _ _, λ ⟨f, hf⟩, hf.countable⟩ lemma countable.of_equiv (α : Sort*) [countable α] (e : α ≃ β) : countable β := e.symm.injective.countable lemma equiv.countable_iff (e : α ≃ β) : countable α ↔ countable β := ⟨λ h, @countable.of_equiv _ _ h e, λ h, @countable.of_equiv _ _ h e.symm⟩ instance {β : Type v} [countable β] : countable (ulift.{u} β) := countable.of_equiv _ equiv.ulift.symm /-! ### Operations on `Sort*`s -/ instance [countable α] : countable (plift α) := equiv.plift.injective.countable @[priority 100] instance subsingleton.to_countable [subsingleton α] : countable α := ⟨⟨λ _, 0, λ x y h, subsingleton.elim x y⟩⟩ @[priority 500] instance [countable α] {p : α → Prop} : countable {x // p x} := subtype.val_injective.countable instance {n : ℕ} : countable (fin n) := subtype.countable @[priority 100] instance finite.to_countable [finite α] : countable α := let ⟨n, ⟨e⟩⟩ := finite.exists_equiv_fin α in countable.of_equiv _ e.symm instance : countable punit.{u} := subsingleton.to_countable @[nolint instance_priority] instance Prop.countable (p : Prop) : countable p := subsingleton.to_countable instance bool.countable : countable bool := ⟨⟨λ b, cond b 0 1, bool.injective_iff.2 nat.one_ne_zero⟩⟩ instance Prop.countable' : countable Prop := countable.of_equiv bool equiv.Prop_equiv_bool.symm @[priority 500] instance [countable α] {r : α → α → Prop} : countable (quot r) := (surjective_quot_mk r).countable @[priority 500] instance [countable α] {s : setoid α} : countable (quotient s) := quot.countable
e8ce78260d4059c98e3d523db10293894c9ce135
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/ordinal_notation_auto.lean
e96c9c660c1e5e815cb633184a34916f324119ea
[]
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
20,470
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.set_theory.ordinal_arithmetic import Mathlib.PostPort universes l u_1 namespace Mathlib /-! # Ordinal notations constructive ordinal arithmetic for ordinals `< ε₀`. -/ /-- Recursive definition of an ordinal notation. `zero` denotes the ordinal 0, and `oadd e n a` is intended to refer to `ω^e * n + a`. For this to be valid Cantor normal form, we must have the exponents decrease to the right, but we can't state this condition until we've defined `repr`, so it is a separate definition `NF`. -/ inductive onote where | zero : onote | oadd : onote → ℕ+ → onote → onote namespace onote /-- Notation for 0 -/ protected instance has_zero : HasZero onote := { zero := zero } @[simp] theorem zero_def : zero = 0 := rfl protected instance inhabited : Inhabited onote := { default := 0 } /-- Notation for 1 -/ protected instance has_one : HasOne onote := { one := oadd 0 1 0 } /-- Notation for ω -/ def omega : onote := oadd 1 1 0 /-- The ordinal denoted by a notation -/ @[simp] def repr : onote → ordinal := sorry /-- Auxiliary definition to print an ordinal notation -/ def to_string_aux1 (e : onote) (n : ℕ) (s : string) : string := ite (e = 0) (to_string n) (ite (e = 1) (string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 (bit1 (bit1 1))))))))))) (string.str (string.str (string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 (bit1 (bit1 1))))))))))) (char.of_nat (bit0 (bit1 (bit1 (bit1 (bit1 (bit0 1)))))))) (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 1)))))) ++ s ++ string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 1))))))) ++ ite (n = 1) string.empty (string.str string.empty (char.of_nat (bit0 (bit1 (bit0 (bit1 (bit0 1)))))) ++ to_string n)) /-- Print an ordinal notation -/ def to_string : onote → string := sorry /-- Print an ordinal notation -/ def repr' : onote → string := sorry protected instance has_to_string : has_to_string onote := has_to_string.mk to_string protected instance has_repr : has_repr onote := has_repr.mk repr' protected instance preorder : preorder onote := preorder.mk (fun (x y : onote) => repr x ≤ repr y) (fun (x y : onote) => repr x < repr y) sorry sorry theorem lt_def {x : onote} {y : onote} : x < y ↔ repr x < repr y := iff.rfl theorem le_def {x : onote} {y : onote} : x ≤ y ↔ repr x ≤ repr y := iff.rfl /-- Convert a `nat` into an ordinal -/ @[simp] def of_nat : ℕ → onote := sorry @[simp] theorem of_nat_one : of_nat 1 = 1 := rfl @[simp] theorem repr_of_nat (n : ℕ) : repr (of_nat n) = ↑n := sorry @[simp] theorem repr_one : repr 1 = 1 := sorry theorem omega_le_oadd (e : onote) (n : ℕ+) (a : onote) : ordinal.omega ^ repr e ≤ repr (oadd e n a) := sorry theorem oadd_pos (e : onote) (n : ℕ+) (a : onote) : 0 < oadd e n a := lt_of_lt_of_le (ordinal.power_pos (repr e) ordinal.omega_pos) (omega_le_oadd e n a) /-- Compare ordinal notations -/ def cmp : onote → onote → ordering := sorry theorem eq_of_cmp_eq {o₁ : onote} {o₂ : onote} : cmp o₁ o₂ = ordering.eq → o₁ = o₂ := sorry theorem zero_lt_one : 0 < 1 := eq.mpr (id (Eq._oldrec (Eq.refl (0 < 1)) (propext lt_def))) (eq.mpr (id (Eq._oldrec (Eq.refl (repr 0 < repr 1)) repr.equations._eqn_1)) (eq.mpr (id (Eq._oldrec (Eq.refl (0 < repr 1)) repr_one)) ordinal.zero_lt_one)) /-- `NF_below o b` says that `o` is a normal form ordinal notation satisfying `repr o < ω ^ b`. -/ inductive NF_below : onote → ordinal → Prop where | zero : ∀ {b : ordinal}, NF_below 0 b | oadd' : ∀ {e : onote} {n : ℕ+} {a : onote} {eb b : ordinal}, NF_below e eb → NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b /-- A normal form ordinal notation has the form ω ^ a₁ * n₁ + ω ^ a₂ * n₂ + ... ω ^ aₖ * nₖ where `a₁ > a₂ > ... > aₖ` and all the `aᵢ` are also in normal form. We will essentially only be interested in normal form ordinal notations, but to avoid complicating the algorithms we define everything over general ordinal notations and only prove correctness with normal form as an invariant. -/ def NF (o : onote) := Exists (NF_below o) protected instance NF.zero : NF 0 := Exists.intro 0 NF_below.zero theorem NF_below.oadd {e : onote} {n : ℕ+} {a : onote} {b : ordinal} : NF e → NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b := sorry theorem NF_below.fst {e : onote} {n : ℕ+} {a : onote} {b : ordinal} (h : NF_below (oadd e n a) b) : NF e := sorry theorem NF.fst {e : onote} {n : ℕ+} {a : onote} : NF (oadd e n a) → NF e := fun (ᾰ : NF (oadd e n a)) => Exists.dcases_on ᾰ fun (ᾰ_w : ordinal) (ᾰ_h : NF_below (oadd e n a) ᾰ_w) => idRhs (NF e) (NF_below.fst ᾰ_h) theorem NF_below.snd {e : onote} {n : ℕ+} {a : onote} {b : ordinal} (h : NF_below (oadd e n a) b) : NF_below a (repr e) := sorry theorem NF.snd' {e : onote} {n : ℕ+} {a : onote} : NF (oadd e n a) → NF_below a (repr e) := fun (ᾰ : NF (oadd e n a)) => Exists.dcases_on ᾰ fun (ᾰ_w : ordinal) (ᾰ_h : NF_below (oadd e n a) ᾰ_w) => idRhs (NF_below a (repr e)) (NF_below.snd ᾰ_h) theorem NF.snd {e : onote} {n : ℕ+} {a : onote} (h : NF (oadd e n a)) : NF a := Exists.intro (repr e) (NF.snd' h) theorem NF.oadd {e : onote} {a : onote} (h₁ : NF e) (n : ℕ+) (h₂ : NF_below a (repr e)) : NF (oadd e n a) := Exists.intro (ordinal.succ (repr e)) (NF_below.oadd h₁ h₂ (ordinal.lt_succ_self (repr e))) protected instance NF.oadd_zero (e : onote) (n : ℕ+) [h : NF e] : NF (oadd e n 0) := NF.oadd h n NF_below.zero theorem NF_below.lt {e : onote} {n : ℕ+} {a : onote} {b : ordinal} (h : NF_below (oadd e n a) b) : repr e < b := sorry theorem NF_below_zero {o : onote} : NF_below o 0 ↔ o = 0 := sorry theorem NF.zero_of_zero {e : onote} {n : ℕ+} {a : onote} (h : NF (oadd e n a)) (e0 : e = 0) : a = 0 := sorry theorem NF_below.repr_lt {o : onote} {b : ordinal} (h : NF_below o b) : repr o < ordinal.omega ^ b := sorry theorem NF_below.mono {o : onote} {b₁ : ordinal} {b₂ : ordinal} (bb : b₁ ≤ b₂) (h : NF_below o b₁) : NF_below o b₂ := sorry theorem NF.below_of_lt {e : onote} {n : ℕ+} {a : onote} {b : ordinal} (H : repr e < b) : NF (oadd e n a) → NF_below (oadd e n a) b := sorry theorem NF.below_of_lt' {o : onote} {b : ordinal} : repr o < ordinal.omega ^ b → NF o → NF_below o b := sorry theorem NF_below_of_nat (n : ℕ) : NF_below (of_nat n) 1 := nat.cases_on n (idRhs (NF_below 0 1) NF_below.zero) fun (n : ℕ) => idRhs (NF_below (oadd 0 (nat.succ_pnat n) 0) 1) (NF_below.oadd NF.zero NF_below.zero ordinal.zero_lt_one) protected instance NF_of_nat (n : ℕ) : NF (of_nat n) := Exists.intro 1 (NF_below_of_nat n) protected instance NF_one : NF 1 := eq.mpr (id (Eq._oldrec (Eq.refl (NF 1)) (Eq.symm of_nat_one))) (onote.NF_of_nat 1) theorem oadd_lt_oadd_1 {e₁ : onote} {n₁ : ℕ+} {o₁ : onote} {e₂ : onote} {n₂ : ℕ+} {o₂ : onote} (h₁ : NF (oadd e₁ n₁ o₁)) (h : e₁ < e₂) : oadd e₁ n₁ o₁ < oadd e₂ n₂ o₂ := lt_of_lt_of_le (NF_below.repr_lt (NF.below_of_lt h h₁)) (omega_le_oadd e₂ n₂ o₂) theorem oadd_lt_oadd_2 {e : onote} {o₁ : onote} {o₂ : onote} {n₁ : ℕ+} {n₂ : ℕ+} (h₁ : NF (oadd e n₁ o₁)) (h : ↑n₁ < ↑n₂) : oadd e n₁ o₁ < oadd e n₂ o₂ := sorry theorem oadd_lt_oadd_3 {e : onote} {n : ℕ+} {a₁ : onote} {a₂ : onote} (h : a₁ < a₂) : oadd e n a₁ < oadd e n a₂ := sorry theorem cmp_compares (a : onote) (b : onote) [NF a] [NF b] : ordering.compares (cmp a b) a b := sorry theorem repr_inj {a : onote} {b : onote} [NF a] [NF b] : repr a = repr b ↔ a = b := sorry theorem NF.of_dvd_omega_power {b : ordinal} {e : onote} {n : ℕ+} {a : onote} (h : NF (oadd e n a)) (d : ordinal.omega ^ b ∣ repr (oadd e n a)) : b ≤ repr e ∧ ordinal.omega ^ b ∣ repr a := sorry theorem NF.of_dvd_omega {e : onote} {n : ℕ+} {a : onote} (h : NF (oadd e n a)) : ordinal.omega ∣ repr (oadd e n a) → repr e ≠ 0 ∧ ordinal.omega ∣ repr a := sorry /-- `top_below b o` asserts that the largest exponent in `o`, if it exists, is less than `b`. This is an auxiliary definition for decidability of `NF`. -/ def top_below (b : onote) : onote → Prop := sorry protected instance decidable_top_below : DecidableRel top_below := id fun (b o : onote) => onote.cases_on o (id decidable.true) fun (o_ᾰ : onote) (o_ᾰ_1 : ℕ+) (o_ᾰ_2 : onote) => id (ordering.decidable_eq (cmp o_ᾰ b) ordering.lt) theorem NF_below_iff_top_below {b : onote} [NF b] {o : onote} : NF_below o (repr b) ↔ NF o ∧ top_below b o := sorry protected instance decidable_NF : decidable_pred NF := sorry /-- Addition of ordinal notations (correct only for normal input) -/ def add : onote → onote → onote := sorry protected instance has_add : Add onote := { add := add } @[simp] theorem zero_add (o : onote) : 0 + o = o := rfl theorem oadd_add (e : onote) (n : ℕ+) (a : onote) (o : onote) : oadd e n a + o = add._match_1 e n (a + o) := rfl /-- Subtraction of ordinal notations (correct only for normal input) -/ def sub : onote → onote → onote := sorry protected instance has_sub : Sub onote := { sub := sub } theorem add_NF_below {b : ordinal} {o₁ : onote} {o₂ : onote} : NF_below o₁ b → NF_below o₂ b → NF_below (o₁ + o₂) b := sorry protected instance add_NF (o₁ : onote) (o₂ : onote) [NF o₁] [NF o₂] : NF (o₁ + o₂) := sorry @[simp] theorem repr_add (o₁ : onote) (o₂ : onote) [NF o₁] [NF o₂] : repr (o₁ + o₂) = repr o₁ + repr o₂ := sorry theorem sub_NF_below {o₁ : onote} {o₂ : onote} {b : ordinal} : NF_below o₁ b → NF o₂ → NF_below (o₁ - o₂) b := sorry protected instance sub_NF (o₁ : onote) (o₂ : onote) [NF o₁] [NF o₂] : NF (o₁ - o₂) := sorry @[simp] theorem repr_sub (o₁ : onote) (o₂ : onote) [NF o₁] [NF o₂] : repr (o₁ - o₂) = repr o₁ - repr o₂ := sorry /-- Multiplication of ordinal notations (correct only for normal input) -/ def mul : onote → onote → onote := sorry protected instance has_mul : Mul onote := { mul := mul } @[simp] theorem zero_mul (o : onote) : 0 * o = 0 := onote.cases_on o (Eq.refl (0 * zero)) fun (o_ᾰ : onote) (o_ᾰ_1 : ℕ+) (o_ᾰ_2 : onote) => Eq.refl (0 * oadd o_ᾰ o_ᾰ_1 o_ᾰ_2) @[simp] theorem mul_zero (o : onote) : o * 0 = 0 := onote.cases_on o (Eq.refl (zero * 0)) fun (o_ᾰ : onote) (o_ᾰ_1 : ℕ+) (o_ᾰ_2 : onote) => Eq.refl (oadd o_ᾰ o_ᾰ_1 o_ᾰ_2 * 0) theorem oadd_mul (e₁ : onote) (n₁ : ℕ+) (a₁ : onote) (e₂ : onote) (n₂ : ℕ+) (a₂ : onote) : oadd e₁ n₁ a₁ * oadd e₂ n₂ a₂ = ite (e₂ = 0) (oadd e₁ (n₁ * n₂) a₁) (oadd (e₁ + e₂) n₂ (oadd e₁ n₁ a₁ * a₂)) := rfl theorem oadd_mul_NF_below {e₁ : onote} {n₁ : ℕ+} {a₁ : onote} {b₁ : ordinal} (h₁ : NF_below (oadd e₁ n₁ a₁) b₁) {o₂ : onote} {b₂ : ordinal} : NF_below o₂ b₂ → NF_below (oadd e₁ n₁ a₁ * o₂) (repr e₁ + b₂) := sorry protected instance mul_NF (o₁ : onote) (o₂ : onote) [NF o₁] [NF o₂] : NF (o₁ * o₂) := sorry @[simp] theorem repr_mul (o₁ : onote) (o₂ : onote) [NF o₁] [NF o₂] : repr (o₁ * o₂) = repr o₁ * repr o₂ := sorry /-- Calculate division and remainder of `o` mod ω. `split' o = (a, n)` means `o = ω * a + n`. -/ def split' : onote → onote × ℕ := sorry /-- Calculate division and remainder of `o` mod ω. `split o = (a, n)` means `o = a + n`, where `ω ∣ a`. -/ def split : onote → onote × ℕ := sorry /-- `scale x o` is the ordinal notation for `ω ^ x * o`. -/ def scale (x : onote) : onote → onote := sorry /-- `mul_nat o n` is the ordinal notation for `o * n`. -/ def mul_nat : onote → ℕ → onote := sorry /-- Auxiliary definition to compute the ordinal notation for the ordinal exponentiation in `power` -/ def power_aux (e : onote) (a0 : onote) (a : onote) : ℕ → ℕ → onote := sorry /-- `power o₁ o₂` calculates the ordinal notation for the ordinal exponential `o₁ ^ o₂`. -/ def power (o₁ : onote) (o₂ : onote) : onote := sorry protected instance has_pow : has_pow onote onote := has_pow.mk power theorem power_def (o₁ : onote) (o₂ : onote) : o₁ ^ o₂ = power._match_1 o₂ (split o₁) := rfl theorem split_eq_scale_split' {o : onote} {o' : onote} {m : ℕ} [NF o] : split' o = (o', m) → split o = (scale 1 o', m) := sorry theorem NF_repr_split' {o : onote} {o' : onote} {m : ℕ} [NF o] : split' o = (o', m) → NF o' ∧ repr o = ordinal.omega * repr o' + ↑m := sorry theorem scale_eq_mul (x : onote) [NF x] (o : onote) [NF o] : scale x o = oadd x 1 0 * o := sorry protected instance NF_scale (x : onote) [NF x] (o : onote) [NF o] : NF (scale x o) := eq.mpr (id (Eq._oldrec (Eq.refl (NF (scale x o))) (scale_eq_mul x o))) (onote.mul_NF (oadd x 1 0) o) @[simp] theorem repr_scale (x : onote) [NF x] (o : onote) [NF o] : repr (scale x o) = ordinal.omega ^ repr x * repr o := sorry theorem NF_repr_split {o : onote} {o' : onote} {m : ℕ} [NF o] (h : split o = (o', m)) : NF o' ∧ repr o = repr o' + ↑m := sorry theorem split_dvd {o : onote} {o' : onote} {m : ℕ} [NF o] (h : split o = (o', m)) : ordinal.omega ∣ repr o' := sorry theorem split_add_lt {o : onote} {e : onote} {n : ℕ+} {a : onote} {m : ℕ} [NF o] (h : split o = (oadd e n a, m)) : repr a + ↑m < ordinal.omega ^ repr e := sorry @[simp] theorem mul_nat_eq_mul (n : ℕ) (o : onote) : mul_nat o n = o * of_nat n := sorry protected instance NF_mul_nat (o : onote) [NF o] (n : ℕ) : NF (mul_nat o n) := eq.mpr (id ((fun (o o_1 : onote) (e_1 : o = o_1) => congr_arg NF e_1) (mul_nat o n) (o * of_nat n) (mul_nat_eq_mul n o))) (onote.mul_NF o (of_nat n)) protected instance NF_power_aux (e : onote) (a0 : onote) (a : onote) [NF e] [NF a0] [NF a] (k : ℕ) (m : ℕ) : NF (power_aux e a0 a k m) := sorry protected instance NF_power (o₁ : onote) (o₂ : onote) [NF o₁] [NF o₂] : NF (o₁ ^ o₂) := sorry theorem scale_power_aux (e : onote) (a0 : onote) (a : onote) [NF e] [NF a0] [NF a] (k : ℕ) (m : ℕ) : repr (power_aux e a0 a k m) = ordinal.omega ^ repr e * repr (power_aux 0 a0 a k m) := sorry theorem repr_power_aux₁ {e : onote} {a : onote} [Ne : NF e] [Na : NF a] {a' : ordinal} (e0 : repr e ≠ 0) (h : a' < ordinal.omega ^ repr e) (aa : repr a = a') (n : ℕ+) : (ordinal.omega ^ repr e * ↑↑n + a') ^ ordinal.omega = (ordinal.omega ^ repr e) ^ ordinal.omega := sorry theorem repr_power_aux₂ {a0 : onote} {a' : onote} [N0 : NF a0] [Na' : NF a'] (m : ℕ) (d : ordinal.omega ∣ repr a') (e0 : repr a0 ≠ 0) (h : repr a' + ↑m < ordinal.omega ^ repr a0) (n : ℕ+) (k : ℕ) : let R : ordinal := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m); (k ≠ 0 → R < (ordinal.omega ^ repr a0) ^ ordinal.succ ↑k) ∧ (ordinal.omega ^ repr a0) ^ ↑k * (ordinal.omega ^ repr a0 * ↑↑n + repr a') + R = (ordinal.omega ^ repr a0 * ↑↑n + repr a' + ↑m) ^ ordinal.succ ↑k := sorry theorem repr_power (o₁ : onote) (o₂ : onote) [NF o₁] [NF o₂] : repr (o₁ ^ o₂) = repr o₁ ^ repr o₂ := sorry end onote /-- The type of normal ordinal notations. (It would have been nicer to define this right in the inductive type, but `NF o` requires `repr` which requires `onote`, so all these things would have to be defined at once, which messes up the VM representation.) -/ def nonote := Subtype fun (o : onote) => onote.NF o protected instance nonote.decidable_eq : DecidableEq nonote := eq.mpr sorry fun (a b : Subtype fun (o : onote) => onote.NF o) => subtype.decidable_eq a b namespace nonote protected instance NF (o : nonote) : onote.NF (subtype.val o) := subtype.property o /-- Construct a `nonote` from an ordinal notation (and infer normality) -/ def mk (o : onote) [h : onote.NF o] : nonote := { val := o, property := h } /-- The ordinal represented by an ordinal notation. (This function is noncomputable because ordinal arithmetic is noncomputable. In computational applications `nonote` can be used exclusively without reference to `ordinal`, but this function allows for correctness results to be stated.) -/ def repr (o : nonote) : ordinal := onote.repr (subtype.val o) protected instance has_to_string : has_to_string nonote := has_to_string.mk fun (x : nonote) => onote.to_string (subtype.val x) protected instance has_repr : has_repr nonote := has_repr.mk fun (x : nonote) => onote.repr' (subtype.val x) protected instance preorder : preorder nonote := preorder.mk (fun (x y : nonote) => repr x ≤ repr y) (fun (x y : nonote) => repr x < repr y) sorry sorry protected instance has_zero : HasZero nonote := { zero := { val := 0, property := onote.NF.zero } } protected instance inhabited : Inhabited nonote := { default := 0 } /-- Convert a natural number to an ordinal notation -/ def of_nat (n : ℕ) : nonote := { val := onote.of_nat n, property := sorry } /-- Compare ordinal notations -/ def cmp (a : nonote) (b : nonote) : ordering := onote.cmp (subtype.val a) (subtype.val b) theorem cmp_compares (a : nonote) (b : nonote) : ordering.compares (cmp a b) a b := sorry protected instance linear_order : linear_order nonote := linear_order_of_compares cmp cmp_compares /-- Asserts that `repr a < ω ^ repr b`. Used in `nonote.rec_on` -/ def old_below (a : nonote) (b : nonote) := onote.NF_below (subtype.val a) (repr b) /-- The `oadd` pseudo-constructor for `nonote` -/ def oadd (e : nonote) (n : ℕ+) (a : nonote) (h : old_below a e) : nonote := { val := onote.oadd (subtype.val e) n (subtype.val a), property := sorry } /-- This is a recursor-like theorem for `nonote` suggesting an inductive definition, which can't actually be defined this way due to conflicting dependencies. -/ def rec_on {C : nonote → Sort u_1} (o : nonote) (H0 : C 0) (H1 : (e : nonote) → (n : ℕ+) → (a : nonote) → (h : old_below a e) → C e → C a → C (oadd e n a h)) : C o := subtype.cases_on o fun (o : onote) (h : onote.NF o) => onote.rec (fun (h : onote.NF onote.zero) => H0) (fun (e : onote) (n : ℕ+) (a : onote) (IHe : (h : onote.NF e) → C { val := e, property := h }) (IHa : (h : onote.NF a) → C { val := a, property := h }) (h : onote.NF (onote.oadd e n a)) => H1 { val := e, property := onote.NF.fst h } n { val := a, property := onote.NF.snd h } (onote.NF.snd' h) (IHe (onote.NF.fst h)) (IHa (onote.NF.snd h))) o h /-- Addition of ordinal notations -/ protected instance has_add : Add nonote := { add := fun (x y : nonote) => mk (subtype.val x + subtype.val y) } theorem repr_add (a : nonote) (b : nonote) : repr (a + b) = repr a + repr b := onote.repr_add (subtype.val a) (subtype.val b) /-- Subtraction of ordinal notations -/ protected instance has_sub : Sub nonote := { sub := fun (x y : nonote) => mk (subtype.val x - subtype.val y) } theorem repr_sub (a : nonote) (b : nonote) : repr (a - b) = repr a - repr b := onote.repr_sub (subtype.val a) (subtype.val b) /-- Multiplication of ordinal notations -/ protected instance has_mul : Mul nonote := { mul := fun (x y : nonote) => mk (subtype.val x * subtype.val y) } theorem repr_mul (a : nonote) (b : nonote) : repr (a * b) = repr a * repr b := onote.repr_mul (subtype.val a) (subtype.val b) /-- Exponentiation of ordinal notations -/ def power (x : nonote) (y : nonote) : nonote := mk (onote.power (subtype.val x) (subtype.val y)) theorem repr_power (a : nonote) (b : nonote) : repr (power a b) = ordinal.power (repr a) (repr b) := onote.repr_power (subtype.val a) (subtype.val b) end Mathlib
edcefae622790d01fa0b754daa0e1ae9c6e47ede
0d7f5899c0475f9e105a439896d9377f80c0d7c3
/src/.old/lang.lean
d9d2d84c801e1783cb7510a060fbc583c15432bc
[]
no_license
adamtopaz/UnivAlg
127038f320e68cdf3efcd0c084c9af02fdb8da3d
2458d47a6e4fd0525e3a25b07cb7dd518ac173ef
refs/heads/master
1,670,320,985,286
1,597,350,882,000
1,597,350,882,000
280,585,500
4
0
null
1,597,350,883,000
1,595,048,527,000
Lean
UTF-8
Lean
false
false
7,565
lean
import data.vector import .for_mathlib --------------- lang --------------- section universe v structure lang := (op : ℕ → Type v) namespace lang instance : has_coe_to_fun lang := ⟨_,op⟩ end lang end --------------- ralg --------------- section universes v u structure ralg (L : lang.{v}) := (carrier : Type u) (appo {n} : L n → vector carrier n → carrier) namespace ralg instance {L} : has_coe_to_sort (ralg L) := ⟨_,carrier⟩ end ralg end notation `applyo` := ralg.appo _ ----------- terms ----------------- section universes v namespace lang inductive term (L : lang.{v}) : ℕ → ℕ → Type v | of {n} : L n → term n 1 | proj {m n} : (fin m → fin n) → term n m | comp {a b c} : term a b → term b c → term a c | liftl {a b c} : term a b → term (a + c) (b + c) | liftr {a b c} : term a b → term (c + a) (c + b) end lang end def applyt {L : lang} {A : ralg L} {m n} (t : L.term m n) : vector A m → vector A n := lang.term.rec_on t (λ _ t as, vector.of $ applyo t as) (λ _ _, vector.proj) (λ _ _ _ _ _ f g, g ∘ f) (λ _ _ _ _, vector.liftl) (λ _ _ _ _, vector.liftr) ------------------- rules ------------------------- structure rules (L : lang) := (cond {m n} : L.term m n → L.term m n → Prop) namespace rules instance {L} : has_coe_to_fun (rules L) := ⟨_,cond⟩ end rules ----------------- ualg -------------------------- structure ualg (L : lang) (R : rules L) extends ralg L := (cond_eq {m n} {t1 t2 : L.term m n} {as : vector carrier m} : R t1 t2 → applyt t1 as = applyt t2 as) namespace ualg instance {L} {R} : has_coe_to_sort (ualg L R) := ⟨_,λ A, A.carrier⟩ end ualg namespace ualg def raw {L} {R} : ualg L R → ralg L := to_ralg end ualg ------------------ langHom ----------------- structure langHom (L1 : lang) (L2 : lang) := (map_op {n} : L1 n → L2 n) infixr ` →# `:25 := langHom namespace langHom instance {L1} {L2} : has_coe_to_fun (L1 →# L2) := ⟨_,map_op⟩ end langHom namespace lang.term variables {L1 : lang} {L2 : lang} (ι : L1 →# L2) include ι def mapt {m n} (t : L1.term m n) : L2.term m n := lang.term.rec_on t (λ _ t, of $ ι t) (λ _ _, proj) (λ _ _ _ _ _, comp) (λ _ _ _ _, liftl) (λ _ _ _ _, liftr) end lang.term ------------------- rulesHom ------------------ structure rulesHom {L1 : lang} {L2 : lang} (R1 : rules L1) (R2 : rules L2) := (lhom : L1 →# L2) (map_cond {m n} {t1 t2 : L1.term m n} : R1 t1 t2 → R2 (t1.mapt lhom) (t2.mapt lhom)) infixr ` →$ `:25 := rulesHom -------------------- algHom's ------------------ structure ralgHom {L : lang} (A : ralg L) (B : ralg L) := (to_fn : A → B) (applyo_map {n} {t : L n} {as : vector A n}: applyo t (as.map to_fn) = to_fn (applyo t as)) def ualgHom {L : lang} {R1 R2 : rules L} (A : ualg L R1) (B : ualg L R2) := ralgHom A.raw B.raw def ralgualgHom {L : lang} {R : rules L} (A : ralg L) (B : ualg L R) := ralgHom A B.raw def ualgralgHom {L : lang} {R : rules L} (A : ualg L R) (B : ralg L) := ralgHom A.raw B namespace ralgHom instance {L} {A : ralg L} {B : ralg L} : has_coe_to_fun (ralgHom A B) := ⟨_,to_fn⟩ end ralgHom namespace ualgHom instance {L} {R1 R2 : rules L} {A : ualg L R1} {B : ualg L R2} : has_coe_to_fun (ualgHom A B) := ⟨_,λ f, f.to_fn⟩ end ualgHom namespace ralgualgHom instance {L} {R : rules L} {A : ralg L} {B : ualg L R} : has_coe_to_fun (ralgualgHom A B) := ⟨_,λ f, f.to_fn⟩ end ralgualgHom namespace ualgralgHom instance {L} {R : rules L} {A : ualg L R} {B : ralg L} : has_coe_to_fun (ualgralgHom A B) := ⟨_,λ f, f.to_fn⟩ end ualgralgHom infixr ` →% `:25 := ralgHom infixr ` →% `:25 := ualgHom infixr ` →% `:25 := ralgualgHom infixr ` →% `:25 := ualgralgHom ---------------- theorems abouts homs ----------- namespace ralgHom variables {L : lang} {A : ralg L} {B : ralg L} @[ext] theorem ext (f g : A →% B) : ⇑f = g → f = g := λ hyp, by {cases f, cases g, simpa} end ralgHom namespace ralg variables {L : lang} {A : ralg L} {B : ralg L} /- A ralg hom commutes with applyo. -/ theorem applyo_map {n} (f : A →% B) (t : L n) (as : vector A n) : applyo t (as.map f) = f (applyo t as) := by apply ralgHom.applyo_map /- A ralg hom commutes with applyt. -/ theorem applyt_map {m n} (f : A →% B) (t : L.term m n) (as : vector A m) : applyt t (as.map f) = (applyt t as).map f := begin induction t with _ _ _ _ _ _ _ _ _ _ h1 h2 _ _ _ _ h3 _ _ _ _ h4, { change vector.of _ = _, rw [applyo_map, ←vector.map_of], refl }, { change vector.proj _ _ = vector.map _ (vector.proj _ _), rw vector.map_proj }, { change (applyt _ (applyt _ _)) = _, rw [h1,h2], refl }, { change _ = vector.map f (vector.append (applyt _ _) _), rw vector.map_append, rw ←h3, change vector.append (applyt _ _) _ = _, congr, { rw vector.map_init }, { rw vector.map_last } }, { change _ = vector.map f (vector.append _ (applyt _ _)), rw vector.map_append, rw ←h4, change vector.append _ (applyt _ _) = _, congr, { rw vector.map_init }, { rw vector.map_last } }, end end ralg --------------------- composition ------------------------- namespace ralgHom variables {L : lang} {A : ralg L} {B : ralg L} {C : ralg L} {D : ralg L} def comp : (A →% B) → (B →% C) → (A →% C) := λ f g, { to_fn := g ∘ f, applyo_map := λ n t as, by rw ←vector.map_map; simp only [ralg.applyo_map] } theorem comp_assoc {f : A →% B} {g : B →% C} {h : C →% D} : (f.comp g).comp h = f.comp (g.comp h) := rfl end ralgHom -------------------- forget_along ----------------------- /- Here we construct some forgetful functors. -/ namespace ralg variables {L0 : lang} {L : lang} (ι : L0 →# L) (A : ralg L) include ι A def forget_along : ralg L0 := { carrier := A, appo := λ n t, applyo (ι t) } end ralg notation A `{`:1000 ι `}`:1000 := ralg.forget_along ι A namespace ralg variables {L0 : lang} {L : lang} (ι : L0 →# L) def cast {A : ralg L} : A → A{ι} := id def uncast {A : ralg L} : A{ι} → A := id include ι theorem applyt_mapt {m n} {A : ralg L} (t : L0.term m n) (as : vector (A{ι}) m): applyt t as = vector.map (cast ι) (applyt (t.mapt ι) (as.map (uncast ι))) := begin simp only [cast, uncast, vector.map_id], induction t with _ _ _ _ _ _ _ _ _ _ h1 h2 _ _ _ _ h3 _ _ _ _ h4, { refl }, { refl }, { change applyt _ (applyt _ _) = _, rw [h1,h2], refl }, { change vector.append (applyt _ _) _ = _, rw h3, refl }, { change vector.append _ (applyt _ _) = _, rw h4, refl }, end end ralg namespace ualg variables {L0 : lang} {L : lang} {R0 : rules L0} {R : rules L} variables (ι : R0 →$ R) (A : ualg _ R) include ι A def forget_along : ualg _ R0 := { cond_eq := λ m n t1 t2 as h, begin simp_rw ralg.applyt_mapt, apply congr_arg, apply A.cond_eq, apply ι.map_cond, assumption, end, ..show ralg L0, by exact A.raw{ι.lhom} } end ualg notation A `⦃`:1000 ι `⦄`:1000 := ualg.forget_along ι A example {L0 : lang} {L : lang} {R0 : rules L0} {R : rules L} (ι : R0 →$ R) (A : ualg _ R) : A⦃ι⦄.raw = A.raw{ι.lhom} := rfl ----------------- forget_along for morphisms ---------------------- namespace ralgHom variables {L0 : lang} {L1 : lang} (ι : L0 →# L1) variables {A : ralg L1} {B : ralg L1} def forget_along (f : A →% B) : A{ι} →% B{ι} := { to_fn := f, applyo_map := λ n t as, by {erw ralg.applyo_map, refl} } end ralgHom notation A `{%`:1000 ι `}`:1000 := ralgHom.forget_along ι A
3fbabe11b764c063b290332309f9422dda58a53c
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/nat/fib.lean
1f2cda4f49e59f9612a8fc57bfee91835b17b1c3
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
5,632
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import data.stream.basic import tactic import data.nat.gcd /-! # The Fibonacci Sequence ## Summary Definition of the Fibonacci sequence `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`. ## Main Definitions - `fib` returns the stream of Fibonacci numbers. ## Main Statements - `fib_succ_succ` : shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.`. - `fib_gcd` : `fib n` is a strong divisibility sequence. ## Implementation Notes For efficiency purposes, the sequence is defined using `stream.iterate`. ## Tags fib, fibonacci -/ namespace nat /-- Auxiliary function used in the definition of `fib_aux_stream`. -/ private def fib_aux_step : (ℕ × ℕ) → (ℕ × ℕ) := λ p, ⟨p.snd, p.fst + p.snd⟩ /-- Auxiliary stream creating Fibonacci pairs `⟨Fₙ, Fₙ₊₁⟩`. -/ private def fib_aux_stream : stream (ℕ × ℕ) := stream.iterate fib_aux_step ⟨0, 1⟩ /-- Implementation of the fibonacci sequence satisfying `fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`. *Note:* We use a stream iterator for better performance when compared to the naive recursive implementation. -/ @[pp_nodot] def fib (n : ℕ) : ℕ := (fib_aux_stream n).fst @[simp] lemma fib_zero : fib 0 = 0 := rfl @[simp] lemma fib_one : fib 1 = 1 := rfl @[simp] lemma fib_two : fib 2 = 1 := rfl private lemma fib_aux_stream_succ {n : ℕ} : fib_aux_stream (n + 1) = fib_aux_step (fib_aux_stream n) := begin change (stream.nth (n + 1) $ stream.iterate fib_aux_step ⟨0, 1⟩) = fib_aux_step (stream.nth n $ stream.iterate fib_aux_step ⟨0, 1⟩), rw [stream.nth_succ_iterate, stream.map_iterate, stream.nth_map] end /-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.` -/ lemma fib_succ_succ {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := by simp only [fib, fib_aux_stream_succ, fib_aux_step] lemma fib_pos {n : ℕ} (n_pos : 0 < n) : 0 < fib n := begin induction n with n IH, case nat.zero { norm_num at n_pos }, case nat.succ { cases n, case nat.zero { simp [fib_succ_succ, zero_lt_one] }, case nat.succ { have : 0 ≤ fib n, by simp, exact (lt_add_of_nonneg_of_lt this $ IH n.succ_pos) }} end lemma fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by { cases n; simp [fib_succ_succ] } lemma fib_mono {n m : ℕ} (n_le_m : n ≤ m) : fib n ≤ fib m := by { induction n_le_m with m n_le_m IH, { refl }, { exact (le_trans IH fib_le_fib_succ) }} lemma le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := begin induction five_le_n with n five_le_n IH, { have : 5 = fib 5, by refl, -- 5 ≤ fib 5 exact le_of_eq this }, { -- n + 1 ≤ fib (n + 1) for 5 ≤ n cases n with n', -- rewrite n = succ n' to use fib.succ_succ { have : 5 = 0, from nat.le_zero_iff.elim_left five_le_n, contradiction }, rw fib_succ_succ, suffices : 1 + (n' + 1) ≤ fib n' + fib (n' + 1), by rwa [nat.succ_eq_add_one, add_comm], have : n' ≠ 0, by { intro h, have : 5 ≤ 1, by rwa h at five_le_n, norm_num at this }, have : 1 ≤ fib n', from nat.succ_le_of_lt (fib_pos $ pos_iff_ne_zero.mpr this), mono } end /-- Subsequent Fibonacci numbers are coprime, see https://proofwiki.org/wiki/Consecutive_Fibonacci_Numbers_are_Coprime -/ lemma fib_coprime_fib_succ (n : ℕ) : nat.coprime (fib n) (fib (n + 1)) := begin unfold coprime, induction n with n ih, { simp }, { convert ih using 1, rw [fib_succ_succ, succ_eq_add_one, gcd_rec, add_mod_right, gcd_comm (fib n), gcd_rec (fib (n + 1))], } end /-- See https://proofwiki.org/wiki/Fibonacci_Number_in_terms_of_Smaller_Fibonacci_Numbers -/ lemma fib_add (m n : ℕ) : fib m * fib n + fib (m + 1) * fib (n + 1) = fib (m + n + 1) := begin induction n with n ih generalizing m, { simp }, { intros, specialize ih (m + 1), rw [add_assoc m 1 n, add_comm 1 n] at ih, simp only [fib_succ_succ, ← ih], ring, } end lemma gcd_fib_add_self (m n : ℕ) : gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n) := begin cases eq_zero_or_pos n, { rw h, simp }, replace h := nat.succ_pred_eq_of_pos h, rw [← h, succ_eq_add_one], calc gcd (fib m) (fib (n.pred + 1 + m)) = gcd (fib m) (fib (n.pred) * (fib m) + fib (n.pred + 1) * fib (m + 1)) : by { rw fib_add n.pred _, ring } ... = gcd (fib m) (fib (n.pred + 1) * fib (m + 1)) : by rw [add_comm, gcd_add_mul_self (fib m) _ (fib (n.pred))] ... = gcd (fib m) (fib (n.pred + 1)) : coprime.gcd_mul_right_cancel_right (fib (n.pred + 1)) (coprime.symm (fib_coprime_fib_succ m)) end lemma gcd_fib_add_mul_self (m n : ℕ) : ∀ k, gcd (fib m) (fib (n + k * m)) = gcd (fib m) (fib n) | 0 := by simp | (k+1) := by rw [← gcd_fib_add_mul_self k, add_mul, ← add_assoc, one_mul, gcd_fib_add_self _ _] /-- `fib n` is a strong divisibility sequence, see https://proofwiki.org/wiki/GCD_of_Fibonacci_Numbers -/ lemma fib_gcd (m n : ℕ) : fib (gcd m n) = gcd (fib m) (fib n) := begin wlog h : m ≤ n using [n m, m n], exact le_total m n, { apply gcd.induction m n, { simp }, intros m n mpos h, rw ← gcd_rec m n at h, conv_rhs { rw ← mod_add_div n m }, rwa [mul_comm, gcd_fib_add_mul_self m (n % m) (n / m), gcd_comm (fib m) _] }, rwa [gcd_comm, gcd_comm (fib m)] end lemma fib_dvd (m n : ℕ) (h : m ∣ n) : fib m ∣ fib n := by rwa [gcd_eq_left_iff_dvd, ← fib_gcd, gcd_eq_left_iff_dvd.mp] end nat
5a4ea990b6bf0aa611a260f0d852ee843214313e
1dd482be3f611941db7801003235dc84147ec60a
/src/data/equiv/basic.lean
387d80b392945b80a046d2d75151786dc95509bc
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
31,913
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 In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import logic.function logic.unique data.set.basic data.bool open function universes u v w 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) namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α infix ` ≃ `:50 := equiv instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from funext $ assume x, have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm, have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this, by simp * @[extensionality] lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[extensionality] lemma perm.ext (σ τ : equiv.perm α) (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext _ _ H @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ protected theorem bijective : ∀ f : α ≃ β, bijective f | ⟨f, g, h₁, h₂⟩ := ⟨injective_of_left_inverse h₁, surjective_of_has_right_inverse ⟨_, h₂⟩⟩ protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α | ⟨H⟩ := ⟨λ a b, e.bijective.1 (H _ _)⟩ protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.bijective.1.eq_iff 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 refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_inverse_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁ @[simp] theorem inverse_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁ @[simp] lemma inverse_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl 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_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by cases e; refl @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp) @[simp] theorem 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 def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩ def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β := equiv_congr e e protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by rw [← set.image_comp]; simpa using set.image_id s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `α` -/ namespace perm instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply inverse_apply_apply end @[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) : f⁻¹ (f x) = x := equiv.inverse_apply_apply _ _ @[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) : f (f⁻¹ x) = x := equiv.apply_inverse_apply _ _ lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def equiv_pempty (h : α → false) : α ≃ pempty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := equiv_empty $ assume a, h ⟨a⟩ def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)), λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)), λ h, by funext a; dsimp; rw [l₁, l₂], λ h, by funext a; dsimp; rw [r₁, r₂]⟩ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by cases u; refl, λ u, by cases u; reflexivity⟩ section @[simp] 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⟩ @[simp] def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩ @[simp] def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ :β₁ ≃ β₂) : (α₁ × β₁) ≃ (α₂ × β₂) := ⟨λp, (e₁ p.1, e₂ p.2), λp, (e₁.symm p.1, e₂.symm p.2), λ ⟨a, b⟩, show (e₁.symm (e₁ a), e₂.symm (e₂ b)) = (a, b), by rw [inverse_apply_apply, inverse_apply_apply], λ ⟨a, b⟩, show (e₁ (e₁.symm a), e₂ (e₂.symm b)) = (a, b), by rw [apply_inverse_apply, apply_inverse_apply]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) : prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) := rfl @[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) := ⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] 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⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_punit (α : Sort*) : (α × punit.{u+1}) ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl @[simp] def punit_prod (α : Sort*) : (punit.{u+1} × α) ≃ α := calc (punit × α) ≃ (α × punit) : prod_comm _ _ ... ≃ α : prod_punit _ @[simp] theorem punit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl @[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) @[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) @[simp] def prod_pempty (α : Sort*) : (α × pempty) ≃ pempty := equiv_pempty (λ ⟨_, e⟩, e.rec _) @[simp] def pempty_prod (α : Sort*) : (pempty × α) ≃ pempty := equiv_pempty (λ ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end, λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end, λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end, λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := by cases e₁; cases e₂; refl @[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := by cases e₁; cases e₂; refl 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⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ @[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) := ⟨λ s, match s with inl a := inr a | inr b := inl b end, λ s, match s with inl b := inr b | inr a := inl a end, λ s, by cases s; refl, λ s, by cases s; refl⟩ @[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, λ s, by rcases s with ⟨_ | _⟩ | _; refl, λ s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] def sum_pempty (α : Sort*) : (α ⊕ pempty) ≃ α := ⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def pempty_sum (α : Sort*) : (pempty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_pempty _ @[simp] def option_equiv_sum_punit (α : Sort*) : option α ≃ (α ⊕ punit.{u+1}) := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ def equiv_fib {α β : Type*} (f : α → β) : α ≃ Σ y : β, {x // f x = y} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨y, x, rfl⟩, rfl⟩ end section 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⟩ end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section 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⟩ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨λ f, λ p, f p.1 p.2, λ f, λ a b, f (a, b), λ f, rfl, λ f, by funext p; cases p; refl⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p s, sum.rec_on s p.1 p.2, λ f, by funext s; cases s; refl, λ p, by cases p; refl⟩ def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; 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 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 def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) := calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (α × (unit ⊕ unit)) : prod_comm _ _ ... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _ ... ≃ (α ⊕ α) : sum_congr (prod_punit _) (prod_punit _) end section open sum nat 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⟩ @[simp] def nat_sum_punit_equiv_nat : (ℕ ⊕ punit.{u+1}) ≃ ℕ := nat_equiv_nat_sum_punit.symm def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α | a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.bijective.1.eq_iff def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ def unique_of_equiv (e : α ≃ β) (h : unique β) : unique α := unique.of_surjective e.symm.bijective.2 def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := e.symm.unique_of_equiv, inv_fun := e.unique_of_equiv, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } section open subtype def subtype_equiv_of_subtype {p : α → Prop} : Π (e : α ≃ β), {a : α // p a} ≃ {b : β // p (e.symm b)} | ⟨f, g, l, r⟩ := ⟨subtype.map f $ assume a ha, show p (g (f a)), by rwa [l], subtype.map g $ assume a ha, ha, assume p, by simp [map_comp, l.comp_eq_id]; rw [map_id]; refl, assume p, by simp [map_comp, r.comp_eq_id]; rw [map_id]; refl⟩ def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ /-- aka coimage -/ def equiv_sigma_subtype {α : Type u} {β : Type v} (f : α → β) : α ≃ Σ b, {x : α // f x = b} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨b, x, H⟩, sigma.eq H $ eq.drec_on H $ subtype.eq rfl⟩ 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 _⟩ def subtype_congr {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := ⟨subtype.map id $ by rw [h]; exact assume h, id, subtype.map id $ by rw [h]; exact assume h, id, assume ⟨a, h⟩, rfl, assume ⟨a, h⟩, rfl,⟩ def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_congr h end section local attribute [elab_with_expected_type] quot.lift def quot_equiv_of_quot' {r : α → α → Prop} {s : β → β → Prop} (e : α ≃ β) (h : ∀ a a', r a a' ↔ s (e a) (e a')) : quot r ≃ quot s := ⟨quot.lift (λ a, quot.mk _ (e a)) (λ a a' H, quot.sound ((h a a').mp H)), quot.lift (λ b, quot.mk _ (e.symm b)) (λ b b' H, quot.sound ((h _ _).mpr (by convert H; simp))), quot.ind $ by simp, quot.ind $ by simp⟩ def quot_equiv_of_quot {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := quot_equiv_of_quot' e (by simp) end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ (s ⊕ t) := ⟨λ ⟨x, h⟩, if hp : p x then sum.inl ⟨_, h.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, h.resolve_left (λ xs, hp (hs _ xs))⟩, λ o, match o with | (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩ | (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩ end, λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, union'._match_2, h]; congr, λ o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union'._match_1, union'._match_2, h]; [simp [hs _ h], simp [ht _ h]]⟩ protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ (s ⊕ t) := set.union' s (λ _, id) (λ x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩) protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by simp at h; subst x, λ ⟨⟩, rfl⟩ protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ (s ⊕ punit.{u+1}) := by rw ← union_singleton; exact (set.union $ inter_singleton_eq_empty.2 H).trans (sum_congr (equiv.refl _) (set.singleton _)) protected def sum_compl {α} (s : set α) [decidable_pred s] : (s ⊕ (-s : set α)) ≃ α := (set.union (inter_compl_self _)).symm.trans (by rw union_compl_self; exact set.univ _) protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] : ((s ∪ t : set α) ⊕ (s ∩ t : set α)) ≃ (s ⊕ t) := calc ((s ∪ t : set α) ⊕ (s ∩ t : set α)) ≃ ((s ∪ t \ s : set α) ⊕ (s ∩ t : set α)) : by rw [union_diff_self] ... ≃ ((s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α)) : sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _) ... ≃ (s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α)) : sum_assoc _ _ _ ... ≃ (s ⊕ (t \ s ∪ s ∩ t : set α)) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ (s ⊕ t) : by rw (_ : t \ s ∪ s ∩ t = t); rw [union_comm, inter_comm, inter_union_diff] protected def prod {α β} (s : set α) (t : set β) : (s.prod t) ≃ (s × t) := ⟨λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩, λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := (set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ) @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := by dunfold equiv.set.range equiv.set.univ; simp [set_coe_cast, -image_univ, image_univ.symm] end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := ⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))), λ x, classical.some_spec (hf.2 x)⟩ @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl lemma 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.eq' (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) } section swap variable [decidable_eq α] open decidable 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⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ λ 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 b = a; simp [swap_apply_def, *] 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 _ := eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _ 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 @[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq α] [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 swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) : swap i j (swap i j a) = a := by rw [← perm.mul_apply, swap_mul_self, perm.one_apply] /-- 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 instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq def unique_unique_equiv : unique (unique α) ≃ unique α := { to_fun := λ h, h.default, inv_fun := λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β := { to_fun := λ _, default β, inv_fun := λ _, default α, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_punit_of_unique [unique α] : α ≃ punit.{v} := equiv_of_unique_of_unique
f64cec2b2bd5f4c72d7988665e41205d2f797538
510e96af568b060ed5858226ad954c258549f143
/data/num/lemmas.lean
01b22bd94522de586cab32a18670cf41b7297ded
[]
no_license
Shamrock-Frost/library_dev
cb6d1739237d81e17720118f72ba0a6db8a5906b
0245c71e4931d3aceeacf0aea776454f6ee03c9c
refs/heads/master
1,609,481,034,595
1,500,165,215,000
1,500,165,347,000
97,350,162
0
0
null
1,500,164,969,000
1,500,164,969,000
null
UTF-8
Lean
false
false
15,929
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Properties of the binary representation of integers. -/ import .basic .bitwise meta def unfold_coe : tactic unit := `[unfold coe lift_t has_lift_t.lift coe_t has_coe_t.coe coe_b has_coe.coe] namespace pos_num theorem one_to_nat : ((1 : pos_num) : ℕ) = 1 := rfl theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl theorem to_nat_pos : ∀ n : pos_num, (n : ℕ) > 0 | 1 := dec_trivial | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem pred'_to_nat : ∀ n, (option.cases_on (pred' n) ((n : ℕ) = 1) (λm, (m : ℕ) = nat.pred n) : Prop) | 1 := rfl | (pos_num.bit1 q) := rfl | (pos_num.bit0 q) := suffices _ → ((option.cases_on (pred' q) 1 bit1 : pos_num) : ℕ) = nat.pred (bit0 q), from this (pred'_to_nat q), match pred' q with | none, (IH : (q : ℕ) = 1) := show 1 = nat.pred (q + q), by rw IH; refl | some p, (IH : ↑p = nat.pred q) := show _root_.bit1 ↑p = nat.pred (q + q), begin rw [←nat.succ_pred_eq_of_pos (to_nat_pos q), IH], generalize (nat.pred q) n, intro n, simp [_root_.bit1, _root_.bit0] end end theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] end pos_num namespace num open pos_num theorem zero_to_nat : ((0 : num) : ℕ) = 0 := rfl theorem one_to_nat : ((1 : num) : ℕ) = 1 := rfl theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := rfl | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := rfl | (n+1) := (succ_to_nat (num.of_nat n)).trans (congr_arg nat.succ (to_of_nat n)) theorem of_nat_inj : ∀ {m n : ℕ}, (m : num) = n → m = n := function.injective_of_left_inverse to_of_nat theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n | 0 := (add_zero _).symm | (n+1) := show succ (m + n : ℕ) = m + succ n, by rw [add_succ, add_of_nat] theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ end num namespace pos_num open num @[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = pos n | 1 := rfl | (bit0 p) := show ↑(p + p : ℕ) = pos (bit0 p), by rw [add_of_nat, of_to_nat]; exact congr_arg pos p.bit0_of_bit0 | (bit1 p) := show num.succ (p + p : ℕ) = pos (bit1 p), by rw [add_of_nat, of_to_nat]; exact congr_arg (num.pos ∘ succ) p.bit0_of_bit0 theorem to_nat_inj {m n : pos_num} (h : (m : ℕ) = n) : m = n := by have := congr_arg (coe : ℕ → num) h; simp at this; injection this theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, revert this, cases pred' n; dsimp [option.get_or_else], { intro this, rw @to_nat_inj n 1 this at h, exact absurd h dec_trivial }, { exact id } end theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl lemma cmp_dec_lemma {m n} : m < n → bit1 m < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_dec : ∀ (m n), (ordering.cases_on (cmp m n) (m < n) (m = n) (m > n) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_dec a b, revert this, cases cmp a b; dsimp; intro, { exact @add_lt_add nat _ _ _ _ _ this this }, { rw this }, { exact @add_lt_add nat _ _ _ _ _ this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_dec a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (@add_lt_add nat _ _ _ _ _ this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_dec_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_dec a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_dec_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (@add_lt_add nat _ _ _ _ _ this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_dec a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := match cmp m n, cmp_dec m n with | ordering.lt, (h : m < n) := ⟨λ_, rfl, λ_, h⟩ | ordering.eq, (h : m = n) := ⟨λh', absurd h' $ by rw h; apply @lt_irrefl nat, dec_trivial⟩ | ordering.gt, (h : m > n) := ⟨λh', absurd h' $ @not_lt_of_gt nat _ _ _ h, dec_trivial⟩ end theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := iff.trans ⟨@not_lt_of_ge nat _ _ _, le_of_not_gt⟩ $ not_congr $ lt_iff_cmp.trans $ by rw ←cmp_swap; cases cmp m n; exact dec_trivial instance decidable_lt : @decidable_rel pos_num (<) := λ m n, decidable_of_decidable_of_iff (by apply_instance) lt_iff_cmp.symm instance decidable_le : @decidable_rel pos_num (≤) := λ m n, decidable_of_decidable_of_iff (by apply_instance) le_iff_cmp.symm meta def transfer_rw : tactic unit := `[repeat {rw add_to_nat <|> rw mul_to_nat <|> rw one_to_nat <|> rw zero_to_nat}] meta def transfer : tactic unit := `[intros, apply to_nat_inj, transfer_rw, try {simp}] instance : add_comm_semigroup pos_num := { add := (+), add_assoc := by transfer, add_comm := by transfer } instance : comm_monoid pos_num := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, mul_comm := by transfer } instance : distrib pos_num := { add := (+), mul := (*), left_distrib := by {transfer, simp [left_distrib]}, right_distrib := by {transfer, simp [left_distrib]} } -- TODO(Mario): Prove these using transfer tactic instance : decidable_linear_order pos_num := { lt := (<), le := (≤), le_refl := λa, @le_refl nat _ _, le_trans := λa b c, @le_trans nat _ _ _ _, le_antisymm := λa b h1 h2, to_nat_inj $ @le_antisymm nat _ _ _ h1 h2, le_total := λa b, @le_total nat _ _ _, le_iff_lt_or_eq := λa b, le_iff_lt_or_eq.trans $ or_congr iff.rfl ⟨to_nat_inj, congr_arg _⟩, lt_irrefl := λ a, @lt_irrefl nat _ _, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } end pos_num namespace num open pos_num @[simp] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n | 0 := rfl | (pos p) := p.of_to_nat theorem to_nat_inj : ∀ {m n : num}, (m : ℕ) = n → m = n := function.injective_of_left_inverse of_to_nat theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := suffices _ → ↑(option.cases_on (pred' p) 0 pos : num) = nat.pred p, from this (pred'_to_nat p), by { cases pred' p; dsimp [option.get_or_else]; intro h, rw h; refl, exact h } theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_dec : ∀ (m n), (ordering.cases_on (cmp m n) (m < n) (m = n) (m > n) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_dec a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := match cmp m n, cmp_dec m n with | ordering.lt, (h : m < n) := ⟨λ_, rfl, λ_, h⟩ | ordering.eq, (h : m = n) := ⟨λh', absurd h' $ by rw h; apply @lt_irrefl nat, dec_trivial⟩ | ordering.gt, (h : m > n) := ⟨λh', absurd h' $ @not_lt_of_gt nat _ _ _ h, dec_trivial⟩ end theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := iff.trans ⟨@not_lt_of_ge nat _ _ _, le_of_not_gt⟩ $ not_congr $ lt_iff_cmp.trans $ by rw ←cmp_swap; cases cmp m n; exact dec_trivial instance decidable_lt : @decidable_rel num (<) := λ m n, decidable_of_decidable_of_iff (by apply_instance) lt_iff_cmp.symm instance decidable_le : @decidable_rel num (≤) := λ m n, decidable_of_decidable_of_iff (by apply_instance) le_iff_cmp.symm meta def transfer_rw : tactic unit := `[repeat {rw add_to_nat <|> rw mul_to_nat <|> rw one_to_nat <|> rw zero_to_nat}] meta def transfer : tactic unit := `[intros, apply to_nat_inj, transfer_rw, try {simp}] instance : comm_semiring num := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [left_distrib]}, right_distrib := by {transfer, simp [left_distrib]}, zero_mul := by transfer, mul_zero := by transfer, mul_comm := by transfer } instance : decidable_linear_ordered_semiring num := { num.comm_semiring with add_left_cancel := λ a b c h, by { apply to_nat_inj, have := congr_arg (coe : num → nat) h, revert this, transfer_rw, apply add_left_cancel }, add_right_cancel := λ a b c h, by { apply to_nat_inj, have := congr_arg (coe : num → nat) h, revert this, transfer_rw, apply add_right_cancel }, lt := (<), le := (≤), le_refl := λa, @le_refl nat _ _, le_trans := λa b c, @le_trans nat _ _ _ _, le_antisymm := λa b h1 h2, to_nat_inj $ @le_antisymm nat _ _ _ h1 h2, le_total := λa b, @le_total nat _ _ _, le_iff_lt_or_eq := λa b, le_iff_lt_or_eq.trans $ or_congr iff.rfl ⟨to_nat_inj, congr_arg _⟩, le_of_lt := λa b, @le_of_lt nat _ _ _, lt_irrefl := λa, @lt_irrefl nat _ _, lt_of_lt_of_le := λa b c, @lt_of_lt_of_le nat _ _ _ _, lt_of_le_of_lt := λa b c, @lt_of_le_of_lt nat _ _ _ _, lt_of_add_lt_add_left := λa b c, show (_:ℕ)<_→(_:ℕ)<_, by {transfer_rw, apply lt_of_add_lt_add_left}, add_lt_add_left := λa b h c, show (_:ℕ)<_, by {transfer_rw, apply @add_lt_add_left nat _ _ _ h}, add_le_add_left := λa b h c, show (_:ℕ)≤_, by {transfer_rw, apply @add_le_add_left nat _ _ _ h}, le_of_add_le_add_left := λa b c, show (_:ℕ)≤_→(_:ℕ)≤_, by {transfer_rw, apply le_of_add_le_add_left}, zero_lt_one := dec_trivial, mul_le_mul_of_nonneg_left := λa b c h _, show (_:ℕ)≤_, by {transfer_rw, apply nat.mul_le_mul_left _ h}, mul_le_mul_of_nonneg_right := λa b c h _, show (_:ℕ)≤_, by {transfer_rw, apply nat.mul_le_mul_right _ h}, mul_lt_mul_of_pos_left := λa b c h₁ h₂, show (_:ℕ)<_, by {transfer_rw, apply nat.mul_lt_mul_of_pos_left h₁ h₂}, mul_lt_mul_of_pos_right := λa b c h₁ h₂, show (_:ℕ)<_, by {transfer_rw, apply nat.mul_lt_mul_of_pos_right h₁ h₂}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq } lemma bitwise_to_nat_lemma {f : num → num → num} (m n) : (f m n : ℕ) = (f ((m : ℕ) : num) ((n : ℕ) : num) : ℕ) := by simp /- TODO(Jeremy): I commented these out to get library_dev to compile. Mario, should we delete them? @[simp] lemma lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := bitwise_to_nat_lemma @[simp] lemma land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := bitwise_to_nat_lemma @[simp] lemma ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := bitwise_to_nat_lemma @[simp] lemma lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := bitwise_to_nat_lemma @[simp] lemma shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := by unfold nat.shiftl; simp @[simp] lemma shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := by unfold nat.shiftr; simp -/ end num
5860cca2b9c20cb0953b65dfd9bf8a81d4c8f6e9
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/bv.lean
3c23b85eea24833d9aef45a1c20caeed8c576e08
[ "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
5,087
lean
/- Copyright (c) 2015 Joe Hendrix. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joe Hendrix Basic operations on bitvectors. This is a work-in-progress, and contains additions to other theories. -/ import data.list import data.tuple namespace bv open bool open eq.ops open list open nat open prod open subtype open tuple attribute [reducible] definition bv (n : ℕ) := tuple bool n -- Create a zero bitvector definition bv_zero (n : ℕ) : bv n := replicate ff -- Create a bitvector with the constant one. definition bv_one : Π (n : ℕ), bv n | 0 := replicate ff | (succ n) := (replicate ff : bv n) ++ (tt :: nil) definition bv_cong {a b : ℕ} : (a = b) → bv a → bv b | c (tag x p) := tag x (c ▸ p) section shift -- shift left definition bv_shl {n:ℕ} : bv n → ℕ → bv n | x i := if le : i ≤ n then let r := dropn i x ++ replicate ff in let eq := calc (n-i) + i = n : nat.sub_add_cancel le in bv_cong eq r else bv_zero n -- unsigned shift right definition bv_ushr {n:ℕ} : bv n → ℕ → bv n | x i := if le : i ≤ n then let y : bv (n-i) := @firstn _ _ (n - i) (sub_le n i) x in let eq := calc (i+(n-i)) = (n - i) + i : add.comm ... = n : nat.sub_add_cancel le in bv_cong eq (replicate ff ++ y) else bv_zero n -- signed shift right definition bv_sshr {m:ℕ} : bv (succ m) → ℕ → bv (succ m) | x i := let n := succ m in if le : i ≤ n then let z : bv i := replicate (head x) in let y : bv (n-i) := @firstn _ _ (n - i) (sub_le n i) x in let eq := calc (i+(n-i)) = (n-i) + i : add.comm ... = n : nat.sub_add_cancel le in bv_cong eq (z ++ y) else bv_zero n end shift section bitwise variable { n : ℕ } definition bv_not : bv n → bv n := map bnot definition bv_and : bv n → bv n → bv n := map₂ band definition bv_or : bv n → bv n → bv n := map₂ bor definition bv_xor : bv n → bv n → bv n := map₂ bxor end bitwise section arith variable { n : ℕ } protected definition xor3 (x:bool) (y:bool) (c:bool) := bxor (bxor x y) c protected definition carry (x:bool) (y:bool) (c:bool) := x && y || x && c || y && c definition bv_neg : bv n → bv n | x := let f := λy c, (y || c, bxor y c) in pr₂ (mapAccumR f x ff) -- Add with carry (no overflow) definition bv_adc : bv n → bv n → bool → bv (n+1) | x y c := let f := λx y c, (bv.carry x y c, bv.xor3 x y c) in let z := tuple.mapAccumR₂ f x y c in (pr₁ z) :: (pr₂ z) definition bv_add : bv n → bv n → bv n | x y := tail (bv_adc x y ff) protected definition borrow (x:bool) (y:bool) (b:bool) := bnot x && y || bnot x && b || y && b -- Subtract with borrow definition bv_sbb : bv n → bv n → bool → bool × bv n | x y b := let f := λx y c, (bv.borrow x y c, bv.xor3 x y c) in tuple.mapAccumR₂ f x y b definition bv_sub : bv n → bv n → bv n | x y := pr₂ (bv_sbb x y ff) attribute [instance] definition bv_has_zero : has_zero (bv n) := has_zero.mk (bv_zero n) attribute [instance] definition bv_has_one : has_one (bv n) := has_one.mk (bv_one n) attribute [instance] definition bv_has_add : has_add (bv n) := has_add.mk bv_add attribute [instance] definition bv_has_sub : has_sub (bv n) := has_sub.mk bv_sub attribute [instance] definition bv_has_neg : has_neg (bv n) := has_neg.mk bv_neg definition bv_mul : bv n → bv n → bv n | x y := let f := λr b, cond b (r + r + y) (r + r) in foldl f 0 (to_list x) attribute [instance] definition bv_has_mul : has_mul (bv n) := has_mul.mk bv_mul definition bv_ult : bv n → bv n → bool := λx y, pr₁ (bv_sbb x y ff) definition bv_ugt : bv n → bv n → bool := λx y, bv_ult y x definition bv_ule : bv n → bv n → bool := λx y, bnot (bv_ult y x) definition bv_uge : bv n → bv n → bool := λx y, bv_ule y x definition bv_slt : bv (succ n) → bv (succ n) → bool := λx y, cond (head x) (cond (head y) (bv_ult (tail x) (tail y)) -- both negative tt) -- x is negative and y is not (cond (head y) ff -- y is negative and x is not (bv_ult (tail x) (tail y))) -- both positive definition bv_sgt : bv (succ n) → bv (succ n) → bool := λx y, bv_slt y x definition bv_sle : bv (succ n) → bv (succ n) → bool := λx y, bnot (bv_slt y x) definition bv_sge : bv (succ n) → bv (succ n) → bool := λx y, bv_sle y x end arith section from_bv variable {A : Type} -- Convert a bitvector to another number. definition from_bv [p : has_add A] [q0 : has_zero A] [q1 : has_one A] {n:nat} (v:bv n) : A := let f := λr b, cond b (r + r + 1) (r + r) in foldl f 0 (to_list v) end from_bv end bv
9ffc2f376735f80e6cf7e40603b9c267aeb3acf7
cb1829c15cd3d28210f93507f96dfb1f56ec0128
/theorem_proving/10-type_classes.lean
41cddc42feff29d3e3200229c569de868237acc6
[]
no_license
williamdemeo/LEAN_wjd
69f9f76e35092b89e4479a320be2fa3c18aed6fe
13826c75c06ef435166a26a72e76fe984c15bad7
refs/heads/master
1,609,516,630,137
1,518,123,893,000
1,518,123,893,000
97,740,278
2
0
null
null
null
null
UTF-8
Lean
false
false
917
lean
-- 10. Type Classes #print "===========================================" #print "Section 10.1. Type Classes and Instances" #print " " namespace Sec_10_1 end Sec_10_1 #print "===========================================" #print "Section 10.2. Chaining Instances" #print " " namespace Sec_10_2 end Sec_10_2 #print "===========================================" #print "Section 10.3. Decidable Propositions" #print " " namespace Sec_10_3 end Sec_10_3 #print "===========================================" #print "Section 10.4. Overloading with Type Classes" #print " " namespace Sec_10_4 end Sec_10_4 #print "===========================================" #print "Section 10.5. Managing Type Class Inference" #print " " namespace Sec_10_5 end Sec_10_5 #print "===========================================" #print "Section 10.6. Coercions using Type Classes" #print " " namespace Sec_10_6 end Sec_10_6
b734a6d01a693cb6b6c15351d3d19664fa133dc8
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/with_attrs1.lean
c535f1d31019cb65e376b72ea792662e04a00d59
[ "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
321
lean
import data.nat open nat constants f : nat → nat → nat axiom f_ax : ∀ a b, f a b = f b a example (a b : nat) : f a b = f b a := begin with_attrs f_ax [simp] simp end definition g (a : nat) := f a 1 example (a : nat) : g a = f 1 a := begin with_attributes g [reducible] with_attributes f_ax [simp] simp end
f6aff25a3a075d208b9997c641f1660ab71cf19b
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/algebra/group.lean
2f95b6f4e1fdadf23c2bdb2cc79efbd1b8ac766a
[ "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
15,740
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.logic init.algebra.ac init.meta init.meta.decl_cmds init.meta.smt.rsimp /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe u variables {α : Type u} class semigroup (α : Type u) extends has_mul α := (mul_assoc : ∀ a b c : α, a * b * c = a * (b * c)) class comm_semigroup (α : Type u) extends semigroup α := (mul_comm : ∀ a b : α, a * b = b * a) class left_cancel_semigroup (α : Type u) extends semigroup α := (mul_left_cancel : ∀ a b c : α, a * b = a * c → b = c) class right_cancel_semigroup (α : Type u) extends semigroup α := (mul_right_cancel : ∀ a b c : α, a * b = c * b → a = c) class monoid (α : Type u) extends semigroup α, has_one α := (one_mul : ∀ a : α, 1 * a = a) (mul_one : ∀ a : α, a * 1 = a) class comm_monoid (α : Type u) extends monoid α, comm_semigroup α class group (α : Type u) extends monoid α, has_inv α := (mul_left_inv : ∀ a : α, a⁻¹ * a = 1) class comm_group (α : Type u) extends group α, comm_monoid α @[simp] lemma mul_assoc [semigroup α] : ∀ a b c : α, a * b * c = a * (b * c) := semigroup.mul_assoc instance semigroup_to_is_associative [semigroup α] : is_associative α mul := ⟨mul_assoc⟩ @[simp] lemma mul_comm [comm_semigroup α] : ∀ a b : α, a * b = b * a := comm_semigroup.mul_comm instance comm_semigroup_to_is_commutative [comm_semigroup α] : is_commutative α mul := ⟨mul_comm⟩ @[simp] lemma mul_left_comm [comm_semigroup α] : ∀ a b c : α, a * (b * c) = b * (a * c) := left_comm mul mul_comm mul_assoc lemma mul_left_cancel [left_cancel_semigroup α] {a b c : α} : a * b = a * c → b = c := left_cancel_semigroup.mul_left_cancel a b c lemma mul_right_cancel [right_cancel_semigroup α] {a b c : α} : a * b = c * b → a = c := right_cancel_semigroup.mul_right_cancel a b c lemma mul_left_cancel_iff [left_cancel_semigroup α] {a b c : α} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ lemma mul_right_cancel_iff [right_cancel_semigroup α] {a b c : α} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ @[simp] lemma one_mul [monoid α] : ∀ a : α, 1 * a = a := monoid.one_mul @[simp] lemma mul_one [monoid α] : ∀ a : α, a * 1 = a := monoid.mul_one @[simp] lemma mul_left_inv [group α] : ∀ a : α, a⁻¹ * a = 1 := group.mul_left_inv def inv_mul_self := @mul_left_inv @[simp] lemma inv_mul_cancel_left [group α] (a b : α) : a⁻¹ * (a * b) = b := by rw [-mul_assoc, mul_left_inv, one_mul] @[simp] lemma inv_mul_cancel_right [group α] (a b : α) : a * b⁻¹ * b = a := by simp @[simp] lemma inv_eq_of_mul_eq_one [group α] {a b : α} (h : a * b = 1) : a⁻¹ = b := by rw [-mul_one a⁻¹, -h, -mul_assoc, mul_left_inv, one_mul] @[simp] lemma one_inv [group α] : 1⁻¹ = (1 : α) := inv_eq_of_mul_eq_one (one_mul 1) @[simp] lemma inv_inv [group α] (a : α) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul_left_inv a) @[simp] lemma mul_right_inv [group α] (a : α) : a * a⁻¹ = 1 := have a⁻¹⁻¹ * a⁻¹ = 1, by rw mul_left_inv, by rwa [inv_inv] at this def mul_inv_self := @mul_right_inv lemma inv_inj [group α] {a b : α} (h : a⁻¹ = b⁻¹) : a = b := have a = a⁻¹⁻¹, by simp, begin rw this, simp [h] end lemma group.mul_left_cancel [group α] {a b c : α} (h : a * b = a * c) : b = c := have a⁻¹ * (a * b) = b, by simp, begin simp [h] at this, rw this end lemma group.mul_right_cancel [group α] {a b c : α} (h : a * b = c * b) : a = c := have a * b * b⁻¹ = a, by simp, begin simp [h] at this, rw this end instance group.to_left_cancel_semigroup [s : group α] : left_cancel_semigroup α := { s with mul_left_cancel := @group.mul_left_cancel α s } instance group.to_right_cancel_semigroup [s : group α] : right_cancel_semigroup α := { s with mul_right_cancel := @group.mul_right_cancel α s } lemma mul_inv_cancel_left [group α] (a b : α) : a * (a⁻¹ * b) = b := by rw [-mul_assoc, mul_right_inv, one_mul] lemma mul_inv_cancel_right [group α] (a b : α) : a * b * b⁻¹ = a := by rw [mul_assoc, mul_right_inv, mul_one] @[simp] lemma mul_inv_rev [group α] (a b : α) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := inv_eq_of_mul_eq_one begin rw [mul_assoc, -mul_assoc b, mul_right_inv, one_mul, mul_right_inv] end lemma eq_inv_of_eq_inv [group α] {a b : α} (h : a = b⁻¹) : b = a⁻¹ := by simp [h] lemma eq_inv_of_mul_eq_one [group α] {a b : α} (h : a * b = 1) : a = b⁻¹ := have a⁻¹ = b, from inv_eq_of_mul_eq_one h, by simp [this^.symm] lemma eq_mul_inv_of_mul_eq [group α] {a b c : α} (h : a * c = b) : a = b * c⁻¹ := by simp [h^.symm] lemma eq_inv_mul_of_mul_eq [group α] {a b c : α} (h : b * a = c) : a = b⁻¹ * c := by simp [h^.symm] lemma inv_mul_eq_of_eq_mul [group α] {a b c : α} (h : b = a * c) : a⁻¹ * b = c := by simp [h] lemma mul_inv_eq_of_eq_mul [group α] {a b c : α} (h : a = c * b) : a * b⁻¹ = c := by simp [h] lemma eq_mul_of_mul_inv_eq [group α] {a b c : α} (h : a * c⁻¹ = b) : a = b * c := by simp [h^.symm] lemma eq_mul_of_inv_mul_eq [group α] {a b c : α} (h : b⁻¹ * a = c) : a = b * c := by simp [h^.symm, mul_inv_cancel_left] lemma mul_eq_of_eq_inv_mul [group α] {a b c : α} (h : b = a⁻¹ * c) : a * b = c := by rw [h, mul_inv_cancel_left] lemma mul_eq_of_eq_mul_inv [group α] {a b c : α} (h : a = c * b⁻¹) : a * b = c := by simp [h] lemma mul_inv [comm_group α] (a b : α) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by rw [mul_inv_rev, mul_comm] /- αdditive "sister" structures. Example, add_semigroup mirrors semigroup. These structures exist just to help automation. In an alternative design, we could have the binary operation as an extra argument for semigroup, monoid, group, etc. However, the lemmas would be hard to index since they would not contain any constant. For example, mul_assoc would be lemma mul_assoc {α : Type u} {op : α → α → α} [semigroup α op] : ∀ a b c : α, op (op a b) c = op a (op b c) := semigroup.mul_assoc The simplifier cannot effectively use this lemma since the pattern for the left-hand-side would be ?op (?op ?a ?b) ?c Remark: we use a tactic for transporting theorems from the multiplicative fragment to the additive one. -/ class add_semigroup (α : Type u) extends has_add α := (add_assoc : ∀ a b c : α, a + b + c = a + (b + c)) class add_comm_semigroup (α : Type u) extends add_semigroup α := (add_comm : ∀ a b : α, a + b = b + a) class add_left_cancel_semigroup (α : Type u) extends add_semigroup α := (add_left_cancel : ∀ a b c : α, a + b = a + c → b = c) class add_right_cancel_semigroup (α : Type u) extends add_semigroup α := (add_right_cancel : ∀ a b c : α, a + b = c + b → a = c) class add_monoid (α : Type u) extends add_semigroup α, has_zero α := (zero_add : ∀ a : α, 0 + a = a) (add_zero : ∀ a : α, a + 0 = a) class add_comm_monoid (α : Type u) extends add_monoid α, add_comm_semigroup α class add_group (α : Type u) extends add_monoid α, has_neg α := (add_left_neg : ∀ a : α, -a + a = 0) class add_comm_group (α : Type u) extends add_group α, add_comm_monoid α open tactic meta def transport_with_dict (dict : name_map name) (src : name) (tgt : name) : command := copy_decl_using dict src tgt >> copy_attribute `reducible src tt tgt >> copy_attribute `simp src tt tgt >> copy_attribute `instance src tt tgt meta def multiplicative_to_additive_pairs : list (name × name) := [/- map operations -/ (`mul, `add), (`one, `zero), (`inv, `neg), (`has_mul, `has_add), (`has_one, `has_zero), (`has_inv, `has_neg), /- map constructors -/ (`has_mul.mk, `has_add.mk), (`has_one, `has_zero.mk), (`has_inv, `has_neg.mk), /- map structures -/ (`semigroup, `add_semigroup), (`monoid, `add_monoid), (`group, `add_group), (`comm_semigroup, `add_comm_semigroup), (`comm_monoid, `add_comm_monoid), (`comm_group, `add_comm_group), (`left_cancel_semigroup, `add_left_cancel_semigroup), (`right_cancel_semigroup, `add_right_cancel_semigroup), (`left_cancel_semigroup.mk, `add_left_cancel_semigroup.mk), (`right_cancel_semigroup.mk, `add_right_cancel_semigroup.mk), /- map instances -/ (`semigroup.to_has_mul, `add_semigroup.to_has_add), (`monoid.to_has_one, `add_monoid.to_has_zero), (`group.to_has_inv, `add_group.to_has_neg), (`comm_semigroup.to_semigroup, `add_comm_semigroup.to_add_semigroup), (`monoid.to_semigroup, `add_monoid.to_add_semigroup), (`comm_monoid.to_monoid, `add_comm_monoid.to_add_monoid), (`comm_monoid.to_comm_semigroup, `add_comm_monoid.to_add_comm_semigroup), (`group.to_monoid, `add_group.to_add_monoid), (`comm_group.to_group, `add_comm_group.to_add_group), (`comm_group.to_comm_monoid, `add_comm_group.to_add_comm_monoid), (`left_cancel_semigroup.to_semigroup, `add_left_cancel_semigroup.to_add_semigroup), (`right_cancel_semigroup.to_semigroup, `add_right_cancel_semigroup.to_add_semigroup), /- map projections -/ (`semigroup.mul_assoc, `add_semigroup.add_assoc), (`comm_semigroup.mul_comm, `add_comm_semigroup.add_comm), (`left_cancel_semigroup.mul_left_cancel, `add_left_cancel_semigroup.add_left_cancel), (`right_cancel_semigroup.mul_right_cancel, `add_right_cancel_semigroup.add_right_cancel), (`monoid.one_mul, `add_monoid.zero_add), (`monoid.mul_one, `add_monoid.add_zero), (`group.mul_left_inv, `add_group.add_left_neg), (`group.mul, `add_group.add), (`group.mul_assoc, `add_group.add_assoc), /- map lemmas -/ (`mul_assoc, `add_assoc), (`mul_comm, `add_comm), (`mul_left_comm, `add_left_comm), (`one_mul, `zero_add), (`mul_one, `add_zero), (`mul_left_inv, `add_left_neg), (`mul_left_cancel, `add_left_cancel), (`mul_right_cancel, `add_right_cancel), (`mul_left_cancel_iff, `add_left_cancel_iff), (`mul_right_cancel_iff, `add_right_cancel_iff), (`inv_mul_cancel_left, `neg_add_cancel_left), (`inv_mul_cancel_right, `neg_add_cancel_right), (`eq_inv_mul_of_mul_eq, `eq_neg_add_of_add_eq), (`inv_eq_of_mul_eq_one, `neg_eq_of_add_eq_zero), (`inv_inv, `neg_neg), (`mul_right_inv, `add_right_neg), (`mul_inv_cancel_left, `add_neg_cancel_left), (`mul_inv_cancel_right, `add_neg_cancel_right), (`mul_inv_rev, `neg_add_rev), (`mul_inv, `neg_add), (`inv_inj, `neg_inj), (`group.mul_left_cancel, `add_group.add_left_cancel), (`group.mul_right_cancel, `add_group.add_right_cancel), (`group.to_left_cancel_semigroup, `add_group.to_left_cancel_add_semigroup), (`group.to_right_cancel_semigroup, `add_group.to_right_cancel_add_semigroup), (`eq_inv_of_eq_inv, `eq_neg_of_eq_neg), (`eq_inv_of_mul_eq_one, `eq_neg_of_add_eq_zero), (`eq_mul_inv_of_mul_eq, `eq_add_neg_of_add_eq), (`inv_mul_eq_of_eq_mul, `neg_add_eq_of_eq_add), (`mul_inv_eq_of_eq_mul, `add_neg_eq_of_eq_add), (`eq_mul_of_mul_inv_eq, `eq_add_of_add_neg_eq), (`eq_mul_of_inv_mul_eq, `eq_add_of_neg_add_eq), (`mul_eq_of_eq_inv_mul, `add_eq_of_eq_neg_add), (`mul_eq_of_eq_mul_inv, `add_eq_of_eq_add_neg), (`one_inv, `neg_zero) ] /- Transport multiplicative to additive -/ meta def transport_multiplicative_to_additive : command := let dict := rb_map.of_list multiplicative_to_additive_pairs in multiplicative_to_additive_pairs^.foldl (λ t ⟨src, tgt⟩, do env ← get_env, if (env^.get tgt)^.to_bool = ff then t >> transport_with_dict dict src tgt else t) skip run_cmd transport_multiplicative_to_additive instance add_semigroup_to_is_eq_associative [add_semigroup α] : is_associative α add := ⟨add_assoc⟩ instance add_comm_semigroup_to_is_eq_commutative [add_comm_semigroup α] : is_commutative α add := ⟨add_comm⟩ def neg_add_self := @add_left_neg def add_neg_self := @add_right_neg def eq_of_add_eq_add_left := @add_left_cancel def eq_of_add_eq_add_right := @add_right_cancel @[reducible] protected def algebra.sub [add_group α] (a b : α) : α := a + -b instance add_group_has_sub [add_group α] : has_sub α := ⟨algebra.sub⟩ @[simp] lemma sub_eq_add_neg [add_group α] (a b : α) : a - b = a + -b := rfl lemma sub_self [add_group α] (a : α) : a - a = 0 := add_right_neg a lemma sub_add_cancel [add_group α] (a b : α) : a - b + b = a := neg_add_cancel_right a b lemma add_sub_cancel [add_group α] (a b : α) : a + b - b = a := add_neg_cancel_right a b lemma add_sub_assoc [add_group α] (a b c : α) : a + b - c = a + (b - c) := by rw [sub_eq_add_neg, add_assoc, -sub_eq_add_neg] lemma eq_of_sub_eq_zero [add_group α] {a b : α} (h : a - b = 0) : a = b := have 0 + b = b, by rw zero_add, have (a - b) + b = b, by rwa h, by rwa [sub_eq_add_neg, neg_add_cancel_right] at this lemma sub_eq_zero_of_eq [add_group α] {a b : α} (h : a = b) : a - b = 0 := by rw [h, sub_self] lemma zero_sub [add_group α] (a : α) : 0 - a = -a := zero_add (-a) lemma sub_zero [add_group α] (a : α) : a - 0 = a := by rw [sub_eq_add_neg, neg_zero, add_zero] lemma sub_ne_zero_of_ne [add_group α] {a b : α} (h : a ≠ b) : a - b ≠ 0 := begin intro hab, apply h, apply eq_of_sub_eq_zero hab end lemma sub_neg_eq_add [add_group α] (a b : α) : a - (-b) = a + b := by rw [sub_eq_add_neg, neg_neg] lemma neg_sub [add_group α] (a b : α) : -(a - b) = b - a := neg_eq_of_add_eq_zero (by rw [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, add_right_neg]) lemma add_sub [add_group α] (a b c : α) : a + (b - c) = a + b - c := by simp lemma sub_add_eq_sub_sub_swap [add_group α] (a b c : α) : a - (b + c) = a - c - b := by simp lemma eq_sub_of_add_eq [add_group α] {a b c : α} (h : a + c = b) : a = b - c := by simp [h^.symm] lemma sub_eq_of_eq_add [add_group α] {a b c : α} (h : a = c + b) : a - b = c := by simp [h] lemma eq_add_of_sub_eq [add_group α] {a b c : α} (h : a - c = b) : a = b + c := by simp [h^.symm] lemma add_eq_of_eq_sub [add_group α] {a b c : α} (h : a = c - b) : a + b = c := by simp [h] lemma sub_add_eq_sub_sub [add_comm_group α] (a b c : α) : a - (b + c) = a - b - c := by simp lemma neg_add_eq_sub [add_comm_group α] (a b : α) : -a + b = b - a := by simp lemma sub_add_eq_add_sub [add_comm_group α] (a b c : α) : a - b + c = a + c - b := by simp lemma sub_sub [add_comm_group α] (a b c : α) : a - b - c = a - (b + c) := by simp lemma add_sub_add_left_eq_sub [add_comm_group α] (a b c : α) : (c + a) - (c + b) = a - b := by simp lemma eq_sub_of_add_eq' [add_comm_group α] {a b c : α} (h : c + a = b) : a = b - c := by simp [h^.symm] lemma sub_eq_of_eq_add' [add_comm_group α] {a b c : α} (h : a = b + c) : a - b = c := by simp [h] lemma eq_add_of_sub_eq' [add_comm_group α] {a b c : α} (h : a - b = c) : a = b + c := by simp [h^.symm] lemma add_eq_of_eq_sub' [add_comm_group α] {a b c : α} (h : b = c - a) : a + b = c := begin simp [h], rw [add_comm c, add_neg_cancel_left] end lemma sub_sub_self [add_comm_group α] (a b : α) : a - (a - b) = b := begin simp, rw [add_comm b, add_neg_cancel_left] end lemma add_sub_comm [add_comm_group α] (a b c d : α) : a + b - (c + d) = (a - c) + (b - d) := by simp lemma sub_eq_sub_add_sub [add_comm_group α] (a b c : α) : a - b = c - b + (a - c) := by simp lemma neg_neg_sub_neg [add_comm_group α] (a b : α) : - (-a - -b) = a - b := by simp /- The following lemmas generate too many instances for rsimp -/ attribute [no_rsimp] mul_assoc mul_comm mul_left_comm add_assoc add_comm add_left_comm
f8e3b2fc3ebeb820c374c92c1e1e7a90be4a779b
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Init/Data/Hashable.lean
3a414d6cb66389a34f4705de464c2863e0cf3d95
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
764
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.Data.UInt import Init.Data.String universes u instance : Hashable Nat := { hash := fun n => USize.ofNat n } instance [Hashable α] [Hashable β] : Hashable (α × β) := { hash := fun (a, b) => mixHash (hash a) (hash b) } protected def Option.hash [Hashable α] : Option α → USize | none => 11 | some a => mixHash (hash a) 13 instance [Hashable α] : Hashable (Option α) := { hash := fun | none => 11 | some a => mixHash (hash a) 13 } instance [Hashable α] : Hashable (List α) := { hash := fun as => as.foldl (fun r a => mixHash r (hash a)) 7 }
18df04a273dd14177a43ca8f44f8fe32404137a6
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/order/bounded_lattice.lean
89c097ab4c07913367c975a07619cc95875c51b8
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
50,224
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.option.basic import logic.nontrivial import order.lattice import tactic.pi_instances /-! # ⊤ and ⊥, bounded lattices and variants This file defines top and bottom elements (greatest and least elements) of a type, the bounded variants of different kinds of lattices, sets up the typeclass hierarchy between them and provides instances for `Prop` and `fun`. ## Main declarations * `has_<top/bot> α`: Typeclasses to declare the `⊤`/`⊥` notation. * `order_<top/bot> α`: Order with a top/bottom element. * `with_<top/bot> α`: Equips `option α` with the order on `α` plus `none` as the top/bottom element. * `semilattice_<sup/inf>_<top/bot>`: Semilattice with a join/meet and a top/bottom element (all four combinations). Typical examples include `ℕ`. * `bounded_lattice α`: Lattice with a top and bottom element. * `distrib_lattice_bot α`: Distributive lattice with a bottom element. It captures the properties of `disjoint` that are common to `generalized_boolean_algebra` and `bounded_distrib_lattice`. * `bounded_distrib_lattice α`: Bounded and distributive lattice. Typical examples include `Prop` and `set α`. * `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a non distributive lattice, an element can have several complements. * `is_complemented α`: Typeclass stating that any element of a lattice has a complement. ## Implementation notes We didn't define `distrib_lattice_top` because the dual notion of `disjoint` isn't really used anywhere. -/ /-! ### Top, bottom element -/ set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ @[notation_class] class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ @[notation_class] class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot @[priority 100] instance has_top_nonempty (α : Type u) [has_top α] : nonempty α := ⟨⊤⟩ @[priority 100] instance has_bot_nonempty (α : Type u) [has_bot α] : nonempty α := ⟨⊥⟩ attribute [pattern] has_bot.bot has_top.top /-- An `order_top` is a partial order with a greatest element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_top.antisymm h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨λ eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := λ h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := le_top.lt_iff_ne lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := λ ha, hb $ top_unique $ ha ▸ hab lemma eq_top_of_maximal (h : ∀ b, ¬ a < b) : a = ⊤ := or.elim (lt_or_eq_of_le le_top) (λ hlt, absurd hlt (h ⊤)) (λ he, he) lemma ne.lt_top (h : a ≠ ⊤) : a < ⊤ := lt_top_iff_ne_top.mpr h lemma ne.lt_top' (h : ⊤ ≠ a) : a < ⊤ := h.symm.lt_top end order_top lemma strict_mono.top_preimage_top' [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end /-- An `order_bot` is a partial order with a least element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := h.antisymm bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨λ eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, λ h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := λ h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := λ ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp only [lt_iff_le_not_le, not_iff_not.mpr le_bot_iff, true_and, bot_le], end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h lemma eq_bot_of_minimal (h : ∀ b, ¬ b < a) : a = ⊥ := or.elim (lt_or_eq_of_le bot_le) (λ hlt, absurd hlt (h ⊥)) (λ he, he.symm) lemma ne.bot_lt (h : a ≠ ⊥) : ⊥ < a := bot_lt_iff_ne_bot.mpr h lemma ne.bot_lt' (h : ⊥ ≠ a) : ⊥ < a := h.symm.bot_lt end order_bot lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /-! ### Bounded lattice -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := λ x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := λ x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := λ x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := λ x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end /-- A `distrib_lattice_bot` is a distributive lattice with a least element. -/ class distrib_lattice_bot α extends distrib_lattice α, semilattice_inf_bot α, semilattice_sup_bot α /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice_bot α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨λ h, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [h, inf_le_right], λ h, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw inf_comm, exact inf_le_inf_left _ h } ... = ⊥ : h₂⟩ /-- Propositions form a bounded distributive lattice. -/ instance Prop.bounded_distrib_lattice : bounded_distrib_lattice Prop := { le := λ a b, a → b, le_refl := λ _, id, le_trans := λ a b c f g, g ∘ f, le_antisymm := λ a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := λ a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := λ a b c H, or_iff_not_imp_left.2 $ λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩, top := true, le_top := λ a Ha, true.intro, bot := false, bot_le := @false.elim } noncomputable instance Prop.linear_order : linear_order Prop := { le_total := by intros p q; change (p → q) ∨ (q → p); tauto!, decidable_le := classical.dec_rel _, .. (_ : partial_order Prop) } @[simp] lemma le_Prop_eq : ((≤) : Prop → Prop → Prop) = (→) := rfl @[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl @[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λ x, p x ∧ q x) := λ a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λ x, p x ∨ q x) := λ a b h, or.imp (m_p h) (m_q h) end logic instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) := { bot := λ _, ⊥, bot_le := λ x a, bot_le, .. pi.partial_order } /-! ### Function lattices -/ instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) : (⊥ : Π i, α i) i = ⊥ := rfl instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) : (⊤ : Π i, α i) i = ⊤ := rfl instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] : semilattice_sup (Π i, α i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] : semilattice_inf (Π i, α i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] : semilattice_inf_bot (Π i, α i) := by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] : semilattice_inf_top (Π i, α i) := by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] : semilattice_sup_bot (Π i, α i) := by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] : semilattice_sup_top (Π i, α i) := by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance pi.distrib_lattice {ι : Type*} {α : ι → Type*} [Π i, distrib_lattice (α i)] : distrib_lattice (Π i, α i) := by refine_struct { .. pi.lattice }; tactic.pi_instance_derive_field instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] : bounded_lattice (Π i, α i) := { .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot } instance pi.distrib_lattice_bot {ι : Type*} {α : ι → Type*} [Π i, distrib_lattice_bot (α i)] : distrib_lattice_bot (Π i, α i) := { .. pi.distrib_lattice, .. pi.order_bot } instance pi.bounded_distrib_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_distrib_lattice (α i)] : bounded_distrib_lattice (Π i, α i) := { .. pi.bounded_lattice, .. pi.distrib_lattice } lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊥ : α) := eq_bot_mono le_top (eq.symm hα) lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊤ : α) := eq_top_mono bot_le hα lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) : subsingleton α := ⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩ lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) : subsingleton α := subsingleton_of_top_le_bot (ge_of_eq hα) lemma subsingleton_iff_bot_eq_top {α : Type*} [bounded_lattice α] : (⊥ : α) = (⊤ : α) ↔ subsingleton α := ⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩ /-! ### `with_bot`, `with_top` -/ /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl @[simp] theorem bot_ne_coe (a : α) : ⊥ ≠ (a : with_bot α) . @[simp] theorem coe_ne_bot (a : α) : (a : with_bot α) ≠ ⊥ . /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_eliminator] def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) : Π (n : with_bot α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl lemma ne_bot_iff_exists {x : with_bot α} : x ≠ ⊥ ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists /-- Deconstruct a `x : with_bot α` to the underlying value in `α`, given a proof that `x ≠ ⊥`. -/ def unbot : Π (x : with_bot α), x ≠ ⊥ → α | ⊥ h := absurd rfl h | (some x) h := x @[simp] lemma unbot_coe (x : α) (h : (x : with_bot α) ≠ ⊥ := coe_ne_bot _) : (x : with_bot α).unbot h = x := rfl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance : can_lift (with_bot α) α := { coe := coe, cond := λ r, r ≠ ⊥, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [preorder α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h @[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} : a.get_or_else ⊥ ≤ b ↔ a ≤ b := by cases a; simp [none_eq_bot, some_eq_coe] instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤) | none x := is_true $ λ a h, option.no_confusion h | (some x) (some y) := if h : x ≤ y then is_true (some_le_some.2 h) else is_false $ by simp * | (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩ instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance [partial_order α] [is_total α (≤)] : is_total (with_bot α) (≤) := { total := λ a b, match a, b with | none , _ := or.inl bot_le | _ , none := or.inr bot_le | some x, some y := by simp only [some_le_some, total_of] end } instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, decidable_le := with_bot.decidable_le, decidable_lt := with_bot.decidable_lt, ..with_bot.partial_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_bot α) = a ⊔ b := rfl instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_bot α) = a ⊓ b := rfl instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] @[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_bot α) = min x y := by simp [min, ite_cast] @[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_bot α) = max x y := by simp [max, ite_cast] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ λ a b, match a, b with | a, none := λ h : a < ⊥, (not_lt_bot h).elim | none, some b := λ h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_eliminator] def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) : Π (n : with_top α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . lemma ne_top_iff_exists {x : with_top α} : x ≠ ⊤ ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists /-- Deconstruct a `x : with_top α` to the underlying value in `α`, given a proof that `x ≠ ⊤`. -/ def untop : Π (x : with_top α), x ≠ ⊤ → α := with_bot.unbot @[simp] lemma untop_coe (x : α) (h : (x : with_top α) ≠ ⊤ := coe_ne_top) : (x : with_top α).untop h = x := rfl @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem le_none [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem some_lt_none [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance : can_lift (with_top α) α := { coe := coe, cond := λ r, r ≠ ⊤, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none theorem coe_lt_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b) | (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe] | none := by simp [none_eq_top, coe_lt_top] lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := λ h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) := λ x y, @with_bot.decidable_le (order_dual α) _ _ y x instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) := λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x instance [partial_order α] [is_total α (≤)] : is_total (with_top α) (≤) := { total := λ a b, match a, b with | none , _ := or.inr le_top | _ , none := or.inl le_top | some x, some y := by simp only [some_le_some, total_of] end } instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, decidable_le := with_top.decidable_le, decidable_lt := with_top.decidable_lt, ..with_top.partial_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] @[simp, norm_cast] lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_top α) = min x y := by simp [min, ite_cast] @[simp, norm_cast] lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_top α) = max x y := by simp [max, ite_cast] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ λ a b, match a, b with | none, a := λ h : ⊤ < a, (not_top_lt h).elim | some a, none := λ h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top /-! ### Subtype, order dual, product lattices -/ namespace subtype /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a `⊔`-`⊤`-semilattice if `⊤` and `⊔` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_sup_top [semilattice_sup_top α] {P : α → Prop} (Ptop : P ⊤) (Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)) : semilattice_sup_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_inf Pinf } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } /- If you define `distrib_lattice_top`, add the `order_dual` instances between `distrib_lattice_bot` and `distrib_lattice_top` here -/ instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := λ a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := λ a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [distrib_lattice_bot α] [distrib_lattice_bot β] : distrib_lattice_bot (α × β) := { .. prod.distrib_lattice α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod /-! ### Disjointness and complements -/ section disjoint section semilattice_inf_bot variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 lemma symmetric_disjoint : symmetric (disjoint : α → α → Prop) := disjoint.symm @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } lemma disjoint.eq_bot_of_le {a b : α} (hab : disjoint a b) (h : a ≤ b) : a = ⊥ := eq_bot_iff.2 (by rwa ←inf_eq_left.2 h) lemma disjoint.of_disjoint_inf_of_le {a b c : α} (h : disjoint (a ⊓ b) c) (hle : a ≤ c) : disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_left.trans hle)] lemma disjoint.of_disjoint_inf_of_le' {a b c : α} (h : disjoint (a ⊓ b) c) (hle : b ≤ c) : disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_right.trans hle)] end semilattice_inf_bot section bounded_lattice variables [bounded_lattice α] {a : α} @[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff] @[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff] lemma eq_bot_of_disjoint_absorbs {a b : α} (w : disjoint a b) (h : a ⊔ b = a) : b = ⊥ := begin rw disjoint_iff at w, rw [←w, right_eq_inf], rwa sup_eq_left at h, end end bounded_lattice section distrib_lattice_bot variables [distrib_lattice_bot α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b := (λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le) lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b := @le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le) ((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left)) end distrib_lattice_bot section semilattice_inf_bot variables [semilattice_inf_bot α] {a b : α} (c : α) lemma disjoint.inf_left (h : disjoint a b) : disjoint (a ⊓ c) b := h.mono_left inf_le_left lemma disjoint.inf_left' (h : disjoint a b) : disjoint (c ⊓ a) b := h.mono_left inf_le_right lemma disjoint.inf_right (h : disjoint a b) : disjoint a (b ⊓ c) := h.mono_right inf_le_left lemma disjoint.inf_right' (h : disjoint a b) : disjoint a (c ⊓ b) := h.mono_right inf_le_right end semilattice_inf_bot end disjoint section is_compl /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := by { rw disjoint_iff, exact h.inf_left_eq_bot_iff } lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := h.disjoint_right_iff.symm lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq section variables [bounded_lattice α] {x : α} lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ := sup_bot_eq.symm.trans h.sup_eq_top lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ := eq_top_of_is_compl_bot h.symm lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ := eq_top_of_is_compl_bot h.to_order_dual lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ := eq_top_of_bot_is_compl h.to_order_dual end /-- A complemented bounded lattice is one where every element has a (not necessarily unique) complement. -/ class is_complemented (α) [bounded_lattice α] : Prop := (exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b) export is_complemented (exists_is_compl) namespace is_complemented variables [bounded_lattice α] [is_complemented α] instance : is_complemented (order_dual α) := ⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.to_order_dual⟩⟩ end is_complemented end is_compl section nontrivial variables [bounded_lattice α] [nontrivial α] lemma bot_ne_top : (⊥ : α) ≠ ⊤ := λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_› lemma top_ne_bot : (⊤ : α) ≠ ⊥ := ne.symm bot_ne_top end nontrivial namespace bool -- Could be generalised to `bounded_distrib_lattice` and `is_complemented` instance : bounded_lattice bool := { top := tt, le_top := λ x, le_tt, bot := ff, bot_le := λ x, ff_le, .. (infer_instance : lattice bool)} end bool section bool @[simp] lemma top_eq_tt : ⊤ = tt := rfl @[simp] lemma bot_eq_ff : ⊥ = ff := rfl end bool
c76d57076928f786188e16bc3835d1196901121e
f3ab5c6b849dd89e43f1fe3572fbed3fc1baaf0f
/lean/nominal.lean
80cad4b570637b07e0dc0830f79785c0bde7f603
[ "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ekmett/coda
69fa7ac66924ea2cee12f7005b192c22baf9e03e
3309ea70c31b58a3915b0ecc9140985c3a1ac565
refs/heads/master
1,670,616,044,398
1,619,020,702,000
1,619,020,702,000
100,850,826
170
15
NOASSERTION
1,670,434,088,000
1,503,220,814,000
Haskell
UTF-8
Lean
false
false
3,990
lean
open function open group -- generally following -- https://www.cl.cam.ac.uk/~amp12/agda/choudhury/choudhury-dissertation.pdf def atom : Type := ℕ def {u} neq {A : Sort u} (a b : A) : Prop := (a = b) → false inductive nelem (a : ℕ) : list ℕ → Prop | nil : nelem [] | cons : Π {b as}, nelem as -> neq a b -> nelem (b :: as) inductive all {A : Type} (P : A → Prop): list A → Prop | nil : all [] | cons : ∀ {a as}, P a → all as → all (a :: as) -- all is a functor from (i -> Prop) to [i] -> Prop def all.map {A : Type} {P Q : A -> Prop} (pq : ∀ {a : A}, P a → Q a) {as : list A} : all P as → all Q as := @all.rec _ P (all Q) (all.nil Q) (λ {a as} p _ qs, all.cons (pq p) qs) as @[pattern] def Z : ℕ := nat.zero @[pattern] def S : ℕ -> ℕ := nat.succ variables a b c: ℕ @[simp] def greater: ℕ := S (max a b) @[simp] def nat_one_add : 1 + a = S a := eq.trans (nat.add_comm 1 a) (nat.add_one a) def max_succ : max (S a) (S b) = S (max a b) := begin refine (eq.subst (nat_one_add a) _), refine (eq.subst (nat_one_add b) _), refine (eq.subst (nat_one_add (max a b)) _), exact (max_add_add_left 1 a b) end def greater_succ : greater (S a) (S b) = S (greater a b) := begin let m : max (S a) (S b) = greater a b := max_succ a b, refine (eq.subst m _), reflexivity, end def greater0 : greater 0 a = S a := begin let m0a : max 0 a = a := max_eq_right (eq.subst (nat.zero_add a) (nat.le_add_right 0 a)), let Sm0a : S (max 0 a) = S a := by cc, exact Sm0a end def greater.comm : greater a b = greater b a := begin let m := max_comm a b, let sm : S (max a b) = S (max b a) := by cc, exact sm end variable as : list ℕ def all_lt (b : ℕ) := all (λ a, a < b) as notation as `≺`:50 b := @all_lt as b def all_lt_le (asb : as ≺ b) (bc : b <= c): as ≺ c := all.map (λ {a} ab, lt_of_lt_of_le ab bc) asb def all_lt_lt (asb : as ≺ b) (bc : b < c): as ≺ c := all.map (λ {a} ab, trans ab bc) asb def lt_greater_left (b c : ℕ): b < greater b c := nat.lt_succ_of_le (le_max_left b c) def lt_greater_right (b c : ℕ): c < greater b c := nat.lt_succ_of_le (le_max_right b c) def outside : list ℕ -> ℕ := list.foldr greater 0 def outside_more : outside as <= outside (a :: as) := begin let m : greater a (outside as) = outside (a :: as) , refl, refine (trans _ (le_of_eq m)), refine (le_of_lt _), exact (lt_greater_right a (outside as)) end def outside_lt : as ≺ outside as := begin introv, induction as, refine (all.nil _), -- nil refine (all.cons _ (all.map _ as_ih)), -- cons calc as_hd < greater as_hd (outside as_tl) : lt_greater_left as_hd (outside as_tl) ... = outside (as_hd :: as_tl) : by refl, intros a ao, exact (lt_of_lt_of_le ao (outside_more as_hd as_tl)) end -- permutations structure perm := (perm: list (ℕ × ℕ)) def swap : ℕ × ℕ → ℕ → ℕ | ⟨a, b⟩ c := if a = c then b else if b = c then a else c def act (p:perm) (n:ℕ) : ℕ := list.foldr swap n p.1 def injective_act (p:perm): injective (act p) := by admit def surjective_act (p:perm): surjective (act p) := by admit -- bijective (act p) -- has_left_inverse (act p) -- has_right_inverse (act p) -- invertible (act p) -- TODO: prove that act is a group homomorphism instance perm_inv : has_inv perm := by apply has_inv.mk; intro a; cases a; exact (perm.mk (list.reverse a)) def reverse.injective {A : Type}: injective (@list.reverse A) := by admit def reverse.surjective {A: Type}: surjective (@list.reverse A) := by admit -- messy, requires actual equality! quotient by permutation equivalence? -- or i can just make my own setoid encoding, blah instance group_perm : group perm := begin apply group.mk, admit, -- inverse proof intros p q; cases p; cases q; exact (perm.mk (p ++ q)), -- cleanup? admit, -- associativity of append exact (perm.mk []), begin intro, admit, end, -- 1*a = a admit, -- a *1 = a exact perm_inv.1, end
c45f81317e4aac47436298fb23d945a26202e8ae
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/comp_val4.lean
bac77f739f0ce6fa7f9b2e10feda99e2cbd568fc
[ "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
323
lean
open tactic example : (1030912003002020:int) ≠ 1021992923928 := by comp_val example : -(1030912003002020:int) ≠ 1021992923928 := by comp_val example : (1030912003002020:int) ≠ -1021992923928 := by comp_val example : -(1030912003002020:int) ≠ 0 := by comp_val example : (0:int) ≠ 1021992923928 := by comp_val
9dd74ecc0670ee63519f2ec66d4ff8a8177c5935
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq3.lean
e773d9be8e17d5a70603d1617beb6911bd3e2f5b
[ "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
266
lean
import data.examples.vector open nat vector definition swap {A : Type} : Π {n}, vector A (succ (succ n)) → vector A (succ (succ n)) | swap (a :: b :: vs) := b :: a :: vs example (n : nat) (a b : num) (v : vector num n) : swap (a :: b :: v) = b :: a :: v := rfl
adcd2c6f32e02fa94a82acf58f8fed772cf49a2d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/fintype/units.lean
de94d0ad60d8c9dcba6a24661827a24e2376c58e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,279
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.prod import data.fintype.sum import data.int.units /-! # fintype instances relating to units > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} instance units_int.fintype : fintype ℤˣ := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ @[simp] lemma units_int.univ : (finset.univ : finset ℤˣ) = {1, -1} := rfl @[simp] theorem fintype.card_units_int : fintype.card ℤˣ = 2 := rfl instance [monoid α] [fintype α] [decidable_eq α] : fintype αˣ := fintype.of_equiv _ (units_equiv_prod_subtype α).symm instance [monoid α] [finite α] : finite αˣ := finite.of_injective _ units.ext lemma fintype.card_units [group_with_zero α] [fintype α] [fintype αˣ] : fintype.card αˣ = fintype.card α - 1 := begin classical, rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : α)⟩), fintype.card_congr (units_equiv_ne_zero α)], have := fintype.card_congr (equiv.sum_compl (= (0 : α))).symm, rwa [fintype.card_sum, add_comm, fintype.card_subtype_eq] at this, end
afa043f24c5763d3121267e1db1561badea99d82
367134ba5a65885e863bdc4507601606690974c1
/src/set_theory/game/nim.lean
1881978d078d99e21353613f63ec5e1d57ada70b
[ "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
15,404
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Markus Himmel -/ import data.nat.bitwise import set_theory.game.impartial import set_theory.ordinal_arithmetic /-! # Nim and the Sprague-Grundy theorem This file contains the definition for nim for any ordinal `O`. In the game of `nim O₁` both players may move to `nim O₂` for any `O₂ < O₁`. We also define a Grundy value for an impartial game `G` and prove the Sprague-Grundy theorem, that `G` is equivalent to `nim (grundy_value G)`. Finally, we compute the sum of finite Grundy numbers: if `G` and `H` have Grundy values `n` and `m`, where `n` and `m` are natural numbers, then `G + H` has the Grundy value `n xor m`. ## Implementation details The pen-and-paper definition of nim defines the possible moves of `nim O` to be `{O' | O' < O}`. However, this definition does not work for us because it would make the type of nim `ordinal.{u} → pgame.{u + 1}`, which would make it impossible for us to state the Sprague-Grundy theorem, since that requires the type of `nim` to be `ordinal.{u} → pgame.{u}`. For this reason, we instead use `O.out.α` for the possible moves, which makes proofs significantly more messy and tedious, but avoids the universe bump. The lemma `nim_def` is somewhat prone to produce "motive is not type correct" errors. If you run into this problem, you may find the lemmas `exists_ordinal_move_left_eq` and `exists_move_left_eq` useful. -/ universes u /-- `ordinal.out` and `ordinal.type_out'` are required to make the definition of nim computable. `ordinal.out` performs the same job as `quotient.out` but is specific to ordinals. -/ def ordinal.out (o : ordinal) : Well_order := ⟨o.out.α, λ x y, o.out.r x y, o.out.wo⟩ /-- This is the same as `ordinal.type_out` but defined to use `ordinal.out`. -/ theorem ordinal.type_out' : ∀ (o : ordinal), ordinal.type (ordinal.out o).r = o := ordinal.type_out /-- The definition of single-heap nim, which can be viewed as a pile of stones where each player can take a positive number of stones from it on their turn. -/ def nim : ordinal → pgame | O₁ := ⟨ O₁.out.α, O₁.out.α, λ O₂, have hwf : (ordinal.typein O₁.out.r O₂) < O₁, from begin nth_rewrite_rhs 0 ←ordinal.type_out' O₁, exact ordinal.typein_lt_type _ _ end, nim (ordinal.typein O₁.out.r O₂), λ O₂, have hwf : (ordinal.typein O₁.out.r O₂) < O₁, from begin nth_rewrite_rhs 0 ←ordinal.type_out' O₁, exact ordinal.typein_lt_type _ _ end, nim (ordinal.typein O₁.out.r O₂)⟩ using_well_founded { dec_tac := tactic.assumption } namespace pgame local infix ` ≈ ` := equiv namespace nim lemma nim_def (O : ordinal) : nim O = pgame.mk O.out.α O.out.α (λ O₂, nim (ordinal.typein O.out.r O₂)) (λ O₂, nim (ordinal.typein O.out.r O₂)) := by rw nim lemma nim_wf_lemma {O₁ : ordinal} (O₂ : O₁.out.α) : (ordinal.typein O₁.out.r O₂) < O₁ := begin nth_rewrite_rhs 0 ← ordinal.type_out O₁, exact ordinal.typein_lt_type _ _ end instance nim_impartial : ∀ (O : ordinal), impartial (nim O) | O := begin rw [impartial_def, nim_def, neg_def], split, split, { rw pgame.le_def, split, { intro i, let hwf : (ordinal.typein O.out.r i) < O := nim_wf_lemma i, exact or.inl ⟨i, (@impartial.neg_equiv_self _ $ nim_impartial $ ordinal.typein O.out.r i).1⟩ }, { intro j, let hwf : (ordinal.typein O.out.r j) < O := nim_wf_lemma j, exact or.inr ⟨j, (@impartial.neg_equiv_self _ $ nim_impartial $ ordinal.typein O.out.r j).1⟩ } }, { rw pgame.le_def, split, { intro i, let hwf : (ordinal.typein O.out.r i) < O := nim_wf_lemma i, exact or.inl ⟨i, (@impartial.neg_equiv_self _ $ nim_impartial $ ordinal.typein O.out.r i).2⟩ }, { intro j, let hwf : (ordinal.typein O.out.r j) < O := nim_wf_lemma j, exact or.inr ⟨j, (@impartial.neg_equiv_self _ $ nim_impartial $ ordinal.typein O.out.r j).2⟩ } }, split, { intro i, let hwf : (ordinal.typein O.out.r i) < O := nim_wf_lemma i, simpa using nim_impartial (ordinal.typein O.out.r i) }, { intro j, let hwf : (ordinal.typein O.out.r j) < O := nim_wf_lemma j, simpa using nim_impartial (ordinal.typein O.out.r j) } end using_well_founded { dec_tac := tactic.assumption } lemma exists_ordinal_move_left_eq (O : ordinal) : ∀ i, ∃ O' < O, (nim O).move_left i = nim O' := by { rw nim_def, exact λ i, ⟨ordinal.typein O.out.r i, ⟨nim_wf_lemma _, rfl⟩⟩ } lemma exists_move_left_eq (O : ordinal) : ∀ O' < O, ∃ i, (nim O).move_left i = nim O' := by { rw nim_def, exact λ _ h, ⟨(ordinal.principal_seg_out h).top, by simp⟩ } lemma zero_first_loses : (nim (0 : ordinal)).first_loses := begin rw [impartial.first_loses_symm, nim_def, le_def_lt], split, { rintro (i : (0 : ordinal).out.α), have h := ordinal.typein_lt_type _ i, rw ordinal.type_out at h, exact false.elim (not_le_of_lt h (ordinal.zero_le (ordinal.typein _ i))) }, { tidy } end lemma non_zero_first_wins (O : ordinal) (hO : O ≠ 0) : (nim O).first_wins := begin rw [impartial.first_wins_symm, nim_def, lt_def_le], rw ←ordinal.pos_iff_ne_zero at hO, exact or.inr ⟨(ordinal.principal_seg_out hO).top, by simpa using zero_first_loses.1⟩ end lemma sum_first_loses_iff_eq (O₁ O₂ : ordinal) : (nim O₁ + nim O₂).first_loses ↔ O₁ = O₂ := begin split, { contrapose, intro h, rw [impartial.not_first_loses], wlog h' : O₁ ≤ O₂ using [O₁ O₂, O₂ O₁], { exact ordinal.le_total O₁ O₂ }, { have h : O₁ < O₂ := lt_of_le_of_ne h' h, rw [impartial.first_wins_symm', lt_def_le, nim_def O₂], refine or.inl ⟨(left_moves_add (nim O₁) _).symm (sum.inr _), _⟩, { exact (ordinal.principal_seg_out h).top }, { simpa using (impartial.add_self (nim O₁)).2 } }, { exact first_wins_of_equiv add_comm_equiv (this (ne.symm h)) } }, { rintro rfl, exact impartial.add_self (nim O₁) } end lemma sum_first_wins_iff_neq (O₁ O₂ : ordinal) : (nim O₁ + nim O₂).first_wins ↔ O₁ ≠ O₂ := by rw [iff_not_comm, impartial.not_first_wins, sum_first_loses_iff_eq] lemma equiv_iff_eq (O₁ O₂ : ordinal) : nim O₁ ≈ nim O₂ ↔ O₁ = O₂ := ⟨λ h, (sum_first_loses_iff_eq _ _).1 $ by rw [first_loses_of_equiv_iff (add_congr h (equiv_refl _)), sum_first_loses_iff_eq], by { rintro rfl, refl }⟩ end nim /-- This definition will be used in the proof of the Sprague-Grundy theorem. It takes a function from some type to ordinals and returns a nonempty set of ordinals with empty intersection with the image of the function. It is guaranteed that the smallest ordinal not in the image will be in the set, i.e. we can use this to find the mex. -/ def nonmoves {α : Type u} (M : α → ordinal.{u}) : set ordinal.{u} := { O : ordinal | ¬ ∃ a : α, M a = O } lemma nonmoves_nonempty {α : Type u} (M : α → ordinal.{u}) : ∃ O : ordinal, O ∈ nonmoves M := begin classical, by_contra h, simp only [nonmoves, not_exists, not_forall, set.mem_set_of_eq, not_not] at h, have hle : cardinal.univ.{u (u+1)} ≤ cardinal.lift.{u (u+1)} (cardinal.mk α), { refine ⟨⟨λ ⟨O⟩, ⟨classical.some (h O)⟩, _⟩⟩, rintros ⟨O₁⟩ ⟨O₂⟩ heq, ext, refine eq.trans (classical.some_spec (h O₁)).symm _, injection heq with heq, rw heq, exact classical.some_spec (h O₂) }, have hlt : cardinal.lift.{u (u+1)} (cardinal.mk α) < cardinal.univ.{u (u+1)} := cardinal.lt_univ.2 ⟨cardinal.mk α, rfl⟩, cases hlt, contradiction end /-- The Grundy value of an impartial game, the ordinal which corresponds to the game of nim that the game is equivalent to -/ noncomputable def grundy_value : Π (G : pgame.{u}) [G.impartial], ordinal.{u} | G := λ hG, by exactI ordinal.omin (nonmoves (λ i, grundy_value (G.move_left i))) (nonmoves_nonempty _) using_well_founded { dec_tac := pgame_wf_tac } lemma grundy_value_def (G : pgame) [G.impartial] : grundy_value G = ordinal.omin (nonmoves (λ i, (grundy_value (G.move_left i)))) (nonmoves_nonempty _) := by { rw grundy_value, refl } /-- The Sprague-Grundy theorem which states that every impartial game is equivalent to a game of nim, namely the game of nim corresponding to the games Grundy value -/ theorem equiv_nim_grundy_value : ∀ (G : pgame.{u}) [G.impartial], by exactI G ≈ nim (grundy_value G) | G := begin classical, introI hG, rw [impartial.equiv_iff_sum_first_loses, ←impartial.no_good_left_moves_iff_first_loses], intro i, equiv_rw left_moves_add G (nim (grundy_value G)) at i, cases i with i₁ i₂, { rw add_move_left_inl, apply first_wins_of_equiv (add_congr (equiv_nim_grundy_value (G.move_left i₁)).symm (equiv_refl _)), rw nim.sum_first_wins_iff_neq, intro heq, rw [eq_comm, grundy_value_def G] at heq, have h := ordinal.omin_mem (nonmoves (λ (i : G.left_moves), grundy_value (G.move_left i))) (nonmoves_nonempty _), rw heq at h, have hcontra : ∃ (i' : G.left_moves), (λ (i'' : G.left_moves), grundy_value (G.move_left i'')) i' = grundy_value (G.move_left i₁) := ⟨i₁, rfl⟩, contradiction }, { rw [add_move_left_inr, ←impartial.good_left_move_iff_first_wins], revert i₂, rw nim.nim_def, intro i₂, have h' : ∃ i : G.left_moves, (grundy_value (G.move_left i)) = ordinal.typein (quotient.out (grundy_value G)).r i₂, { have hlt : ordinal.typein (quotient.out (grundy_value G)).r i₂ < ordinal.type (quotient.out (grundy_value G)).r := ordinal.typein_lt_type _ _, rw ordinal.type_out at hlt, revert i₂ hlt, rw grundy_value_def, intros i₂ hlt, have hnotin : ordinal.typein (quotient.out (ordinal.omin (nonmoves (λ i, grundy_value (G.move_left i))) _)).r i₂ ∉ (nonmoves (λ (i : G.left_moves), grundy_value (G.move_left i))), { intro hin, have hge := ordinal.omin_le hin, have hcontra := (le_not_le_of_lt hlt).2, contradiction }, simpa [nonmoves] using hnotin }, cases h' with i hi, use (left_moves_add _ _).symm (sum.inl i), rw [add_move_left_inl, move_left_mk], apply first_loses_of_equiv (add_congr (equiv_symm (equiv_nim_grundy_value (G.move_left i))) (equiv_refl _)), simpa only [hi] using impartial.add_self (nim (grundy_value (G.move_left i))) } end using_well_founded { dec_tac := pgame_wf_tac } lemma equiv_nim_iff_grundy_value_eq (G : pgame) [G.impartial] (O : ordinal) : G ≈ nim O ↔ grundy_value G = O := ⟨by { intro h, rw ←nim.equiv_iff_eq, exact equiv_trans (equiv_symm (equiv_nim_grundy_value G)) h }, by { rintro rfl, exact equiv_nim_grundy_value G }⟩ lemma nim.grundy_value (O : ordinal.{u}) : grundy_value (nim O) = O := by rw ←equiv_nim_iff_grundy_value_eq lemma equiv_iff_grundy_value_eq (G H : pgame) [G.impartial] [H.impartial] : G ≈ H ↔ grundy_value G = grundy_value H := (equiv_congr_left.1 (equiv_nim_grundy_value H) _).trans $ equiv_nim_iff_grundy_value_eq _ _ lemma grundy_value_zero : grundy_value 0 = 0 := by rw [(equiv_iff_grundy_value_eq 0 (nim 0)).1 (equiv_symm nim.zero_first_loses), nim.grundy_value] lemma equiv_zero_iff_grundy_value (G : pgame) [G.impartial] : G ≈ 0 ↔ grundy_value G = 0 := by rw [equiv_iff_grundy_value_eq, grundy_value_zero] lemma grundy_value_nim_add_nim (n m : ℕ) : grundy_value (nim n + nim m) = nat.lxor n m := begin induction n using nat.strong_induction_on with n hn generalizing m, induction m using nat.strong_induction_on with m hm, rw [grundy_value_def], -- We want to show that `n xor m` is the smallest unreachable Grundy value. We will do this in two -- steps: -- h₀: `n xor m` is not a reachable grundy number. -- h₁: every Grundy number strictly smaller than `n xor m` is reachable. have h₀ : (nat.lxor n m : ordinal) ∈ nonmoves (λ i, grundy_value ((nim n + nim m).move_left i)), { -- To show that `n xor m` is unreachable, we show that every move produces a Grundy number -- different from `n xor m`. simp only [nonmoves, not_exists, set.mem_set_of_eq], equiv_rw left_moves_add _ _, -- The move operates either on the left pile or on the right pile. rintro (a|a), all_goals { -- One of the piles is reduced to `k` stones, with `k < n` or `k < m`. obtain ⟨ok, ⟨hk, hk'⟩⟩ := nim.exists_ordinal_move_left_eq _ a, obtain ⟨k, rfl⟩ := ordinal.lt_omega.1 (lt_trans hk (ordinal.nat_lt_omega _)), replace hk := ordinal.nat_cast_lt.1 hk, -- Thus, the problem is reduced to computing the Grundy value of `nim n + nim k` or -- `nim k + nim m`, both of which can be dealt with using an inductive hypothesis. simp only [hk', add_move_left_inl, add_move_left_inr, id], rw hn _ hk <|> rw hm _ hk, -- But of course xor is injective, so if we change one of the arguments, we will not get the -- same value again. intro h, rw ordinal.nat_cast_inj at h, try { rw [nat.lxor_comm n k, nat.lxor_comm n m] at h }, exact _root_.ne_of_lt hk (nat.lxor_left_inj h) } }, have h₁ : ∀ (u : ordinal), u < nat.lxor n m → u ∉ nonmoves (λ i, grundy_value ((nim n + nim m).move_left i)), { -- Take any natural number `u` less than `n xor m`. intros ou hu, obtain ⟨u, rfl⟩ := ordinal.lt_omega.1 (lt_trans hu (ordinal.nat_lt_omega _)), replace hu := ordinal.nat_cast_lt.1 hu, -- Our goal is to produce a move that gives the Grundy value `u`. simp only [nonmoves, not_exists, not_not, set.mem_set_of_eq, not_forall], -- By a lemma about xor, either `u xor m < n` or `u xor n < m`. have : nat.lxor u (nat.lxor n m) ≠ 0, { intro h, rw nat.lxor_eq_zero at h, linarith }, rcases nat.lxor_trichotomy this with h|h|h, { linarith }, -- Therefore, we can play the corresponding move, and by the inductive hypothesis the new state -- is `(u xor m) xor m = u` or `n xor (u xor n) = u` as required. { obtain ⟨i, hi⟩ := nim.exists_move_left_eq _ _ (ordinal.nat_cast_lt.2 h), refine ⟨(left_moves_add _ _).symm (sum.inl i), _⟩, simp only [hi, add_move_left_inl], rw [hn _ h, nat.lxor_assoc, nat.lxor_self, nat.lxor_zero] }, { obtain ⟨i, hi⟩ := nim.exists_move_left_eq _ _ (ordinal.nat_cast_lt.2 h), refine ⟨(left_moves_add _ _).symm (sum.inr i), _⟩, simp only [hi, add_move_left_inr], rw [hm _ h, nat.lxor_comm, nat.lxor_assoc, nat.lxor_self, nat.lxor_zero] } }, -- We are done! apply le_antisymm (ordinal.omin_le h₀), contrapose! h₁, exact ⟨_, ⟨h₁, ordinal.omin_mem _ _⟩⟩ end lemma nim_add_nim_equiv {n m : ℕ} : nim n + nim m ≈ nim (nat.lxor n m) := by rw [equiv_nim_iff_grundy_value_eq, grundy_value_nim_add_nim] lemma grundy_value_add (G H : pgame) [G.impartial] [H.impartial] {n m : ℕ} (hG : grundy_value G = n) (hH : grundy_value H = m) : grundy_value (G + H) = nat.lxor n m := begin rw [←nim.grundy_value (nat.lxor n m), ←equiv_iff_grundy_value_eq], refine equiv_trans _ nim_add_nim_equiv, convert add_congr (equiv_nim_grundy_value G) (equiv_nim_grundy_value H); simp only [hG, hH] end end pgame
eec6e4e3dc3a705af332bb0bc85acf2ee3896943
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/data/list/perm.lean
2e53309e3640ad4224e5b6575aec19e0b72c8304
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
53,752
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.list.bag_inter import data.list.erase_dup import data.list.zip import logic.relation /-! # List permutations -/ open_locale nat namespace list universe variables uu vv variables {α : Type uu} {β : Type vv} /-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations of each other. This is defined by induction using pairwise swaps. -/ inductive perm : list α → list α → Prop | nil : perm [] [] | cons : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ open perm (swap) infix ` ~ `:50 := perm @[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l | [] := perm.nil | (x::xs) := (perm.refl xs).cons x @[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p perm.nil (λ x l₁ l₂ p₁ r₁, r₁.cons x) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₂.trans r₁) theorem perm_comm {l₁ l₂ : list α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨perm.symm, perm.symm⟩ theorem perm.swap' (x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ := (swap _ _ _).trans ((p.cons _).cons _) attribute [trans] perm.trans theorem perm.eqv (α) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) instance is_setoid (α) : setoid (list α) := setoid.mk (@perm α) (perm.eqv α) theorem perm.subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ := λ a, perm.rec_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim i (λ ax, by simp [ax]) (λ al₁, or.inr (r₁ al₁))) (λ x y l ayxl, or.elim ayxl (λ ay, by simp [ay]) (λ axl, or.elim axl (λ ax, by simp [ax]) (λ al, or.inr (or.inr al)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem perm.mem_iff {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ := iff.intro (λ m, h.subset m) (λ m, h.symm.subset m) theorem perm.append_right {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ := perm.rec_on p (perm.refl ([] ++ t₁)) (λ x l₁ l₂ p₁ r₁, r₁.cons x) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₁.trans r₂) theorem perm.append_left {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂ | [] p := p | (x::xs) p := (perm.append_left xs p).cons x theorem perm.append {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ := (p₁.append_right t₁).trans (p₂.append_left l₂) theorem perm.append_cons (a : α) {h₁ h₂ t₁ t₂ : list α} (p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ := p₁.append (p₂.cons a) @[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂) | [] l₂ := perm.refl _ | (b::l₁) l₂ := ((@perm_middle l₁ l₂).cons _).trans (swap a b _) @[simp] theorem perm_append_singleton (a : α) (l : list α) : l ++ [a] ~ a::l := perm_middle.trans $ by rw [append_nil] theorem perm_append_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁) | [] l₂ := by simp | (a::t) l₂ := (perm_append_comm.cons _).trans perm_middle.symm theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l := by simp theorem perm.length_eq {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ := perm.rec_on p rfl (λ x l₁ l₂ p r, by simp[r]) (λ x y l, by simp) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem perm.eq_nil {l : list α} (p : l ~ []) : l = [] := eq_nil_of_length_eq_zero p.length_eq theorem perm.nil_eq {l : list α} (p : [] ~ l) : [] = l := p.symm.eq_nil.symm @[simp] theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] := ⟨λ p, p.eq_nil, λ e, e ▸ perm.refl _⟩ @[simp] theorem nil_perm {l₁ : list α} : [] ~ l₁ ↔ l₁ = [] := perm_comm.trans perm_nil theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l | p := by injection p.symm.eq_nil @[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l | [] := perm.nil | (a::l) := by { rw reverse_cons, exact (perm_append_singleton _ _).trans ((reverse_perm l).cons a) } theorem perm_cons_append_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) := (p.cons a).trans perm_middle.symm @[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : l ~ repeat a n ↔ l = repeat a n := ⟨λ p, (eq_repeat.2 ⟨p.length_eq.trans $ length_repeat _ _, λ b m, eq_of_mem_repeat $ p.subset m⟩), λ h, h ▸ perm.refl _⟩ @[simp] theorem repeat_perm {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l := (perm_comm.trans perm_repeat).trans eq_comm @[simp] theorem perm_singleton {a : α} {l : list α} : l ~ [a] ↔ l = [a] := @perm_repeat α a 1 l @[simp] theorem singleton_perm {a : α} {l : list α} : [a] ~ l ↔ [a] = l := @repeat_perm α a 1 l theorem perm.eq_singleton {a : α} {l : list α} (p : l ~ [a]) : l = [a] := perm_singleton.1 p theorem perm.singleton_eq {a : α} {l : list α} (p : [a] ~ l) : [a] = l := p.symm.eq_singleton.symm theorem singleton_perm_singleton {a b : α} : [a] ~ [b] ↔ a = b := by simp theorem perm_cons_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : l ~ a :: l.erase a := let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in e₂.symm ▸ e₁.symm ▸ perm_middle @[elab_as_eliminator] theorem perm_induction_on {P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l, from assume l, list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ @[congr] theorem perm.filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : filter_map f l₁ ~ filter_map f l₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp only [filter_map], cases f x with a; simp [filter_map, IH, perm.cons] }, { simp only [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] }, { exact IH₁.trans IH₂ } end @[congr] theorem perm.map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : map f l₁ ~ map f l₂ := filter_map_eq_map f ▸ p.filter_map _ theorem perm.pmap {p : α → Prop} (f : Π a, p a → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp [IH, perm.cons] }, { simp [swap] }, { refine IH₁.trans IH₂, exact λ a m, H₂ a (p₂.subset m) } end theorem perm.filter (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ := by rw ← filter_map_eq_filter; apply s.filter_map _ theorem exists_perm_sublist {l₁ l₂ l₂' : list α} (s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s, { exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ }, { cases s with _ _ _ s l₁ _ _ s, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ }, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', p'.cons x, s'.cons2 _ _ _⟩ } }, { cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s, { exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ }, { exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ }, { exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ }, { exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } }, { exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in ⟨r₁, pr.trans pm, sr⟩ } end theorem perm.sizeof_eq_sizeof [has_sizeof α] {l₁ l₂ : list α} (h : l₁ ~ l₂) : l₁.sizeof = l₂.sizeof := begin induction h with hd l₁ l₂ h₁₂ h_sz₁₂ a b l l₁ l₂ l₃ h₁₂ h₂₃ h_sz₁₂ h_sz₂₃, { refl }, { simp only [list.sizeof, h_sz₁₂] }, { simp only [list.sizeof, add_left_comm] }, { simp only [h_sz₁₂, h_sz₂₃] } end section rel open relator variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} local infixr ` ∘r ` : 80 := relation.comp lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm := begin funext a c, apply propext, split, { exact assume ⟨b, hab, hba⟩, perm.trans hab hba }, { exact assume h, ⟨a, perm.refl a, h⟩ } end lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v := begin induction hlu generalizing v, case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ }, case perm.cons : a l u hlu ih { cases huv with _ b _ v hab huv', rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩, exact ⟨b::l₂, forall₂.cons hab h₁₂, h₂₃.cons _⟩ }, case perm.swap : a₁ a₂ l₁ l₂ h₂₃ { cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃, cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂, exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩ }, case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ { rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩, rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩, exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩ } end lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r := begin funext l₁ l₃, apply propext, split, { assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩, have : forall₂ (flip r) l₂ l₁, from h₁₂.flip , rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩, exact ⟨l', h₂.symm, h₁.flip⟩ }, { exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ } end lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm := assume a b h₁ c d h₂ h, have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩, have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d, by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this, let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in have b' = b, from right_unique_forall₂' hr hcb hbc, this ▸ hbd lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm := assume a b hab c d hcd, iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp (left_unique_flip hr.1) hab.flip hcd.flip) end rel section subperm /-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects multiplicities of elements, and is used for the `≤` relation on multisets. -/ def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂ infix ` <+~ `:50 := subperm theorem nil_subperm {l : list α} : [] <+~ l := ⟨[], perm.nil, by simp⟩ theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ := suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂, from ⟨this p, this p.symm⟩, λ l₁ l₂ p ⟨u, pu, su⟩, let ⟨v, pv, sv⟩ := exists_perm_sublist su p in ⟨v, pv.trans pu, sv⟩ theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l := ⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩, λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩ theorem sublist.subperm {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ := ⟨l₁, perm.refl _, s⟩ theorem perm.subperm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ := ⟨l₂, p.symm, sublist.refl _⟩ @[refl] theorem subperm.refl (l : list α) : l <+~ l := (perm.refl _).subperm @[trans] theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃ | s ⟨l₂', p₂, s₂⟩ := let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩ theorem subperm.length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂ | ⟨l, p, s⟩ := p.length_eq ▸ length_le_of_sublist s theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂ | ⟨l, p, s⟩ h := suffices l = l₂, from this ▸ p.symm, eq_of_sublist_of_length_le s $ p.symm.length_eq ▸ h theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ := h₁.perm_of_length_le h₂.length_le theorem subperm.subset {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂ | ⟨l, p, s⟩ := subset.trans p.symm.subset s.subset end subperm theorem sublist.exists_perm_append : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l | ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩ | ._ ._ (sublist.cons l₁ l₂ a s) := let ⟨l, p⟩ := sublist.exists_perm_append s in ⟨a::l, (p.cons a).trans perm_middle.symm⟩ | ._ ._ (sublist.cons2 l₁ l₂ a s) := let ⟨l, p⟩ := sublist.exists_perm_append s in ⟨l, p.cons a⟩ theorem perm.countp_eq (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ := by rw [countp_eq_length_filter, countp_eq_length_filter]; exact (s.filter _).length_eq theorem subperm.countp_le (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂ | ⟨l, p', s⟩ := p'.countp_eq p ▸ countp_le_of_sublist p s theorem perm.count_eq [decidable_eq α] {l₁ l₂ : list α} (p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ := p.countp_eq _ theorem subperm.count_le [decidable_eq α] {l₁ l₂ : list α} (s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ := s.countp_le _ theorem perm.foldl_eq' {f : β → α → β} {l₁ l₂ : list α} (p : l₁ ~ l₂) : (∀ (x ∈ l₁) (y ∈ l₁) z, f (f z x) y = f (f z y) x) → ∀ b, foldl f b l₁ = foldl f b l₂ := perm_induction_on p (λ H b, rfl) (λ x t₁ t₂ p r H b, r (λ x hx y hy, H _ (or.inr hx) _ (or.inr hy)) _) (λ x y t₁ t₂ p r H b, begin simp only [foldl], rw [H x (or.inr $ or.inl rfl) y (or.inl rfl)], exact r (λ x hx y hy, H _ (or.inr $ or.inr hx) _ (or.inr $ or.inr hy)) _ end) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ H b, eq.trans (r₁ H b) (r₂ (λ x hx y hy, H _ (p₁.symm.subset hx) _ (p₁.symm.subset hy)) b)) theorem perm.foldl_eq {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) : ∀ b, foldl f b l₁ = foldl f b l₂ := p.foldl_eq' $ λ x hx y hy z, rcomm z x y theorem perm.foldr_eq {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) : ∀ b, foldr f b l₁ = foldr f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, by simp; rw [r b]) (λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b]) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) lemma perm.rec_heq {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α} (hl : perm l l') (f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b') (f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) : @list.rec α β b f l == @list.rec α β b f l' := begin induction hl, case list.perm.nil { refl }, case list.perm.cons : a l l' h ih { exact f_congr h ih }, case list.perm.swap : a a' l { exact f_swap }, case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ } end section variables {op : α → α → α} [is_associative α op] [is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l lemma perm.fold_op_eq {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a := h.foldl_eq (right_comm _ is_commutative.comm is_associative.assoc) _ end section comm_monoid /-- If elements of a list commute with each other, then their product does not depend on the order of elements-/ @[to_additive] lemma perm.prod_eq' [monoid α] {l₁ l₂ : list α} (h : l₁ ~ l₂) (hc : l₁.pairwise (λ x y, x * y = y * x)) : l₁.prod = l₂.prod := h.foldl_eq' (forall_of_forall_of_pairwise (λ x y h z, (h z).symm) (λ x hx z, rfl) $ hc.imp $ λ x y h z, by simp only [mul_assoc, h]) _ variable [comm_monoid α] @[to_additive] lemma perm.prod_eq {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ := h.fold_op_eq @[to_additive] lemma prod_reverse (l : list α) : prod l.reverse = prod l := (reverse_perm l).prod_eq end comm_monoid theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ := begin generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂, intro p, revert l₁ l₂ r₁ r₂ e₁ e₂, refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _) (λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂, { apply (not_mem_nil a).elim, rw ← e₁, simp }, { cases l₁ with y l₁; cases l₂ with z l₂; dsimp at e₁ e₂; injections; subst x, { substs t₁ t₂, exact p }, { substs z t₁ t₂, exact p.trans perm_middle }, { substs y t₁ t₂, exact perm_middle.symm.trans p }, { substs z t₁ t₂, exact (IH rfl rfl).cons y } }, { rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩; dsimp at e₁ e₂; injections; substs x y, { substs r₁ r₂, exact p.cons a }, { substs r₁ r₂, exact p.cons u }, { substs r₁ v t₂, exact (p.trans perm_middle).cons u }, { substs r₁ r₂, exact p.cons y }, { substs r₁ r₂ y u, exact p.cons a }, { substs r₁ u v t₂, exact ((p.trans perm_middle).cons y).trans (swap _ _ _) }, { substs r₂ z t₁, exact (perm_middle.symm.trans p).cons y }, { substs r₂ y z t₁, exact (swap _ _ _).trans ((perm_middle.symm.trans p).cons u) }, { substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } }, { substs t₁ t₃, have : a ∈ t₂ := p₁.subset (by simp), rcases mem_split this with ⟨l₂, r₂, e₂⟩, subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) } end theorem perm.cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := @perm_inv_core _ _ [] [] _ _ @[simp] theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ := ⟨perm.cons_inv, perm.cons a⟩ theorem perm_append_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂ | [] := iff.rfl | (a::l) := (perm_cons a).trans (perm_append_left_iff l) theorem perm_append_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ := ⟨λ p, (perm_append_left_iff _).1 $ perm_append_comm.trans $ p.trans perm_append_comm, perm.append_right _⟩ theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ := begin refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩, cases o₁ with a; cases o₂ with b, {refl}, { cases p.length_eq }, { cases p.length_eq }, { exact option.mem_to_list.1 (p.symm.subset $ by simp) } end theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ := ⟨λ ⟨l, p, s⟩, begin cases s with _ _ _ s' u _ _ s', { exact (p.subperm_left.2 $ (sublist_cons _ _).subperm).trans s'.subperm }, { exact ⟨u, p.cons_inv, s'⟩ } end, λ ⟨l, p, s⟩, ⟨a::l, p.cons a, s.cons2 _ _ _⟩⟩ theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂) (s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ := begin rcases s with ⟨l, p, s⟩, induction s generalizing l₁, case list.sublist.slnil { cases h₂ }, case list.sublist.cons : r₁ r₂ b s' ih { simp at h₂, cases h₂ with e m, { subst b, exact ⟨a::r₁, p.cons a, s'.cons2 _ _ _⟩ }, { rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } }, case list.sublist.cons2 : r₁ r₂ b s' ih { have bm : b ∈ l₁ := (p.subset $ mem_cons_self _ _), have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm), rcases mem_split bm with ⟨t₁, t₂, rfl⟩, have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp, rcases ih am (nodup_of_sublist st d₁) (mt (λ x, st.subset x) h₁) (perm.cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩, exact ⟨b::t, (p'.cons b).trans $ (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons2 _ _ _⟩ } end theorem subperm_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂ | [] := iff.rfl | (a::l) := (subperm_cons a).trans (subperm_append_left l) theorem subperm_append_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ := (perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l) theorem subperm.exists_of_length_lt {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂ | ⟨l, p, s⟩ h := suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from (this $ p.symm.length_eq ▸ h).imp (λ a, (p.cons a).subperm_right.1), begin clear subperm.exists_of_length_lt p h l₁, rename l₂ u, induction s with l₁ l₂ a s IH _ _ b s IH; intro h, { cases h }, { cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h, { exact (IH h).imp (λ a s, s.trans (sublist_cons _ _).subperm) }, { exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } }, { exact (IH $ nat.lt_of_succ_lt_succ h).imp (λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) } end theorem subperm_of_subset_nodup {l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ := begin induction d with a l₁' h d IH, { exact ⟨nil, perm.nil, nil_sublist _⟩ }, { cases forall_mem_cons.1 H with H₁ H₂, simp at h, exact cons_subperm_of_mem d h H₁ (IH H₂) } end theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) : l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ := ⟨λ p a, p.mem_iff, λ H, subperm.antisymm (subperm_of_subset_nodup d₁ (λ a, (H a).1)) (subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩ theorem nodup.sublist_ext {l₁ l₂ l : list α} (d : nodup l) (s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ := ⟨λ h, begin induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁, { exact h.eq_nil }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { exact IH d.2 s₁ h }, { apply d.1.elim, exact subperm.subset ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { apply d.1.elim, exact subperm.subset ⟨_, h, s₁⟩ (mem_cons_self _ _) }, { rw IH d.2 s₁ h.cons_inv } } end, λ h, by rw h⟩ section variable [decidable_eq α] -- attribute [congr] theorem perm.erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁.erase a ~ l₂.erase a := if h₁ : a ∈ l₁ then have h₂ : a ∈ l₂, from p.subset h₁, perm.cons_inv $ (perm_cons_erase h₁).symm.trans $ p.trans (perm_cons_erase h₂) else have h₂ : a ∉ l₂, from mt p.mem_iff.2 h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p theorem subperm_cons_erase (a : α) (l : list α) : l <+~ a :: l.erase a := begin by_cases h : a ∈ l, { exact (perm_cons_erase h).subperm }, { rw [erase_of_not_mem h], exact (sublist_cons _ _).subperm } end theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l := (erase_sublist _ _).subperm theorem subperm.erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a := let ⟨l, hp, hs⟩ := h in ⟨l.erase a, hp.erase _, hs.erase _⟩ theorem perm.diff_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, perm.erase] theorem perm.diff_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ := by induction h generalizing l; simp [*, perm.erase, erase_comm] <|> exact (ih_1 _).trans (ih_2 _) theorem perm.diff {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.diff t₁ ~ l₂.diff t₂ := ht.diff_left l₂ ▸ hl.diff_right _ theorem subperm.diff_right {l₁ l₂ : list α} (h : l₁ <+~ l₂) (t : list α) : l₁.diff t <+~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, subperm.erase] theorem erase_cons_subperm_cons_erase (a b : α) (l : list α) : (a :: l).erase b <+~ a :: l.erase b := begin by_cases h : a = b, { subst b, rw [erase_cons_head], apply subperm_cons_erase }, { rw [erase_cons_tail _ h] } end theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂ | l₁ [] := ⟨a::l₁, by simp⟩ | l₁ (b::l₂) := begin simp only [diff_cons], refine ((erase_cons_subperm_cons_erase a b l₁).diff_right l₂).trans _, apply subperm_cons_diff end theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ := subperm_cons_diff.subset theorem perm.bag_inter_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.bag_inter t ~ l₂.bag_inter t := begin induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp}, { by_cases x ∈ t; simp [*, perm.cons] }, { by_cases x = y, {simp [h]}, by_cases xt : x ∈ t; by_cases yt : y ∈ t, { simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] }, { simp [xt, yt, mt mem_of_mem_erase, perm.cons] }, { simp [xt, yt, mt mem_of_mem_erase, perm.cons] }, { simp [xt, yt] } }, { exact (ih_1 _).trans (ih_2 _) } end theorem perm.bag_inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l.bag_inter t₁ = l.bag_inter t₂ := begin induction l with a l IH generalizing t₁ t₂ p, {simp}, by_cases a ∈ t₁, { simp [h, p.subset h, IH (p.erase _)] }, { simp [h, mt p.mem_iff.2 h, IH p] } end theorem perm.bag_inter {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.bag_inter t₁ ~ l₂.bag_inter t₂ := ht.bag_inter_left l₂ ▸ hl.bag_inter_right _ theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a := ⟨λ h, have a ∈ l₂, from h.subset (mem_cons_self a l₁), ⟨this, (h.trans $ perm_cons_erase this).cons_inv⟩, λ ⟨m, h⟩, (h.cons a).trans (perm_cons_erase m).symm⟩ theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ := ⟨perm.count_eq, λ H, begin induction l₁ with a l₁ IH generalizing l₂, { cases l₂ with b l₂, {refl}, specialize H b, simp at H, contradiction }, { have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos), refine ((IH $ λ b, _).cons a).trans (perm_cons_erase this).symm, specialize H b, rw (perm_cons_erase this).count_eq at H, by_cases b = a; simp [h] at H ⊢; assumption } end⟩ lemma subperm.cons_right {α : Type*} {l l' : list α} (x : α) (h : l <+~ l') : l <+~ x :: l' := h.trans (sublist_cons x l').subperm /-- The list version of `multiset.add_sub_of_le`. -/ lemma subperm_append_diff_self_of_count_le {l₁ l₂ : list α} (h : ∀ x ∈ l₁, count x l₁ ≤ count x l₂) : l₁ ++ l₂.diff l₁ ~ l₂ := begin induction l₁ with hd tl IH generalizing l₂, { simp }, { have : hd ∈ l₂, { rw ←count_pos, exact lt_of_lt_of_le (count_pos.mpr (mem_cons_self _ _)) (h hd (mem_cons_self _ _)) }, replace this : l₂ ~ hd :: l₂.erase hd := perm_cons_erase this, refine perm.trans _ this.symm, rw [cons_append, diff_cons, perm_cons], refine IH (λ x hx, _), specialize h x (mem_cons_of_mem _ hx), rw (perm_iff_count.mp this) at h, by_cases hx : x = hd, { subst hd, simpa [nat.succ_le_succ_iff] using h }, { simpa [hx] using h } }, end /-- The list version of `multiset.le_iff_count`. -/ lemma subperm_ext_iff {l₁ l₂ : list α} : l₁ <+~ l₂ ↔ ∀ x ∈ l₁, count x l₁ ≤ count x l₂ := begin refine ⟨λ h x hx, subperm.count_le h x, λ h, _⟩, suffices : l₁ <+~ (l₂.diff l₁ ++ l₁), { refine this.trans (perm.subperm _), exact perm_append_comm.trans (subperm_append_diff_self_of_count_le h) }, convert (subperm_append_right _).mpr nil_subperm using 1 end lemma subperm.cons_left {l₁ l₂ : list α} (h : l₁ <+~ l₂) (x : α) (hx : count x l₁ < count x l₂) : x :: l₁ <+~ l₂ := begin rw subperm_ext_iff at h ⊢, intros y hy, by_cases hy' : y = x, { subst x, simpa using nat.succ_le_of_lt hx }, { rw count_cons_of_ne hy', refine h y _, simpa [hy'] using hy } end instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) | [] [] := is_true $ perm.refl _ | [] (b::l₂) := is_false $ λ h, by have := h.nil_eq; contradiction | (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a); exact decidable_of_iff' _ cons_perm_iff_perm_erase -- @[congr] theorem perm.erase_dup {l₁ l₂ : list α} (p : l₁ ~ l₂) : erase_dup l₁ ~ erase_dup l₂ := perm_iff_count.2 $ λ a, if h : a ∈ l₁ then by simp [nodup_erase_dup, h, p.subset h] else by simp [h, mt p.mem_iff.2 h] -- attribute [congr] theorem perm.insert (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ := if h : a ∈ l₁ then by simpa [h, p.subset h] using p else by simpa [h, mt p.mem_iff.2 h] using p.cons a theorem perm_insert_swap (x y : α) (l : list α) : insert x (insert y l) ~ insert y (insert x l) := begin by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl], by_cases xy : x = y, { simp [xy] }, simp [not_mem_cons_of_ne_of_not_mem xy xl, not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl], constructor end theorem perm_insert_nth {α} (x : α) (l : list α) {n} (h : n ≤ l.length) : insert_nth n x l ~ x :: l := begin induction l generalizing n, { cases n, refl, cases h }, cases n, { simp [insert_nth] }, { simp only [insert_nth, modify_nth_tail], transitivity, { apply perm.cons, apply l_ih, apply nat.le_of_succ_le_succ h }, { apply perm.swap } } end theorem perm.union_right {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ := begin induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp}, { exact ih.insert a }, { apply perm_insert_swap }, { exact ih_1.trans ih_2 } end theorem perm.union_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ := by induction l; simp [*, perm.insert] -- @[congr] theorem perm.union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ := (p₁.union_right t₁).trans (p₂.union_left l₂) theorem perm.inter_right {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ := perm.filter _ theorem perm.inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ := by { dsimp [(∩), list.inter], congr, funext a, rw [p.mem_iff] } -- @[congr] theorem perm.inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ := p₂.inter_left l₂ ▸ p₁.inter_right t₁ theorem perm.inter_append {l t₁ t₂ : list α} (h : disjoint t₁ t₂) : l ∩ (t₁ ++ t₂) ~ l ∩ t₁ ++ l ∩ t₂ := begin induction l, case list.nil { simp }, case list.cons : x xs l_ih { by_cases h₁ : x ∈ t₁, { have h₂ : x ∉ t₂ := h h₁, simp * }, by_cases h₂ : x ∈ t₂, { simp only [*, inter_cons_of_not_mem, false_or, mem_append, inter_cons_of_mem, not_false_iff], transitivity, { apply perm.cons _ l_ih, }, change [x] ++ xs ∩ t₁ ++ xs ∩ t₂ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ t₂), rw [← list.append_assoc], solve_by_elim [perm.append_right, perm_append_comm] }, { simp * } }, end end theorem perm.pairwise_iff {R : α → α → Prop} (S : symmetric R) : ∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ := suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩, λ l₁ l₂ p d, begin induction d with a l₁ h d IH generalizing l₂, { rw ← p.nil_eq, constructor }, { have : a ∈ l₂ := p.subset (mem_cons_self _ _), rcases mem_split this with ⟨s₂, t₂, rfl⟩, have p' := (p.trans perm_middle).cons_inv, refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩), exact h _ (p'.symm.subset m) } end theorem perm.nodup_iff {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) := perm.pairwise_iff $ @ne.symm α theorem perm.bind_right {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) : l₁.bind f ~ l₂.bind f := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact IH.append_left _ }, { simp, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end theorem perm.bind_left (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) : l.bind f ~ l.bind g := by induction l with a l IH; simp; exact (h a).append IH theorem bind_append_perm (l : list α) (f g : α → list β) : l.bind f ++ l.bind g ~ l.bind (λ x, f x ++ g x) := begin induction l with a l IH; simp, refine (perm.trans _ (IH.append_left _)).append_left _, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ end theorem perm.product_right {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) : product l₁ t₁ ~ product l₂ t₁ := p.bind_right _ theorem perm.product_left (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) : product l t₁ ~ product l t₂ := perm.bind_left _ $ λ a, p.map _ @[congr] theorem perm.product {l₁ l₂ : list α} {t₁ t₂ : list β} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ := (p₁.product_right t₁).trans (p₂.product_left l₂) theorem sublists_cons_perm_append (a : α) (l : list α) : sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) := begin simp only [sublists, sublists_aux_cons_cons, cons_append, perm_cons], refine (perm.cons _ _).trans perm_middle.symm, induction sublists_aux l cons with b l IH; simp, exact (IH.cons _).trans perm_middle.symm end theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l | [] := perm.refl _ | (a::l) := let IH := sublists_perm_sublists' l in by rw sublists'_cons; exact (sublists_cons_perm_append _ _).trans (IH.append (IH.map _)) theorem revzip_sublists (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l := begin rw revzip, apply list.reverse_rec_on l, { intros l₁ l₂ h, simp at h, simp [h] }, { intros l a IH l₁ l₂ h, rw [sublists_concat, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [skip, {simp}], simp only [prod.mk.inj_iff, mem_map, mem_append, prod.map_mk, prod.exists] at h, rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { rw ← append_assoc, exact (IH _ _ h).append_right _ }, { rw append_assoc, apply (perm_append_comm.append_left _).trans, rw ← append_assoc, exact (IH _ _ h).append_right _ } } end theorem revzip_sublists' (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l := begin rw revzip, induction l with a l IH; intros l₁ l₂ h, { simp at h, simp [h] }, { rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [simp at h, simp], rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', h, rfl⟩, { exact perm_middle.trans ((IH _ _ h).cons _) }, { exact (IH _ _ h).cons _ } } end theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α} (H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁) (p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ := begin let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { cases h : f a, { simp [h], exact IH (pairwise_cons.1 H).2 }, { simp [lookmap_cons_some _ _ h, p] } }, { cases h₁ : f a with c; cases h₂ : f b with d, { simp [h₁, h₂], apply swap }, { simp [h₁, lookmap_cons_some _ _ h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂], rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩, refl } }, { refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)), exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm } end theorem perm.erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α} (H : pairwise (λ a b, f a → f b → false) l₁) (p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ := begin let F := λ a b, f a → f b → false, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { by_cases h : f a, { simp [h, p] }, { simp [h], exact IH (pairwise_cons.1 H).2 } }, { by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂], { cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ }, { apply swap } }, { refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)), exact λ a b h h₁ h₂, h h₂ h₁ } end lemma perm.take_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ) (h : xs ~ ys) (h' : ys.nodup) : xs.take n ~ ys.inter (xs.take n) := begin simp only [list.inter] at *, induction h generalizing n, case list.perm.nil : n { simp only [not_mem_nil, filter_false, take_nil] }, case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih n { cases n; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos, perm_cons, take, not_mem_nil, filter_false], cases h' with _ _ h₁ h₂, convert h_ih h₂ n using 1, apply filter_congr, introv h, simp only [(h₁ x h).symm, false_or], }, case list.perm.swap : h_x h_y h_l n { cases h' with _ _ h₁ h₂, cases h₂ with _ _ h₂ h₃, have := h₁ _ (or.inl rfl), cases n; simp only [mem_cons_iff, not_mem_nil, filter_false, take], cases n; simp only [mem_cons_iff, false_or, true_or, filter, *, nat.nat_zero_eq_zero, if_true, not_mem_nil, eq_self_iff_true, or_false, if_false, perm_cons, take], { rw filter_eq_nil.2, intros, solve_by_elim [ne.symm], }, { convert perm.swap _ _ _, rw @filter_congr _ _ (∈ take n h_l), { clear h₁, induction n generalizing h_l; simp only [not_mem_nil, filter_false, take], cases h_l; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos, true_and, take, not_mem_nil, filter_false, take_nil], cases h₃ with _ _ h₃ h₄, rwa [@filter_congr _ _ (∈ take n_n h_l_tl), n_ih], { introv h, apply h₂ _ (or.inr h), }, { introv h, simp only [(h₃ x h).symm, false_or], }, }, { introv h, simp only [(h₂ x h).symm, (h₁ x (or.inr h)).symm, false_or], } } }, case list.perm.trans : h_l₁ h_l₂ h_l₃ h₀ h₁ h_ih₀ h_ih₁ n { transitivity, { apply h_ih₀, rwa h₁.nodup_iff }, { apply perm.filter _ h₁, } }, end lemma perm.drop_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ) (h : xs ~ ys) (h' : ys.nodup) : xs.drop n ~ ys.inter (xs.drop n) := begin by_cases h'' : n ≤ xs.length, { let n' := xs.length - n, have h₀ : n = xs.length - n', { dsimp [n'], rwa nat.sub_sub_self, } , have h₁ : n' ≤ xs.length, { apply nat.sub_le_self }, have h₂ : xs.drop n = (xs.reverse.take n').reverse, { rw [reverse_take _ h₁, h₀, reverse_reverse], }, rw [h₂], apply (reverse_perm _).trans, rw inter_reverse, apply perm.take_inter _ _ h', apply (reverse_perm _).trans; assumption, }, { have : drop n xs = [], { apply eq_nil_of_length_eq_zero, rw [length_drop, nat.sub_eq_zero_iff_le], apply le_of_not_ge h'' }, simp [this, list.inter], } end lemma perm.slice_inter {α} [decidable_eq α] {xs ys : list α} (n m : ℕ) (h : xs ~ ys) (h' : ys.nodup) : list.slice n m xs ~ ys ∩ (list.slice n m xs) := begin simp only [slice_eq], have : n ≤ n + m := nat.le_add_right _ _, have := h.nodup_iff.2 h', apply perm.trans _ (perm.inter_append _).symm; solve_by_elim [perm.append, perm.drop_inter, perm.take_inter, disjoint_take_drop, h, h'] { max_depth := 7 }, end /- enumerating permutations -/ section permutations theorem perm_of_mem_permutations_aux : ∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2 m, rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m, rcases m with m | ⟨l₁, l₂, m, _, e⟩, { exact (IH1 m).trans perm_middle }, { subst e, have p : l₁ ++ l₂ ~ is, { simp [permutations] at m, cases m with e m, {simp [e]}, exact is.append_nil ▸ IH2 m }, exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) } end theorem perm_of_mem_permutations {l₁ l₂ : list α} (h : l₁ ∈ permutations l₂) : l₁ ~ l₂ := (eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _) (λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m) theorem length_permutations_aux : ∀ ts is : list α, length (permutations_aux ts is) + is.length! = (length ts + length is)! := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2, have IH2 : length (permutations_aux is nil) + 1 = is.length!, { simpa using IH2 }, simp [-add_comm, nat.factorial, nat.add_succ, mul_comm] at IH1, rw [permutations_aux_cons, length_foldr_permutations_aux2' _ _ _ _ _ (λ l m, (perm_of_mem_permutations m).length_eq), permutations, length, length, IH2, nat.succ_add, nat.factorial_succ, mul_comm (nat.succ _), ← IH1, add_comm (_*_), add_assoc, nat.mul_succ, mul_comm] end theorem length_permutations (l : list α) : length (permutations l) = (length l)! := length_permutations_aux l [] theorem mem_permutations_of_perm_lemma {is l : list α} (H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is []) : l ~ is → l ∈ permutations is := by simpa [permutations, perm_nil] using H theorem mem_permutations_aux_of_perm : ∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2 l p, rw [permutations_aux_cons, mem_foldr_permutations_aux2], rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m, { clear p, subst e, rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩, subst is', have p := (perm_middle.symm.trans p').cons_inv, cases l₂ with a l₂', { exact or.inl ⟨l₁, by simpa using p⟩ }, { exact or.inr (or.inr ⟨l₁, a::l₂', mem_permutations_of_perm_lemma IH2 p, by simp⟩) } }, { exact or.inr (or.inl m) } end @[simp] theorem mem_permutations {s t : list α} : s ∈ permutations t ↔ s ~ t := ⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩ theorem perm_permutations'_aux_comm (a b : α) (l : list α) : (permutations'_aux a l).bind (permutations'_aux b) ~ (permutations'_aux b l).bind (permutations'_aux a) := begin induction l with c l ih, {simp [swap]}, simp [permutations'_aux], apply perm.swap', have : ∀ a b, (map (cons c) (permutations'_aux a l)).bind (permutations'_aux b) ~ map (cons b ∘ cons c) (permutations'_aux a l) ++ map (cons c) ((permutations'_aux a l).bind (permutations'_aux b)), { intros, simp only [map_bind, permutations'_aux], refine (bind_append_perm _ (λ x, [_]) _).symm.trans _, rw [← map_eq_bind, ← bind_map] }, refine (((this _ _).append_left _).trans _).trans ((this _ _).append_left _).symm, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append (ih.map _), end theorem perm.permutations' {s t : list α} (p : s ~ t) : permutations' s ~ permutations' t := begin induction p with a s t p IH a b l s t u p₁ p₂ IH₁ IH₂, {simp}, { simp only [permutations'], exact IH.bind_right _ }, { simp only [permutations'], rw [bind_assoc, bind_assoc], apply perm.bind_left, apply perm_permutations'_aux_comm }, { exact IH₁.trans IH₂ } end theorem permutations_perm_permutations' (ts : list α) : ts.permutations ~ ts.permutations' := begin obtain ⟨n, h⟩ : ∃ n, length ts < n := ⟨_, nat.lt_succ_self _⟩, induction n with n IH generalizing ts, {cases h}, refine list.reverse_rec_on ts (λ h, _) (λ ts t _ h, _) h, {simp [permutations]}, rw [← concat_eq_append, length_concat, nat.succ_lt_succ_iff] at h, have IH₂ := (IH ts.reverse (by rwa [length_reverse])).trans (reverse_perm _).permutations', simp only [permutations_append, foldr_permutations_aux2, permutations_aux_nil, permutations_aux_cons, append_nil], refine (perm_append_comm.trans ((IH₂.bind_right _).append ((IH _ h).map _))).trans (perm.trans _ perm_append_comm.permutations'), rw [map_eq_bind, singleton_append, permutations'], convert bind_append_perm _ _ _, funext ys, rw [permutations'_aux_eq_permutations_aux2, permutations_aux2_append] end @[simp] theorem mem_permutations' {s t : list α} : s ∈ permutations' t ↔ s ~ t := (permutations_perm_permutations' _).symm.mem_iff.trans mem_permutations theorem perm.permutations {s t : list α} (h : s ~ t) : permutations s ~ permutations t := (permutations_perm_permutations' _).trans $ h.permutations'.trans (permutations_perm_permutations' _).symm @[simp] theorem perm_permutations_iff {s t : list α} : permutations s ~ permutations t ↔ s ~ t := ⟨λ h, mem_permutations.1 $ h.mem_iff.1 $ mem_permutations.2 (perm.refl _), perm.permutations⟩ @[simp] theorem perm_permutations'_iff {s t : list α} : permutations' s ~ permutations' t ↔ s ~ t := ⟨λ h, mem_permutations'.1 $ h.mem_iff.1 $ mem_permutations'.2 (perm.refl _), perm.permutations'⟩ lemma nth_le_permutations'_aux (s : list α) (x : α) (n : ℕ) (hn : n < length (permutations'_aux x s)) : (permutations'_aux x s).nth_le n hn = s.insert_nth n x := begin induction s with y s IH generalizing n, { simp only [length, permutations'_aux, nat.lt_one_iff] at hn, simp [hn] }, { cases n, { simp }, { simpa using IH _ _ } } end lemma count_permutations'_aux_self [decidable_eq α] (l : list α) (x : α) : count (x :: l) (permutations'_aux x l) = length (take_while ((=) x) l) + 1 := begin induction l with y l IH generalizing x, { simp [take_while], }, { rw [permutations'_aux, count_cons_self], by_cases hx : x = y, { subst hx, simpa [take_while, nat.succ_inj'] using IH _ }, { rw take_while, rw if_neg hx, cases permutations'_aux x l with a as, { simp }, { rw [count_eq_zero_of_not_mem, length, zero_add], simp [hx, ne.symm hx] } } } end @[simp] lemma length_permutations'_aux (s : list α) (x : α) : length (permutations'_aux x s) = length s + 1 := begin induction s with y s IH, { simp }, { simpa using IH } end @[simp] lemma permutations'_aux_nth_le_zero (s : list α) (x : α) (hn : 0 < length (permutations'_aux x s) := by simp) : (permutations'_aux x s).nth_le 0 hn = x :: s := nth_le_permutations'_aux _ _ _ _ lemma injective_permutations'_aux (x : α) : function.injective (permutations'_aux x) := begin intros s t h, apply insert_nth_injective s.length x, have hl : s.length = t.length := by simpa using congr_arg length h, rw [←nth_le_permutations'_aux s x s.length (by simp), ←nth_le_permutations'_aux t x s.length (by simp [hl])], simp [h, hl] end lemma nodup_permutations'_aux_of_not_mem (s : list α) (x : α) (hx : x ∉ s) : nodup (permutations'_aux x s) := begin induction s with y s IH, { simp }, { simp only [not_or_distrib, mem_cons_iff] at hx, simp only [not_and, exists_eq_right_right, mem_map, permutations'_aux, nodup_cons], refine ⟨λ _, ne.symm hx.left, _⟩, rw nodup_map_iff, { exact IH hx.right }, { simp } } end lemma nodup_permutations'_aux_iff {s : list α} {x : α} : nodup (permutations'_aux x s) ↔ x ∉ s := begin refine ⟨λ h, _, nodup_permutations'_aux_of_not_mem _ _⟩, intro H, obtain ⟨k, hk, hk'⟩ := nth_le_of_mem H, rw nodup_iff_nth_le_inj at h, suffices : k = k + 1, { simpa using this }, refine h k (k + 1) _ _ _, { simpa [nat.lt_succ_iff] using hk.le }, { simpa using hk }, rw [nth_le_permutations'_aux, nth_le_permutations'_aux], have hl : length (insert_nth k x s) = length (insert_nth (k + 1) x s), { rw [length_insert_nth _ _ hk.le, length_insert_nth _ _ (nat.succ_le_of_lt hk)] }, refine ext_le hl (λ n hn hn', _), rcases lt_trichotomy n k with H|rfl|H, { rw [nth_le_insert_nth_of_lt _ _ _ _ H (H.trans hk), nth_le_insert_nth_of_lt _ _ _ _ (H.trans (nat.lt_succ_self _))] }, { rw [nth_le_insert_nth_self _ _ _ hk.le, nth_le_insert_nth_of_lt _ _ _ _ (nat.lt_succ_self _) hk, hk'] }, { rcases (nat.succ_le_of_lt H).eq_or_lt with rfl|H', { rw [nth_le_insert_nth_self _ _ _ (nat.succ_le_of_lt hk)], convert hk' using 1, convert nth_le_insert_nth_add_succ _ _ _ 0 _, simpa using hk }, { obtain ⟨m, rfl⟩ := nat.exists_eq_add_of_lt H', rw [length_insert_nth _ _ hk.le, nat.succ_lt_succ_iff, nat.succ_add] at hn, rw nth_le_insert_nth_add_succ, convert nth_le_insert_nth_add_succ s x k m.succ _ using 2, { simp [nat.add_succ, nat.succ_add] }, { simp [add_left_comm, add_comm] }, { simpa [nat.add_succ] using hn }, { simpa [nat.succ_add] using hn } } } end lemma nodup_permutations (s : list α) (hs : nodup s) : nodup s.permutations := begin rw (permutations_perm_permutations' s).nodup_iff, induction hs with x l h h' IH, { simp }, { rw [permutations'], rw nodup_bind, split, { intros ys hy, rw mem_permutations' at hy, rw [nodup_permutations'_aux_iff, hy.mem_iff], exact λ H, h x H rfl }, { refine IH.pairwise_of_forall_ne (λ as ha bs hb H, _), rw disjoint_iff_ne, rintro a ha' b hb' rfl, obtain ⟨n, hn, hn'⟩ := nth_le_of_mem ha', obtain ⟨m, hm, hm'⟩ := nth_le_of_mem hb', rw mem_permutations' at ha hb, have hl : as.length = bs.length := (ha.trans hb.symm).length_eq, simp only [nat.lt_succ_iff, length_permutations'_aux] at hn hm, rw nth_le_permutations'_aux at hn' hm', have hx : nth_le (insert_nth n x as) m (by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff, hl]) = x, { simp [hn', ←hm', hm] }, have hx' : nth_le (insert_nth m x bs) n (by rwa [length_insert_nth _ _ hm, nat.lt_succ_iff, ←hl]) = x, { simp [hm', ←hn', hn] }, rcases lt_trichotomy n m with ht|ht|ht, { suffices : x ∈ bs, { exact h x (hb.subset this) rfl }, rw [←hx', nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hm)], exact nth_le_mem _ _ _ }, { simp only [ht] at hm' hn', rw ←hm' at hn', exact H (insert_nth_injective _ _ hn') }, { suffices : x ∈ as, { exact h x (ha.subset this) rfl }, rw [←hx, nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hn)], exact nth_le_mem _ _ _ } } } end -- TODO: `nodup s.permutations ↔ nodup s` -- TODO: `count s s.permutations = (zip_with count s s.tails).prod` end permutations end list
e4e76ba671f1e3249cde4c17f033c180bcf3742f
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/examples/perfectly-adapted-signal-response.lean
c8dd39240a0c6f36254a8b0d3d9d05b44e13b6dc
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
1,742
lean
import .common open cpi open cpi.species open_locale normalise def k1 : ℍ := fin_poly.X "k₁" def k2 : ℍ := fin_poly.X "k₂" def k3 : ℍ := fin_poly.X "k₃" def k4 : ℍ := fin_poly.X "k₄" def aff : affinity ℍ := affinity.mk_pair k2 def ω : context := context.extend 0 (context.extend 0 (context.extend 0 context.nil)) def Γ : context := context.extend aff.arity context.nil @[pattern] def R : reference 0 ω := reference.zero 0 @[pattern] def S : reference 0 ω := reference.extend $ reference.zero 0 @[pattern] def X : reference 0 ω := reference.extend ∘ reference.extend $ reference.zero 0 def a {Γ} : name (context.extend 2 Γ) := name.zero 0 def b {Γ} : name (context.extend 2 Γ) := name.zero 1 -- R = a.0 def R_ : choices ℍ ω Γ := a# ⬝' nil -- S = τ@2.(S|R) + τ@1.(S|X) def S_ : choices ℍ ω Γ := whole.cons τ@k1 (apply S ∅ |ₛ apply R ∅) ∘ whole.cons τ@k3 (apply S ∅ |ₛ apply X ∅) $ whole.empty -- X = τ@1.0 + b.X def X_ : choices ℍ ω Γ := whole.cons τ@k4 nil ∘ whole.cons (b#) (apply X ∅) $ whole.empty def ℓ : lookup ℍ ω Γ := λ n a, begin cases a with _ _ _ _ _ a, from species.rename name.extend R_, cases a with _ _ _ _ _ a, from species.rename name.extend S_, cases a with _ _ _ _ _ a, from species.rename name.extend X_, cases a with _ _ _ _ _ a, end def system : process ℍ ℍ ω Γ := fin_poly.X "S" ◯ (apply S ∅) |ₚ fin_poly.X "R" ◯ (apply R ∅) |ₚ fin_poly.X "X" ◯ (apply X ∅) #eval process_immediate aff ℓ (function.embedding.refl _) system /- (-1•(R•X•k₂) + 1•(S•k₁)) • 0([]) (-1•(X•k₄) + 1•(S•k₃)) • 2([]) ⇒ dR/dt = k₁S - k₂X•R ⇒ dX/dt = k₃S - k₄X -/
7f550f82da4b5314a10db1f557a7d69e708ae5fd
c56b090bd37dca8992124f0b09c22340ef7e27bc
/src/lecture4-divisibility.lean
fd5e2528df88825634a1e22abf9a9f8a75288127
[]
no_license
stjordanis/math135
df113ed7ae9f81b27316cc5b000f88b385391a81
e270f3a9cae435c066c0d2574f03a8adbe40b7b5
refs/heads/master
1,677,069,951,721
1,611,905,122,000
1,611,905,122,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,904
lean
import data.int.basic import data.nat.parity import data.nat.prime import tactic import tactic.linarith namespace lecture4 open nat theorem div_14_div_7 : ∀ N, 14 ∣ N → 7 ∣ N := begin intros N h, cases h with divisor h, refine dvd.intro _ _, let divisor' := 2 * divisor, use divisor', simp, linarith, end theorem prime_and_prime_succ : ∀ p, prime p → prime (p + 1) → p = 2 := begin intros p hprime hprimesucc, cases even_or_odd p, { cases h with n hn, let hprime2 := hprime, cases hprime, specialize hprime_right n, have n_div_p : n ∣ p, { exact dvd.intro_left 2 (eq.symm hn) }, cases hprime_right n_div_p, { linarith, }, have p_zero : p = 0, { rw h at hn, linarith, }, by_contradiction h', apply not_prime_zero, rw p_zero at hprime2, exact hprime2, }, let h2 := h, cases h with n hn, cases hprimesucc, have n_div_succ_p : 2 ∣ succ p, { refine even_iff_two_dvd.mp _, refine even_succ.mpr _, exact odd_iff_not_even.mp h2, }, specialize hprimesucc_right 2, cases hprimesucc_right n_div_succ_p, { by_contradiction h', linarith, }, have n_zero : n = 0, { linarith, }, rw n_zero at hn, by_contradiction, refine not_prime_one _, have p_one : p = 1, { linarith, }, rw ←p_one, exact hprime, end lemma only_even_prime_is_2 : ∀ {n}, prime n -> even n -> n = 2 := begin intros n hp he, cases hp, cases he, specialize hp_right 2, cases hp_right (dvd.intro he_w (eq.symm he_h) : 2 ∣ n), { finish, }, linarith, end theorem prime_and_prime_succ2 {p} (hprime : prime p) (hprimesucc : prime (p + 1)) : p = 2 := begin cases even_or_odd p, { exact only_even_prime_is_2 hprime h, }, exfalso, have p_succ_even : even (p + 1) := begin refine even_succ.mpr _, exact odd_iff_not_even.mp h, end, have p_succ_is_two : (p + 1) = 2 := only_even_prime_is_2 hprimesucc p_succ_even, have p_is_one : p = 1 := by linarith, refine not_prime_one _, rw p_is_one at hprime, exact hprime, end -- this should be defined over ℤ theorem bounds_by_divisibility {a b : ℕ} (a_divs_b : a ∣ b) (b_neq_0 : b ≠ 0) : a ≤ b := begin refine le_of_dvd _ a_divs_b, by_contradiction, have b_leq_0 : b ≤ 0 := by linarith, finish, end theorem div_trans {a b c : ℕ} (a_divs_b : a ∣ b) (b_divs_c : b ∣ c) : a ∣ c := begin cases a_divs_b with k hk, cases b_divs_c with i hi, refine dvd.intro _ _, use k * i, finish, end theorem div_of_int_combo {a b c : ℕ} (a_divs_b : a ∣ b) (b_divs_c : b ∣ c) : ∀ x y, a ∣ (b * x + c * y) := begin intros x y, cases a_divs_b with k hk, cases b_divs_c with i hi, refine dvd.intro _ _, use (k*x + k*i*y), rw hi, repeat {rw hk}, linarith, end end lecture4
fdc9421ae54e197704015576c5d0f271f1cf7c7c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/mv_polynomial/equiv.lean
bbdf61fa66fa74ecc172887a6c6b1cb99cd21340
[ "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
18,822
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, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.rename import data.polynomial.algebra_map import data.polynomial.lifts import data.mv_polynomial.variables import data.finsupp.fin import logic.equiv.fin import algebra.big_operators.fin /-! # Equivalences between polynomial rings This file establishes a number of equivalences between polynomial rings, based on equivalences between the underlying types. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ## Tags equivalence, isomorphism, morphism, ring hom, hom -/ noncomputable theory open_locale classical big_operators polynomial open set function finsupp add_monoid_algebra universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {s : σ →₀ ℕ} section equiv variables (R) [comm_semiring R] /-- The ring isomorphism between multivariable polynomials in a single variable and polynomials over the ground ring. -/ @[simps] def punit_alg_equiv : mv_polynomial punit R ≃ₐ[R] R[X] := { to_fun := eval₂ polynomial.C (λu:punit, polynomial.X), inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star), left_inv := begin let f : R[X] →+* mv_polynomial punit R := (polynomial.eval₂_ring_hom mv_polynomial.C (X punit.star)), let g : mv_polynomial punit R →+* R[X] := (eval₂_hom polynomial.C (λu:punit, polynomial.X)), show ∀ p, f.comp g p = p, apply is_id, { ext a, dsimp, rw [eval₂_C, polynomial.eval₂_C] }, { rintros ⟨⟩, dsimp, rw [eval₂_X, polynomial.eval₂_X] } end, right_inv := assume p, polynomial.induction_on p (assume a, by rw [polynomial.eval₂_C, mv_polynomial.eval₂_C]) (assume p q hp hq, by rw [polynomial.eval₂_add, mv_polynomial.eval₂_add, hp, hq]) (assume p n hp, by rw [polynomial.eval₂_mul, polynomial.eval₂_pow, polynomial.eval₂_X, polynomial.eval₂_C, eval₂_mul, eval₂_C, eval₂_pow, eval₂_X]), map_mul' := λ _ _, eval₂_mul _ _, map_add' := λ _ _, eval₂_add _ _, commutes' := λ _, eval₂_C _ _ _} section map variables {R} (σ) /-- If `e : A ≃+* B` is an isomorphism of rings, then so is `map e`. -/ @[simps apply] def map_equiv [comm_semiring S₁] [comm_semiring S₂] (e : S₁ ≃+* S₂) : mv_polynomial σ S₁ ≃+* mv_polynomial σ S₂ := { to_fun := map (e : S₁ →+* S₂), inv_fun := map (e.symm : S₂ →+* S₁), left_inv := map_left_inverse e.left_inv, right_inv := map_right_inverse e.right_inv, ..map (e : S₁ →+* S₂) } @[simp] lemma map_equiv_refl : map_equiv σ (ring_equiv.refl R) = ring_equiv.refl _ := ring_equiv.ext map_id @[simp] lemma map_equiv_symm [comm_semiring S₁] [comm_semiring S₂] (e : S₁ ≃+* S₂) : (map_equiv σ e).symm = map_equiv σ e.symm := rfl @[simp] lemma map_equiv_trans [comm_semiring S₁] [comm_semiring S₂] [comm_semiring S₃] (e : S₁ ≃+* S₂) (f : S₂ ≃+* S₃) : (map_equiv σ e).trans (map_equiv σ f) = map_equiv σ (e.trans f) := ring_equiv.ext (map_map e f) variables {A₁ A₂ A₃ : Type*} [comm_semiring A₁] [comm_semiring A₂] [comm_semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] /-- If `e : A ≃ₐ[R] B` is an isomorphism of `R`-algebras, then so is `map e`. -/ @[simps apply] def map_alg_equiv (e : A₁ ≃ₐ[R] A₂) : mv_polynomial σ A₁ ≃ₐ[R] mv_polynomial σ A₂ := { to_fun := map (e : A₁ →+* A₂), ..map_alg_hom (e : A₁ →ₐ[R] A₂), ..map_equiv σ (e : A₁ ≃+* A₂) } @[simp] lemma map_alg_equiv_refl : map_alg_equiv σ (alg_equiv.refl : A₁ ≃ₐ[R] A₁) = alg_equiv.refl := alg_equiv.ext map_id @[simp] lemma map_alg_equiv_symm (e : A₁ ≃ₐ[R] A₂) : (map_alg_equiv σ e).symm = map_alg_equiv σ e.symm := rfl @[simp] lemma map_alg_equiv_trans (e : A₁ ≃ₐ[R] A₂) (f : A₂ ≃ₐ[R] A₃) : (map_alg_equiv σ e).trans (map_alg_equiv σ f) = map_alg_equiv σ (e.trans f) := alg_equiv.ext (map_map e f) end map section variables (S₁ S₂ S₃) /-- The function from multivariable polynomials in a sum of two types, to multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. See `sum_ring_equiv` for the ring isomorphism. -/ def sum_to_iter : mv_polynomial (S₁ ⊕ S₂) R →+* mv_polynomial S₁ (mv_polynomial S₂ R) := eval₂_hom (C.comp C) (λbc, sum.rec_on bc X (C ∘ X)) @[simp] lemma sum_to_iter_C (a : R) : sum_to_iter R S₁ S₂ (C a) = C (C a) := eval₂_C _ _ a @[simp] lemma sum_to_iter_Xl (b : S₁) : sum_to_iter R S₁ S₂ (X (sum.inl b)) = X b := eval₂_X _ _ (sum.inl b) @[simp] lemma sum_to_iter_Xr (c : S₂) : sum_to_iter R S₁ S₂ (X (sum.inr c)) = C (X c) := eval₂_X _ _ (sum.inr c) /-- The function from multivariable polynomials in one type, with coefficents in multivariable polynomials in another type, to multivariable polynomials in the sum of the two types. See `sum_ring_equiv` for the ring isomorphism. -/ def iter_to_sum : mv_polynomial S₁ (mv_polynomial S₂ R) →+* mv_polynomial (S₁ ⊕ S₂) R := eval₂_hom (eval₂_hom C (X ∘ sum.inr)) (X ∘ sum.inl) lemma iter_to_sum_C_C (a : R) : iter_to_sum R S₁ S₂ (C (C a)) = C a := eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _) lemma iter_to_sum_X (b : S₁) : iter_to_sum R S₁ S₂ (X b) = X (sum.inl b) := eval₂_X _ _ _ lemma iter_to_sum_C_X (c : S₂) : iter_to_sum R S₁ S₂ (C (X c)) = X (sum.inr c) := eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _) variable (σ) /-- The algebra isomorphism between multivariable polynomials in no variables and the ground ring. -/ @[simps] def is_empty_alg_equiv [he : is_empty σ] : mv_polynomial σ R ≃ₐ[R] R := alg_equiv.of_alg_hom (aeval (is_empty.elim he)) (algebra.of_id _ _) (by { ext, simp [algebra.of_id_apply, algebra_map_eq] }) (by { ext i m, exact is_empty.elim' he i }) /-- The ring isomorphism between multivariable polynomials in no variables and the ground ring. -/ @[simps] def is_empty_ring_equiv [he : is_empty σ] : mv_polynomial σ R ≃+* R := (is_empty_alg_equiv R σ).to_ring_equiv variable {σ} /-- A helper function for `sum_ring_equiv`. -/ @[simps] def mv_polynomial_equiv_mv_polynomial [comm_semiring S₃] (f : mv_polynomial S₁ R →+* mv_polynomial S₂ S₃) (g : mv_polynomial S₂ S₃ →+* mv_polynomial S₁ R) (hfgC : (f.comp g).comp C = C) (hfgX : ∀n, f (g (X n)) = X n) (hgfC : (g.comp f).comp C = C) (hgfX : ∀n, g (f (X n)) = X n) : mv_polynomial S₁ R ≃+* mv_polynomial S₂ S₃ := { to_fun := f, inv_fun := g, left_inv := is_id (ring_hom.comp _ _) hgfC hgfX, right_inv := is_id (ring_hom.comp _ _) hfgC hfgX, map_mul' := f.map_mul, map_add' := f.map_add } /-- The ring isomorphism between multivariable polynomials in a sum of two types, and multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. -/ def sum_ring_equiv : mv_polynomial (S₁ ⊕ S₂) R ≃+* mv_polynomial S₁ (mv_polynomial S₂ R) := begin apply @mv_polynomial_equiv_mv_polynomial R (S₁ ⊕ S₂) _ _ _ _ (sum_to_iter R S₁ S₂) (iter_to_sum R S₁ S₂), { refine ring_hom.ext (λ p, _), rw [ring_hom.comp_apply], convert hom_eq_hom ((sum_to_iter R S₁ S₂).comp ((iter_to_sum R S₁ S₂).comp C)) C _ _ p, { ext1 a, dsimp, rw [iter_to_sum_C_C R S₁ S₂, sum_to_iter_C R S₁ S₂] }, { assume c, dsimp, rw [iter_to_sum_C_X R S₁ S₂, sum_to_iter_Xr R S₁ S₂] } }, { assume b, rw [iter_to_sum_X R S₁ S₂, sum_to_iter_Xl R S₁ S₂] }, { ext1 a, rw [ring_hom.comp_apply, ring_hom.comp_apply, sum_to_iter_C R S₁ S₂, iter_to_sum_C_C R S₁ S₂] }, { assume n, cases n with b c, { rw [sum_to_iter_Xl, iter_to_sum_X] }, { rw [sum_to_iter_Xr, iter_to_sum_C_X] } }, end /-- The algebra isomorphism between multivariable polynomials in a sum of two types, and multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. -/ def sum_alg_equiv : mv_polynomial (S₁ ⊕ S₂) R ≃ₐ[R] mv_polynomial S₁ (mv_polynomial S₂ R) := { commutes' := begin intro r, have A : algebra_map R (mv_polynomial S₁ (mv_polynomial S₂ R)) r = (C (C r) : _), by refl, have B : algebra_map R (mv_polynomial (S₁ ⊕ S₂) R) r = C r, by refl, simp only [sum_ring_equiv, sum_to_iter_C, mv_polynomial_equiv_mv_polynomial_apply, ring_equiv.to_fun_eq_coe, A, B], end, ..sum_ring_equiv R S₁ S₂ } section -- this speeds up typeclass search in the lemma below local attribute [instance, priority 2000] is_scalar_tower.right /-- The algebra isomorphism between multivariable polynomials in `option S₁` and polynomials with coefficients in `mv_polynomial S₁ R`. -/ @[simps] def option_equiv_left : mv_polynomial (option S₁) R ≃ₐ[R] polynomial (mv_polynomial S₁ R) := alg_equiv.of_alg_hom (mv_polynomial.aeval (λ o, o.elim polynomial.X (λ s, polynomial.C (X s)))) (polynomial.aeval_tower (mv_polynomial.rename some) (X none)) (by ext : 2; simp [← polynomial.C_eq_algebra_map]) (by ext i : 2; cases i; simp) end /-- The algebra isomorphism between multivariable polynomials in `option S₁` and multivariable polynomials with coefficients in polynomials. -/ def option_equiv_right : mv_polynomial (option S₁) R ≃ₐ[R] mv_polynomial S₁ R[X] := alg_equiv.of_alg_hom (mv_polynomial.aeval (λ o, o.elim (C polynomial.X) X)) (mv_polynomial.aeval_tower (polynomial.aeval (X none)) (λ i, X (option.some i))) begin ext : 2; simp only [mv_polynomial.algebra_map_eq, option.elim, alg_hom.coe_comp, alg_hom.id_comp, is_scalar_tower.coe_to_alg_hom', comp_app, aeval_tower_C, polynomial.aeval_X, aeval_X, option.elim, aeval_tower_X, alg_hom.coe_id, id.def, eq_self_iff_true, implies_true_iff], end begin ext ⟨i⟩ : 2; simp only [option.elim, alg_hom.coe_comp, comp_app, aeval_X, aeval_tower_C, polynomial.aeval_X, alg_hom.coe_id, id.def, aeval_tower_X], end variables (n : ℕ) /-- The algebra isomorphism between multivariable polynomials in `fin (n + 1)` and polynomials over multivariable polynomials in `fin n`. -/ def fin_succ_equiv : mv_polynomial (fin (n + 1)) R ≃ₐ[R] polynomial (mv_polynomial (fin n) R) := (rename_equiv R (fin_succ_equiv n)).trans (option_equiv_left R (fin n)) lemma fin_succ_equiv_eq : (fin_succ_equiv R n : mv_polynomial (fin (n + 1)) R →+* polynomial (mv_polynomial (fin n) R)) = eval₂_hom (polynomial.C.comp (C : R →+* mv_polynomial (fin n) R)) (λ i : fin (n+1), fin.cases polynomial.X (λ k, polynomial.C (X k)) i) := begin ext : 2, { simp only [fin_succ_equiv, option_equiv_left_apply, aeval_C, alg_equiv.coe_trans, ring_hom.coe_coe, coe_eval₂_hom, comp_app, rename_equiv_apply, eval₂_C, ring_hom.coe_comp, rename_C], refl }, { intro i, refine fin.cases _ _ i; simp [fin_succ_equiv] } end @[simp] lemma fin_succ_equiv_apply (p : mv_polynomial (fin (n + 1)) R) : fin_succ_equiv R n p = eval₂_hom (polynomial.C.comp (C : R →+* mv_polynomial (fin n) R)) (λ i : fin (n+1), fin.cases polynomial.X (λ k, polynomial.C (X k)) i) p := by { rw ← fin_succ_equiv_eq, refl } lemma fin_succ_equiv_comp_C_eq_C {R : Type u} [comm_semiring R] (n : ℕ) : (↑(mv_polynomial.fin_succ_equiv R n).symm : polynomial (mv_polynomial (fin n) R) →+* _).comp ((polynomial.C).comp (mv_polynomial.C)) = (mv_polynomial.C : R →+* mv_polynomial (fin n.succ) R) := begin refine ring_hom.ext (λ x, _), rw ring_hom.comp_apply, refine (mv_polynomial.fin_succ_equiv R n).injective (trans ((mv_polynomial.fin_succ_equiv R n).apply_symm_apply _) _), simp only [mv_polynomial.fin_succ_equiv_apply, mv_polynomial.eval₂_hom_C], end variables {n} {R} lemma fin_succ_equiv_X_zero : fin_succ_equiv R n (X 0) = polynomial.X := by simp lemma fin_succ_equiv_X_succ {j : fin n} : fin_succ_equiv R n (X j.succ) = polynomial.C (X j) := by simp /-- The coefficient of `m` in the `i`-th coefficient of `fin_succ_equiv R n f` equals the coefficient of `finsupp.cons i m` in `f`. -/ lemma fin_succ_equiv_coeff_coeff (m : fin n →₀ ℕ) (f : mv_polynomial (fin (n + 1)) R) (i : ℕ) : coeff m (polynomial.coeff (fin_succ_equiv R n f) i) = coeff (m.cons i) f := begin induction f using mv_polynomial.induction_on' with j r p q hp hq generalizing i m, swap, { simp only [(fin_succ_equiv R n).map_add, polynomial.coeff_add, coeff_add, hp, hq] }, simp only [fin_succ_equiv_apply, coe_eval₂_hom, eval₂_monomial, ring_hom.coe_comp, prod_pow, polynomial.coeff_C_mul, coeff_C_mul, coeff_monomial, fin.prod_univ_succ, fin.cases_zero, fin.cases_succ, ← ring_hom.map_prod, ← ring_hom.map_pow], rw [← mul_boole, mul_comm (polynomial.X ^ j 0), polynomial.coeff_C_mul_X_pow], congr' 1, obtain rfl | hjmi := eq_or_ne j (m.cons i), { simpa only [cons_zero, cons_succ, if_pos rfl, monomial_eq, C_1, one_mul, prod_pow] using coeff_monomial m m (1:R), }, { simp only [hjmi, if_false], obtain hij | rfl := ne_or_eq i (j 0), { simp only [hij, if_false, coeff_zero] }, simp only [eq_self_iff_true, if_true], have hmj : m ≠ j.tail, { rintro rfl, rw [cons_tail] at hjmi, contradiction }, simpa only [monomial_eq, C_1, one_mul, prod_pow, finsupp.tail_apply, if_neg hmj.symm] using coeff_monomial m j.tail (1:R), } end lemma eval_eq_eval_mv_eval' (s : fin n → R) (y : R) (f : mv_polynomial (fin (n + 1)) R) : eval (fin.cons y s : fin (n + 1) → R) f = polynomial.eval y (polynomial.map (eval s) (fin_succ_equiv R n f)) := begin -- turn this into a def `polynomial.map_alg_hom` let φ : (mv_polynomial (fin n) R)[X] →ₐ[R] R[X] := { commutes' := λ r, by { convert polynomial.map_C _, exact (eval_C _).symm }, .. polynomial.map_ring_hom (eval s) }, show aeval (fin.cons y s : fin (n + 1) → R) f = (polynomial.aeval y).comp (φ.comp (fin_succ_equiv R n).to_alg_hom) f, congr' 2, apply mv_polynomial.alg_hom_ext, rw fin.forall_fin_succ, simp only [aeval_X, fin.cons_zero, alg_equiv.to_alg_hom_eq_coe, alg_hom.coe_comp, polynomial.coe_aeval_eq_eval, polynomial.map_C, alg_hom.coe_mk, ring_hom.to_fun_eq_coe, polynomial.coe_map_ring_hom, alg_equiv.coe_alg_hom, comp_app, fin_succ_equiv_apply, eval₂_hom_X', fin.cases_zero, polynomial.map_X, polynomial.eval_X, eq_self_iff_true, fin.cons_succ, fin.cases_succ, eval_X, polynomial.eval_C, implies_true_iff, and_self], end lemma coeff_eval_eq_eval_coeff (s' : fin n → R) (f : polynomial (mv_polynomial (fin n) R)) (i : ℕ) : polynomial.coeff (polynomial.map (eval s') f) i = eval s' (polynomial.coeff f i) := by simp only [polynomial.coeff_map] lemma support_coeff_fin_succ_equiv {f : mv_polynomial (fin (n + 1)) R} {i : ℕ} {m : fin n →₀ ℕ } : m ∈ (polynomial.coeff ((fin_succ_equiv R n) f) i).support ↔ (finsupp.cons i m) ∈ f.support := begin apply iff.intro, { intro h, simpa [←fin_succ_equiv_coeff_coeff] using h }, { intro h, simpa [mem_support_iff, ←fin_succ_equiv_coeff_coeff m f i] using h }, end lemma fin_succ_equiv_support (f : mv_polynomial (fin (n + 1)) R) : (fin_succ_equiv R n f).support = finset.image (λ m : fin (n + 1)→₀ ℕ, m 0) f.support := begin ext i, rw [polynomial.mem_support_iff, finset.mem_image, nonzero_iff_exists], split, { rintro ⟨m, hm⟩, refine ⟨cons i m, _, cons_zero _ _⟩, rw ← support_coeff_fin_succ_equiv, simpa using hm, }, { rintro ⟨m, h, rfl⟩, refine ⟨tail m, _⟩, rwa [← coeff, ← mem_support_iff, support_coeff_fin_succ_equiv, cons_tail] }, end lemma fin_succ_equiv_support' {f : mv_polynomial (fin (n + 1)) R} {i : ℕ} : finset.image (finsupp.cons i) (polynomial.coeff ((fin_succ_equiv R n) f) i).support = f.support.filter(λ m, m 0 = i) := begin ext m, rw [finset.mem_filter, finset.mem_image, mem_support_iff], conv_lhs { congr, funext, rw [mem_support_iff, fin_succ_equiv_coeff_coeff, ne.def] }, split, { rintros ⟨m',⟨h, hm'⟩⟩, simp only [←hm'], exact ⟨h, by rw cons_zero⟩ }, { intro h, use tail m, rw [← h.2, cons_tail], simp [h.1] } end lemma support_fin_succ_equiv_nonempty {f : mv_polynomial (fin (n + 1)) R} (h : f ≠ 0) : (fin_succ_equiv R n f).support.nonempty := begin by_contradiction c, simp only [finset.not_nonempty_iff_eq_empty, polynomial.support_eq_empty] at c, have t'' : (fin_succ_equiv R n f) ≠ 0, { let ii := (fin_succ_equiv R n).symm, have h' : f = 0 := calc f = ii (fin_succ_equiv R n f) : by simpa only [ii, ←alg_equiv.inv_fun_eq_symm] using ((fin_succ_equiv R n).left_inv f).symm ... = ii 0 : by rw c ... = 0 : by simp, simpa [h'] using h }, simpa [c] using h, end lemma degree_fin_succ_equiv {f : mv_polynomial (fin (n + 1)) R} (h : f ≠ 0) : (fin_succ_equiv R n f).degree = degree_of 0 f := begin have h' : (fin_succ_equiv R n f).support.sup (λ x , x) = degree_of 0 f, { rw [degree_of_eq_sup, fin_succ_equiv_support f, finset.sup_image] }, rw [polynomial.degree, ← h', finset.coe_sup_of_nonempty (support_fin_succ_equiv_nonempty h), finset.max_eq_sup_coe], end lemma nat_degree_fin_succ_equiv (f : mv_polynomial (fin (n + 1)) R) : (fin_succ_equiv R n f).nat_degree = degree_of 0 f := begin by_cases c : f = 0, { rw [c, (fin_succ_equiv R n).map_zero, polynomial.nat_degree_zero, degree_of_zero] }, { rw [polynomial.nat_degree, degree_fin_succ_equiv (by simpa only [ne.def]) ], simp }, end lemma degree_of_coeff_fin_succ_equiv (p : mv_polynomial (fin (n + 1)) R) (j : fin n) (i : ℕ) : degree_of j (polynomial.coeff (fin_succ_equiv R n p) i) ≤ degree_of j.succ p := begin rw [degree_of_eq_sup, degree_of_eq_sup, finset.sup_le_iff], intros m hm, rw ← finsupp.cons_succ j i m, convert finset.le_sup (support_coeff_fin_succ_equiv.1 hm), refl, end end end equiv end mv_polynomial
b40279d4725e8f2380bc5caf6e7d4884b17ec271
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Meta/Offset.lean
a18348857d1e4064b24a21651a614c7cda80252a
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,378
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.Data.LBool import Lean.Meta.InferType namespace Lean.Meta partial def evalNat : Expr → Option Nat | Expr.lit (Literal.natVal n) _ => pure n | Expr.mdata _ e _ => evalNat e | Expr.const `Nat.zero _ _ => pure 0 | e@(Expr.app _ a _) => do let fn := e.getAppFn match fn with | Expr.const c _ _ => let nargs := e.getAppNumArgs if c == `Nat.succ && nargs == 1 then let v ← evalNat a pure $ v+1 else if c == `Nat.add && nargs == 2 then let v₁ ← evalNat (e.getArg! 0) let v₂ ← evalNat (e.getArg! 1) pure $ v₁ + v₂ else if c == `Nat.sub && nargs == 2 then let v₁ ← evalNat (e.getArg! 0) let v₂ ← evalNat (e.getArg! 1) pure $ v₁ - v₂ else if c == `Nat.mul && nargs == 2 then let v₁ ← evalNat (e.getArg! 0) let v₂ ← evalNat (e.getArg! 1) pure $ v₁ * v₂ else if c == `Add.add && nargs == 4 then let v₁ ← evalNat (e.getArg! 2) let v₂ ← evalNat (e.getArg! 3) pure $ v₁ + v₂ else if c == `Sub.sub && nargs == 4 then let v₁ ← evalNat (e.getArg! 2) let v₂ ← evalNat (e.getArg! 3) pure $ v₁ - v₂ else if c == `Mul.mul && nargs == 4 then let v₁ ← evalNat (e.getArg! 2) let v₂ ← evalNat (e.getArg! 3) pure $ v₁ * v₂ else if c == `OfNat.ofNat && nargs == 3 then evalNat (e.getArg! 2) else none | _ => none | _ => none /- Quick function for converting `e` into `s + k` s.t. `e` is definitionally equal to `Nat.add s k`. -/ private partial def getOffsetAux : Expr → Bool → Option (Expr × Nat) | e@(Expr.app _ a _), top => let fn := e.getAppFn match fn with | Expr.const c _ _ => let nargs := e.getAppNumArgs if c == `Nat.succ && nargs == 1 then do let (s, k) ← getOffsetAux a false pure (s, k+1) else if c == `Nat.add && nargs == 2 then do let v ← evalNat (e.getArg! 1) let (s, k) ← getOffsetAux (e.getArg! 0) false pure (s, k+v) else if c == `Add.add && nargs == 4 then do let v ← evalNat (e.getArg! 3) let (s, k) ← getOffsetAux (e.getArg! 2) false pure (s, k+v) else if top then none else pure (e, 0) | _ => if top then none else pure (e, 0) | e, top => if top then none else pure (e, 0) private def getOffset (e : Expr) : Option (Expr × Nat) := getOffsetAux e true private partial def isOffset : Expr → Option (Expr × Nat) | e@(Expr.app _ a _) => let fn := e.getAppFn match fn with | Expr.const c _ _ => let nargs := e.getAppNumArgs if (c == `Nat.succ && nargs == 1) || (c == `Nat.add && nargs == 2) || (c == `Add.add && nargs == 4) then getOffset e else none | _ => none | _ => none private def isNatZero (e : Expr) : Bool := match evalNat e with | some v => v == 0 | _ => false private def mkOffset (e : Expr) (offset : Nat) : Expr := if offset == 0 then e else if isNatZero e then mkNatLit offset else mkAppB (mkConst `Nat.add) e (mkNatLit offset) def isDefEqOffset (s t : Expr) : MetaM LBool := let isDefEq (s t) : MetaM LBool := toLBoolM $ Meta.isExprDefEqAux s t match isOffset s with | some (s, k₁) => match isOffset t with | some (t, k₂) => -- s+k₁ =?= t+k₂ if k₁ == k₂ then isDefEq s t else if k₁ < k₂ then isDefEq s (mkOffset t (k₂ - k₁)) else isDefEq (mkOffset s (k₁ - k₂)) t | none => match evalNat t with | some v₂ => -- s+k₁ =?= v₂ if v₂ ≥ k₁ then isDefEq s (mkNatLit $ v₂ - k₁) else pure LBool.false | none => pure LBool.undef | none => match evalNat s with | some v₁ => match isOffset t with | some (t, k₂) => -- v₁ =?= t+k₂ if v₁ ≥ k₂ then isDefEq (mkNatLit $ v₁ - k₂) t else pure LBool.false | none => match evalNat t with | some v₂ => pure (v₁ == v₂).toLBool -- v₁ =?= v₂ | none => pure LBool.undef | none => pure LBool.undef end Lean.Meta
cb1689bca7a4bfc1f5c682d33af03a2e480505b7
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/alex_playground/uncurr2.lean
bef39e04e3352957199cf4eb81144aad0453b383
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
2,484
lean
import data.real.basic import tactic.interactive import order.liminf_limsup universe variables u v w x -- copied from current mathlib, but changed to support sorts. section uncurry variables {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} /-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ class has_uncurry (α : Sort*) (β : out_param Sort*) (γ : out_param Sort*) := (uncurry : α → (β → γ)) notation `↿`:max x:max := has_uncurry.uncurry x instance has_uncurry_base : has_uncurry (α → β) α β := ⟨id⟩ instance has_uncurry_induction [has_uncurry β γ δ] : has_uncurry (α → β) (Σ' (a : α), γ) δ := ⟨λ f p, ↿(f p.1) p.2⟩ -- My own addition for dependent products: -- instance has_uncurry_induction_dep {φ : α → Sort w} [s : ∀ a : α, has_uncurry β (φ a) δ] : -- has_uncurry (α → β) (Σ' (a : α), φ a) δ := -- ⟨λ f p, begin haveI := s p.1, exact ↿(f p.1) p.2 end⟩ instance has_uncurry_induction_dep {φ : α → Sort w} [∀ a : α, has_uncurry (φ a) γ δ] : has_uncurry (Π (a : α), φ a) (Σ' (a : α), γ) δ := ⟨λ f p, ↿(f p.1) p.2⟩ end uncurry -- merge objfun and feasable: def solution {α β γ : Sort*} [has_uncurry α β γ] [has_le γ] (objfun : α) := { x : β // ∀ y : β, ↿objfun y ≤ ↿objfun x } notation `over ` binders ` maximize ` f:(scoped Q, Q) := solution f -- class instantiation isnt smart enough: #check @solution _ _ _ (@has_uncurry_induction_dep _ _ _ (λ (x : ℝ), x ≥ 0 → ℝ) (λ a, _)) _ (λ (x : ℝ), λ (h : x ≥ 0), x) #check @solution _ _ _ _ _ (λ (x : ℝ), λ (h : x ≥ 0), x) class myinhabited (α : Sort u) (β : out_param Sort*) := (default : α) instance : myinhabited ℝ ℝ := { default := 0 } instance foo {α : Sort u} {β : Sort v} {φ : α → Sort w} [∀ n : α, myinhabited (φ n) β] : myinhabited (Π n, φ n) β := { default := (λ n : α, @myinhabited.default (φ n) β _) } #check @myinhabited.default (Π n : ℕ, ℝ) ℝ _ def mysolution : over (x y : ℝ) (h : x ≤ 0 ∧ y ≤ 0) maximize x + y := begin use (0, 0), split, split, simp, simp, intros y hy, change y.1 + y.2 ≤ 0 + 0, change y.1 ≤ 0 ∧ y.2 ≤ 0 at hy, linarith, end #print mysolution
407c8c1cf83bc5975be898660aabc1d43213991e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Tactic/ElabTerm.lean
f8d23ff54989fa04fd5ee384618d8799fd0b501c
[ "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
18,109
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Constructor import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Rename import Lean.Elab.Tactic.Basic import Lean.Elab.SyntheticMVars namespace Lean.Elab.Tactic open Meta /-! # `elabTerm` for Tactics and basic tactics that use it. -/ /-- Runs a term elaborator inside a tactic. This function ensures that term elaboration fails when backtracking, i.e., in `first| tac term | other`. -/ def runTermElab (k : TermElabM α) (mayPostpone := false) : TacticM α := do /- If error recovery is disabled, we disable `Term.withoutErrToSorry` -/ if (← read).recover then go else Term.withoutErrToSorry go where go := k <* Term.synthesizeSyntheticMVars (mayPostpone := mayPostpone) /-- Elaborate `stx` in the current `MVarContext`. If given, the `expectedType` will be used to help elaboration but not enforced (use `elabTermEnsuringType` to enforce an expected type). -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := withRef stx do instantiateMVars <| ← runTermElab (mayPostpone := mayPostpone) do Term.elabTerm stx expectedType? /-- Elaborate `stx` in the current `MVarContext`. If given, the `expectedType` will be used to help elaboration and then a `TypeMismatchError` will be thrown if the elaborated type doesn't match. -/ def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do let e ← elabTerm stx expectedType? mayPostpone -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here. match expectedType? with | none => return e | some expectedType => let eType ← inferType e -- We allow synthetic opaque metavars to be assigned in the following step since the `isDefEq` is not really -- part of the elaboration, but part of the tactic. See issue #492 unless (← withAssignableSyntheticOpaque <| isDefEq eType expectedType) do Term.throwTypeMismatchError none expectedType eType e return e /-- Try to close main goal using `x target`, where `target` is the type of the main goal. -/ def closeMainGoalUsing (x : Expr → TacticM Expr) (checkUnassigned := true) : TacticM Unit := withMainContext do closeMainGoal (checkUnassigned := checkUnassigned) (← x (← getMainTarget)) def logUnassignedAndAbort (mvarIds : Array MVarId) : TacticM Unit := do if (← Term.logUnassignedUsingErrorInfos mvarIds) then throwAbortTactic def filterOldMVars (mvarIds : Array MVarId) (mvarCounterSaved : Nat) : MetaM (Array MVarId) := do let mctx ← getMCtx return mvarIds.filter fun mvarId => (mctx.getDecl mvarId |>.index) >= mvarCounterSaved @[builtin_tactic «exact»] def evalExact : Tactic := fun stx => match stx with | `(tactic| exact $e) => closeMainGoalUsing (checkUnassigned := false) fun type => do let mvarCounterSaved := (← getMCtx).mvarCounter let r ← elabTermEnsuringType e type logUnassignedAndAbort (← filterOldMVars (← getMVars r) mvarCounterSaved) return r | _ => throwUnsupportedSyntax def sortMVarIdArrayByIndex [MonadMCtx m] [Monad m] (mvarIds : Array MVarId) : m (Array MVarId) := do let mctx ← getMCtx return mvarIds.qsort fun mvarId₁ mvarId₂ => let decl₁ := mctx.getDecl mvarId₁ let decl₂ := mctx.getDecl mvarId₂ if decl₁.index != decl₂.index then decl₁.index < decl₂.index else Name.quickLt mvarId₁.name mvarId₂.name def sortMVarIdsByIndex [MonadMCtx m] [Monad m] (mvarIds : List MVarId) : m (List MVarId) := return (← sortMVarIdArrayByIndex mvarIds.toArray).toList /-- Execute `k`, and collect new "holes" in the resulting expression. -/ def withCollectingNewGoalsFrom (k : TacticM Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := /- When `allowNaturalHoles = true`, unassigned holes should become new metavariables, including `_`s. Thus, we set `holesAsSynthethicOpaque` to true if it is not already set to `true`. See issue #1681. We have the tactic ``` `refine' (fun x => _) ``` If we create a natural metavariable `?m` for `_` with type `Nat`, then when we try to abstract `x`, a new metavariable `?n` with type `Nat -> Nat` is created, and we assign `?m := ?n x`, and the resulting term is `fun x => ?n x`. Then, `getMVarsNoDelayed` would return `?n` as a new goal which would be confusing since it has type `Nat -> Nat`. -/ if allowNaturalHoles then withTheReader Term.Context (fun ctx => { ctx with holesAsSyntheticOpaque := ctx.holesAsSyntheticOpaque || allowNaturalHoles }) do /- We also enable the assignment of synthetic metavariables, otherwise we will fail to elaborate terms such as `f _ x` where `f : (α : Type) → α → α` and `x : A`. IMPORTANT: This is not a perfect solution. For example, `isDefEq` will be able assign metavariables associated with `by ...`. This should not be an immediate problem since this feature is only used to implement `refine'`. If it becomes an issue in practice, we should add a new kind of opaque metavariable for `refine'`, and mark the holes created using `_` with it, and have a flag that allows us to assign this kind of metavariable, but prevents us from assigning metavariables created by the `by ...` notation. -/ withAssignableSyntheticOpaque go else go where go := do let mvarCounterSaved := (← getMCtx).mvarCounter let val ← k let newMVarIds ← getMVarsNoDelayed val /- ignore let-rec auxiliary variables, they are synthesized automatically later -/ let newMVarIds ← newMVarIds.filterM fun mvarId => return !(← Term.isLetRecAuxMVar mvarId) /- The following `unless … do` block guards against unassigned natural mvarids created during `k` in the case that `allowNaturalHoles := false`. If we pass this block without aborting, we can be assured that `newMVarIds` does not contain unassigned natural mvars created during `k`. Note that in all cases we must allow `newMVarIds` to contain unassigned natural mvars which were created *before* `k`; this is the purpose of `mvarCounterSaved`, which lets us distinguish mvars created before `k` from those created during and after. See issue #2434. -/ unless allowNaturalHoles do let naturalMVarIds ← newMVarIds.filterM fun mvarId => return (← mvarId.getKind).isNatural let naturalMVarIds ← filterOldMVars naturalMVarIds mvarCounterSaved logUnassignedAndAbort naturalMVarIds /- We sort the new metavariable ids by index to ensure the new goals are ordered using the order the metavariables have been created. See issue #1682. Potential problem: if elaboration of subterms is delayed the order the new metavariables are created may not match the order they appear in the `.lean` file. We should tell users to prefer tagged goals. -/ let newMVarIds ← sortMVarIdsByIndex newMVarIds.toList tagUntaggedGoals (← getMainTag) tagSuffix newMVarIds return (val, newMVarIds) def elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := do withCollectingNewGoalsFrom (elabTermEnsuringType stx expectedType?) tagSuffix allowNaturalHoles /-- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned "natural" metavariables. Recall that "natutal" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be filled by typing constraints. "Synthetic" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/ def refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do withMainContext do let (val, mvarIds') ← elabTermWithHoles stx (← getMainTarget) tagSuffix allowNaturalHoles let mvarId ← getMainGoal let val ← instantiateMVars val unless val == mkMVar mvarId do if val.findMVar? (· == mvarId) matches some _ then throwError "'refine' tactic failed, value{indentExpr val}\ndepends on the main goal metavariable '{mkMVar mvarId}'" mvarId.assign val replaceMainGoal mvarIds' @[builtin_tactic «refine»] def evalRefine : Tactic := fun stx => match stx with | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false) | _ => throwUnsupportedSyntax @[builtin_tactic «refine'»] def evalRefine' : Tactic := fun stx => match stx with | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true) | _ => throwUnsupportedSyntax @[builtin_tactic «specialize»] def evalSpecialize : Tactic := fun stx => withMainContext do match stx with | `(tactic| specialize $e:term) => let (e, mvarIds') ← elabTermWithHoles e none `specialize (allowNaturalHoles := true) let h := e.getAppFn if h.isFVar then let localDecl ← h.fvarId!.getDecl let mvarId ← (← getMainGoal).assert localDecl.userName (← inferType e).headBeta e let (_, mvarId) ← mvarId.intro1P let mvarId ← mvarId.tryClear h.fvarId! replaceMainGoal (mvarIds' ++ [mvarId]) else throwError "'specialize' requires a term of the form `h x_1 .. x_n` where `h` appears in the local context" | _ => throwUnsupportedSyntax /-- Given a tactic ``` apply f ``` we want the `apply` tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. A similar method is also used in Lean 3. This method is useful when applying lemmas such as: ``` theorem infLeRight {s t : Set α} : s ⊓ t ≤ t ``` where `s ≤ t` here is defined as ``` ∀ {x : α}, x ∈ s → x ∈ t ``` -/ def elabTermForApply (stx : Syntax) (mayPostpone := true) : TacticM Expr := do if stx.isIdent then match (← Term.resolveId? stx (withInfo := true)) with | some e => return e | _ => pure () /- By disabling the "error recovery" (and consequently "error to sorry") feature, we make sure an `apply e` fails without logging an error message. The motivation is that `apply` is frequently used when writing tactic such as ``` cases h <;> intro h' <;> first | apply t[h'] | .... ``` Here the type of `h'` may be different in each case, and the term `t[h']` containing `h'` may even fail to be elaborated in some cases. When this happens we want the tactic to fail without reporting any error to the user, and the next tactic is tried. A drawback of disabling "error to sorry" is that there is no error recovery after the error is thrown, and features such as auto-completion are affected. By disabling "error to sorry", we also limit ourselves to at most one error at `t[h']`. By disabling "error to sorry", we also miss the opportunity to catch mistakes is tactic code such as `first | apply nonsensical-term | assumption` This should not be a big problem for the `apply` tactic since we usually provide small terms there. Note that we do not disable "error to sorry" at `exact` and `refine` since they are often used to elaborate big terms, and we do want error recovery there, and we want to see the error messages. We should probably provide options for allowing users to control this behavior. see issue #1037 More complex solution: - We do not disable "error to sorry" - We elaborate term and check whether errors were produced - If there are other tactic braches and there are errors, we remove the errors from the log, and throw a new error to force the tactic to backtrack. -/ withoutRecover <| elabTerm stx none mayPostpone def getFVarId (id : Syntax) : TacticM FVarId := withRef id do -- use apply-like elaboration to suppress insertion of implicit arguments let e ← withMainContext do elabTermForApply id (mayPostpone := false) match e with | Expr.fvar fvarId => return fvarId | _ => throwError "unexpected term '{e}'; expected single reference to variable" def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do withMainContext do ids.mapM getFVarId def evalApplyLikeTactic (tac : MVarId → Expr → MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do withMainContext do let mut val ← instantiateMVars (← elabTermForApply e) if val.isMVar then /- If `val` is a metavariable, we force the elaboration of postponed terms. This is useful for producing a more useful error message in examples such as ``` example (h : P) : P ∨ Q := by apply .inl ``` Recall that `apply` elaborates terms without using the expected type, and the notation `.inl` requires the expected type to be available. -/ Term.synthesizeSyntheticMVarsNoPostponing val ← instantiateMVars val let mvarIds' ← tac (← getMainGoal) val Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' @[builtin_tactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx => match stx with | `(tactic| apply $e) => evalApplyLikeTactic (·.apply) e | _ => throwUnsupportedSyntax @[builtin_tactic Lean.Parser.Tactic.constructor] def evalConstructor : Tactic := fun _ => withMainContext do let mvarIds' ← (← getMainGoal).constructor Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' @[builtin_tactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx => withReducible <| evalTactic stx[1] @[builtin_tactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx => withReducibleAndInstances <| evalTactic stx[1] @[builtin_tactic Lean.Parser.Tactic.withUnfoldingAll] def evalWithUnfoldingAll : Tactic := fun stx => withTransparency TransparencyMode.all <| evalTactic stx[1] /-- Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable. Note that, the main goal is updated when `Meta.assert` is used in the second case. -/ def elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId := withMainContext do let e ← elabTerm stx none match e with | .fvar fvarId => pure fvarId | _ => let type ← inferType e let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do let mvarId ← getMainGoal let (fvarId, mvarId) ← liftMetaM do let mvarId ← mvarId.assert userName type e Meta.intro1Core mvarId preserveBinderNames replaceMainGoal [mvarId] return fvarId match userName? with | none => intro `h false | some userName => intro userName true @[builtin_tactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx => match stx with | `(tactic| rename $typeStx:term => $h:ident) => do withMainContext do /- Remark: we also use `withoutRecover` to make sure `elabTerm` does not succeed using `sorryAx`, and we get `"failed to find ..."` which will not be logged because it contains synthetic sorry's -/ let fvarId ← withoutModifyingState <| withNewMCtxDepth <| withoutRecover do let type ← elabTerm typeStx none (mayPostpone := true) let fvarId? ← (← getLCtx).findDeclRevM? fun localDecl => do if (← isDefEq type localDecl.type) then return localDecl.fvarId else return none match fvarId? with | none => throwError "failed to find a hypothesis with type{indentExpr type}" | some fvarId => return fvarId replaceMainGoal [← (← getMainGoal).rename fvarId h.getId] | _ => throwUnsupportedSyntax /-- Make sure `expectedType` does not contain free and metavariables. It applies zeta-reduction to eliminate let-free-vars. -/ private def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do let mut expectedType ← instantiateMVars expectedType if expectedType.hasFVar then expectedType ← zetaReduce expectedType if expectedType.hasFVar || expectedType.hasMVar then throwError "expected type must not contain free or meta variables{indentExpr expectedType}" return expectedType @[builtin_tactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun _ => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let d ← instantiateMVars d let r ← withDefault <| whnf d unless r.isConstOf ``true do throwError "failed to reduce to 'true'{indentExpr r}" let s := d.appArg! -- get instance from `d` let rflPrf ← mkEqRefl (toExpr true) return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s rflPrf private def mkNativeAuxDecl (baseName : Name) (type value : Expr) : TermElabM Name := do let auxName ← Term.mkAuxName baseName let decl := Declaration.defnDecl { name := auxName, levelParams := [], type, value hints := .abbrev safety := .safe } addDecl decl compileDecl decl pure auxName @[builtin_tactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun _ => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let auxDeclName ← mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d let rflPrf ← mkEqRefl (toExpr true) let s := d.appArg! -- get instance from `d` return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s <| mkApp3 (Lean.mkConst ``Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf end Lean.Elab.Tactic
c5af53b9e1050936b3b13ec1ce943dd5733a56e6
3618c6e11aa822fd542440674dfb9a7b9921dba0
/src/coprod/pre.lean
436bb7fec15915908074ca454fd4af0fa119e135
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
21,831
lean
import data.list.chain import data.sigma.basic variables {ι : Type*} {M : ι → Type*} {G : ι → Type*} {N : Type*} variables [Π i, monoid (M i)] [Π i, group (G i)] [monoid N] open list function namespace coprod.pre def reduced (l : list (Σ i, M i)) : Prop := l.chain' (λ a b, a.1 ≠ b.1) ∧ ∀ a : Σ i, M i, a ∈ l → a.2 ≠ 1 @[simp] lemma reduced_nil : reduced ([] : list (Σ i, M i)) := ⟨list.chain'_nil, λ _, false.elim⟩ lemma reduced_singleton {i : Σ i, M i} (hi : i.2 ≠ 1) : reduced [i] := ⟨by simp, begin cases i with i a, rintros ⟨j, b⟩, simp only [and_imp, ne.def, mem_singleton], rintro rfl h₂, simp * at * end⟩ lemma reduced_of_reduced_cons {i : Σ i, M i} {l : list (Σ i, M i)} (h : reduced (i :: l)) : reduced l := ⟨(list.chain'_cons'.1 h.1).2, λ b hb, h.2 _ (mem_cons_of_mem _ hb)⟩ lemma reduced_cons_of_reduced_cons {i : ι} {a b : M i} {l : list (Σ i, M i)} (h : reduced (⟨i, a⟩ :: l)) (hb : b ≠ 1) : reduced (⟨i, b⟩ :: l) := ⟨chain'_cons'.2 (chain'_cons'.1 h.1), begin rintros ⟨k, c⟩ hk, cases (mem_cons_iff _ _ _).1 hk with hk hk, { simp only at hk, rcases hk with ⟨rfl, h⟩, simp * at * }, { exact h.2 _ (mem_cons_of_mem _ hk) } end⟩ lemma reduced_cons_cons {i j : ι} {a : M i} {b : M j} {l : list (Σ i, M i)} (hij : i ≠ j) (ha : a ≠ 1) (hbl : reduced (⟨j, b⟩ :: l)) : reduced (⟨i, a⟩ :: ⟨j, b⟩ :: l) := ⟨chain'_cons.2 ⟨hij, hbl.1⟩, begin rintros ⟨k, c⟩ hk, cases (mem_cons_iff _ _ _).1 hk with hk hk, { simp only at hk, rcases hk with ⟨rfl, h⟩, simp * at * }, { exact hbl.2 _ hk } end⟩ lemma reduced_reverse {l : list (Σ i, M i)} (h : reduced l) : reduced l.reverse := ⟨chain'_reverse.2 $ by {convert h.1, simp [function.funext_iff, eq_comm] }, by simpa using h.2⟩ @[simp] lemma reduced_reverse_iff {l : list (Σ i, M i)} : reduced l.reverse ↔ reduced l := ⟨λ h, by convert reduced_reverse h; simp, reduced_reverse⟩ lemma reduced_of_reduced_append_right : ∀ {l₁ l₂ : list (Σ i, M i)} (h : reduced (l₁ ++ l₂)), reduced l₂ | [] l₂ h := h | (i::l₁) l₂ h := begin rw cons_append at h, exact reduced_of_reduced_append_right (reduced_of_reduced_cons h) end lemma reduced_of_reduced_append_left {l₁ l₂ : list (Σ i, M i)} (h : reduced (l₁ ++ l₂)) : reduced l₁ := begin rw [← reduced_reverse_iff], rw [← reduced_reverse_iff, reverse_append] at h, exact reduced_of_reduced_append_right h end variables {ι} [decidable_eq ι] {M} [Π i, decidable_eq (M i)] def rcons : (Σ i, M i) → list (Σ i, M i) → list (Σ i, M i) | i [] := [i] | i (j::l) := if hij : i.1 = j.1 then let c := i.2 * cast (congr_arg M hij).symm j.2 in if c = 1 then l else ⟨i.1, c⟩ :: l else i::j::l def reduce : list (Σ i, M i) → list (Σ i, M i) | [] := [] | (i :: l) := if i.2 = 1 then reduce l else rcons i (reduce l) @[simp] lemma reduce_nil : reduce ([] : list (Σ i, M i)) = [] := rfl lemma reduce_cons (i : Σ i, M i) (l : list (Σ i, M i)) : reduce (i::l) = if i.2 = 1 then reduce l else rcons i (reduce l) := rfl lemma reduced_rcons : ∀ {i : Σ i, M i} {l : list (Σ i, M i)}, i.2 ≠ 1 → reduced l → reduced (rcons i l) | ⟨i, a⟩ [] hi h := ⟨list.chain'_singleton _, begin rintros ⟨j, b⟩ hj, simp only [rcons, list.mem_singleton] at hj, rcases hj with ⟨rfl, h⟩, simp * at * end⟩ | ⟨i, a⟩ (⟨j, b⟩ :: l) hi h := begin simp [rcons], split_ifs, { exact reduced_of_reduced_cons h }, { dsimp only at h_1, subst h_1, exact reduced_cons_of_reduced_cons h h_2 }, { exact reduced_cons_cons h_1 hi h } end lemma reduced_reduce : ∀ l : list (Σ i, M i), reduced (reduce l) | [] := reduced_nil | (a::l) := begin rw reduce, split_ifs, { exact reduced_reduce l }, { exact reduced_rcons h (reduced_reduce l) } end lemma rcons_eq_cons : ∀ {i : Σ i, M i} {l : list (Σ i, M i)}, reduced (i :: l) → rcons i l = i :: l | i [] h := rfl | i (j::l) h := dif_neg (chain'_cons.1 h.1).1 lemma rcons_reduce_eq_reduce_cons : ∀ {i : Σ i, M i} {l : list (Σ i, M i)}, i.2 ≠ 1 → rcons i (reduce l) = reduce (i :: l) | a [] ha := by simp [rcons, reduce, ha] | a (b::l) ha := begin rw [reduce], split_ifs, { rw [reduce, if_neg ha, reduce, if_pos h] }, { rw [reduce, if_neg ha, reduce, if_neg h] } end lemma reduce_eq_self_of_reduced : ∀ {l : list (Σ i, M i)}, reduced l → reduce l = l | [] h := rfl | (a::l) h := by rw [← rcons_reduce_eq_reduce_cons (h.2 a (mem_cons_self _ _)), reduce_eq_self_of_reduced (reduced_of_reduced_cons h), rcons_eq_cons h] lemma rcons_eq_reduce_cons {i : Σ i, M i} {l : list (Σ i, M i)} (ha : i.2 ≠ 1) (hl : reduced l) : rcons i l = reduce (i :: l) := by rw [← rcons_reduce_eq_reduce_cons ha, reduce_eq_self_of_reduced hl] @[simp] lemma reduce_reduce (l : list (Σ i, M i)) : reduce (reduce l) = reduce l := reduce_eq_self_of_reduced (reduced_reduce l) @[simp] lemma reduce_cons_reduce_eq_reduce_cons (i : Σ i, M i) (l : list (Σ i, M i)) : reduce (i :: reduce l) = reduce (i :: l) := if ha : i.2 = 1 then by rw [reduce, if_pos ha, reduce, if_pos ha, reduce_reduce] else by rw [← rcons_reduce_eq_reduce_cons ha, ← rcons_reduce_eq_reduce_cons ha, reduce_reduce] lemma length_rcons_le : ∀ (i : Σ i, M i) (l : list (Σ i, M i)), (rcons i l).length ≤ (i::l : list _).length | i [] := le_refl _ | ⟨i, a⟩ (⟨j, b⟩::l) := begin simp [rcons], split_ifs, { repeat { constructor } }, { simp }, { simp } end lemma length_reduce_le : ∀ (l : list (Σ i, M i)), (reduce l).length ≤ l.length | [] := le_refl _ | [a] := by { simp [reduce], split_ifs; simp [rcons] } | (a::b::l) := begin simp only [reduce, rcons], split_ifs, { exact le_trans (length_reduce_le _) (le_trans (nat.le_succ _) (nat.le_succ _)) }, { exact le_trans (length_rcons_le _ _) (nat.succ_le_succ (le_trans (length_reduce_le _) (nat.le_succ _))) }, { exact le_trans (length_rcons_le _ _) (nat.succ_le_succ (le_trans (length_reduce_le _) (nat.le_succ _))) }, { exact le_trans (length_rcons_le _ _) (nat.succ_le_succ (le_trans (length_rcons_le _ _) (nat.succ_le_succ (length_reduce_le _)))) } end lemma length_rcons_lt_or_eq_rcons : ∀ (i : Σ i, M i) (l : list (Σ i, M i)), (rcons i l).length < (i :: l : list _).length ∨ rcons i l = (i::l) | i [] := or.inr rfl | i (j::l) := begin simp only [rcons], split_ifs, { exact or.inl (nat.lt_succ_of_le (nat.le_succ _)) }, { exact or.inl (nat.lt_succ_self _) }, { simp } end lemma length_reduce_lt_or_eq_reduce : ∀ (l : list (Σ i, M i)), (reduce l).length < l.length ∨ reduce l = l | [] := or.inr rfl | (i::l) := begin simp only [reduce], split_ifs, { exact or.inl (nat.lt_succ_of_le (length_reduce_le _)) }, { cases length_rcons_lt_or_eq_rcons i (reduce l) with h h, { exact or.inl (lt_of_lt_of_le h (nat.succ_le_succ (length_reduce_le _))) }, { rw h, cases length_reduce_lt_or_eq_reduce l with h h, { exact or.inl (nat.succ_lt_succ h) }, { rw h, right, refl } } } end lemma rcons_append : ∀ {i j : Σ i, M i} {l₁ l₂ : list (Σ i, M i)}, rcons i ((j::l₁) ++ l₂) = rcons i (j::l₁) ++ l₂ | i j [] l₂ := begin simp [rcons], split_ifs; simp end | a b (c::l₁) l₂ := begin rw [cons_append, rcons], dsimp, split_ifs, { simp [rcons, *] }, { simp [rcons, *] }, { simp [rcons, *] } end lemma rcons_rcons_of_mul_eq_one {i : ι} {a b : M i} : ∀ {l : list (Σ i, M i)}, a * b = 1 → reduced l → rcons ⟨i, a⟩ (rcons ⟨i, b⟩ l) = l | [] hab hl := by simp [rcons, cast, hab] | (⟨j, c⟩::l) hab hl := begin simp only [rcons], split_ifs, { dsimp only at h, subst h, rw [← rcons_eq_cons hl, left_inv_eq_right_inv hab h_1, cast_eq] }, { dsimp only at h, subst h, simp only [rcons, dif_pos rfl], rw [cast_eq, cast_eq, if_neg, ← mul_assoc, hab, one_mul], { rw [← mul_assoc, hab, one_mul], exact hl.2 ⟨i, c⟩ (mem_cons_self _ _) } }, { rw [rcons, dif_pos rfl, cast_eq], dsimp, rw [if_pos hab] } end lemma rcons_rcons_of_mul_ne_one {i : ι} {a b : M i} : ∀ {l : list (Σ i, M i)}, a * b ≠ 1 → a ≠ 1 → reduced l → rcons ⟨i, a⟩ (rcons ⟨i, b⟩ l) = rcons ⟨i, a * b⟩ l | [] hab ha hl := by simp [rcons, hab] | [⟨j, c⟩] hab ha hl := begin simp only [rcons], split_ifs, { rw [mul_assoc, h_1, mul_one] at h_2, exact (ha h_2).elim }, { simp [rcons, mul_assoc, h_1] }, { simp only [rcons, ← mul_assoc, *, dif_pos rfl, if_pos rfl, cast_eq] }, { dsimp only at h, subst h, simp only [rcons, dif_pos rfl, ← mul_assoc, cast_eq, *] at *, simp, }, { simp [rcons, if_neg hab, if_pos rfl] } end | (⟨j, c⟩::⟨k, d⟩::l) hab ha hl := begin have hjk : j ≠ k, from (chain'_cons.1 hl.1).1, dsimp only [rcons], split_ifs, { rw [mul_assoc, h_1, mul_one] at h_2, exact (ha h_2).elim }, { dsimp [rcons], subst h, simp [*, rcons, mul_assoc] at * }, { simp [*, rcons, ← mul_assoc] at * }, { simp [*, rcons, ← mul_assoc] }, { simp [*, rcons] } end lemma reduce_rcons : ∀ {i : Σ i, M i} (l : list (Σ i, M i)), i.2 ≠ 1 → reduce (rcons i l) = rcons i (reduce l) | i [] hi := by simp [rcons, reduce, hi] | ⟨i, a⟩ [⟨j, b⟩] ha := begin replace ha : a ≠ 1 := ha, dsimp only [reduce, rcons], by_cases hij : i = j, { subst hij, split_ifs; simp [*, reduce, rcons] at * }, { simp [hij, reduce, rcons, ha] } end | ⟨i, a⟩ (⟨j, b⟩::l) ha := begin dsimp only [rcons], split_ifs, { subst h, rw [cast_eq] at h_1, rw [reduce, if_neg, rcons_rcons_of_mul_eq_one h_1 (reduced_reduce _)], { refine λ hb : b = 1, _, rw [hb, mul_one] at h_1, exact ha h_1 } }, { subst h, rw [reduce, if_neg h_1, reduce], split_ifs, { erw [cast_eq, show b = 1, from h, mul_one] }, { rw cast_eq at h_1, rw [rcons_rcons_of_mul_ne_one h_1 ha (reduced_reduce l), cast_eq], } }, { rw [rcons_eq_reduce_cons ha (reduced_reduce _), reduce_cons_reduce_eq_reduce_cons] } end lemma reduce_cons_cons_of_mul_eq_one {l : list (Σ i, M i)} {i : ι} {a b : M i} (ha : a ≠ 1) (hb : b ≠ 1) (hab : a * b = 1) : reduce (⟨i, a⟩ :: ⟨i, b⟩ :: l) = reduce l := by rw [reduce, if_neg ha, reduce, if_neg hb, rcons_rcons_of_mul_eq_one hab (reduced_reduce _)] lemma reduce_cons_cons_of_mul_ne_one {l : list (Σ i, M i)} {i : ι} {a b : M i} (ha : a ≠ 1) (hab : a * b ≠ 1) : reduce (⟨i, a⟩ :: ⟨i, b⟩ :: l) = reduce (⟨i, a * b⟩ :: l) := begin rw [reduce, if_neg ha, reduce], split_ifs, { rw [rcons_eq_reduce_cons (show (⟨i, a⟩ : Σ i, M i).snd ≠ 1, from ha) (reduced_reduce _), show b = 1, from h, mul_one, reduce_cons_reduce_eq_reduce_cons] }, { rw [rcons_rcons_of_mul_ne_one hab ha (reduced_reduce _), rcons_eq_reduce_cons (show (⟨i, a * b⟩ : Σ i, M i).snd ≠ 1, from hab : _) (reduced_reduce _), reduce_cons_reduce_eq_reduce_cons] } end @[simp] lemma reduce_reduce_append_eq_reduce_append : ∀ (l₁ l₂ : list (Σ i, M i)), reduce (reduce l₁ ++ l₂) = reduce (l₁ ++ l₂) | [] l₂ := rfl | (a::l₁) l₂ := begin simp only [reduce, cons_append], split_ifs with ha ha, { exact reduce_reduce_append_eq_reduce_append _ _ }, { rw [← reduce_reduce_append_eq_reduce_append l₁ l₂], induction h : reduce l₁, { simp [rcons, rcons_eq_reduce_cons ha (reduced_reduce _)] }, { rw [← rcons_append, reduce_rcons _ ha] } } end @[simp] lemma reduce_append_reduce_eq_reduce_append : ∀ (l₁ l₂ : list (Σ i, M i)), reduce (l₁ ++ reduce l₂) = reduce (l₁ ++ l₂) | [] l₂ := by simp | (a::l₁) l₂ := by rw [cons_append, ← reduce_cons_reduce_eq_reduce_cons, reduce_append_reduce_eq_reduce_append, reduce_cons_reduce_eq_reduce_cons, cons_append] lemma reduced_iff_reduce_eq_self {l : list (Σ i, M i)} : reduced l ↔ reduce l = l := ⟨reduce_eq_self_of_reduced, λ h, h ▸ reduced_reduce l⟩ lemma reduced_append_overlap {l₁ l₂ l₃ : list (Σ i, M i)} (h₁ : reduced (l₁ ++ l₂)) (h₂ : reduced (l₂ ++ l₃)) (hn : l₂ ≠ []): reduced (l₁ ++ l₂ ++ l₃) := ⟨chain'.append_overlap h₁.1 h₂.1 hn, λ i hi, (mem_append.1 hi).elim (h₁.2 _) (λ hi, h₂.2 _ (mem_append_right _ hi))⟩ /-- `mul_aux` returns `reduce (l₁.reverse ++ l₂)` -/ def mul_aux : Π (l₁ l₂ : list (Σ i, M i)), list (Σ i, M i) | [] l₂ := l₂ | (i::l₁) [] := reverse (i :: l₁) | (i::l₁) (j::l₂) := if hij : i.1 = j.1 then let c := i.2 * cast (congr_arg M hij).symm j.2 in if c = 1 then mul_aux l₁ l₂ else l₁.reverse_core (⟨i.1, c⟩::l₂) else l₁.reverse_core (i::j::l₂) @[simp] lemma mul_aux_nil (l : list (Σ i, M i)) : mul_aux l [] = l.reverse := by cases l; refl lemma mul_aux_eq_reduce_append : ∀ {l₁ l₂: list (Σ i, M i)}, reduced l₁ → reduced l₂ → mul_aux l₁ l₂ = reduce (l₁.reverse ++ l₂) | [] l₂ := λ h₁ h₂, by clear_aux_decl; simp [mul_aux, reduce_eq_self_of_reduced, *] | (i::hd) [] := λ h₁ h₂, by rw [mul_aux, append_nil, reduce_eq_self_of_reduced (reduced_reverse h₁)] | (⟨i,a⟩::l₁) (⟨j,b⟩::l₂) := λ h₁ h₂, begin simp only [mul_aux], dsimp only, have ha : a ≠ 1, from h₁.2 ⟨i, a⟩ (by simp), have hb : b ≠ 1, from h₂.2 ⟨j, b⟩ (list.mem_cons_self _ _), rcases decidable.em (i = j) with ⟨rfl, hij⟩, { rw [dif_pos rfl, cast_eq], split_ifs, { have hrl₁ : reduced l₁, { exact reduced_of_reduced_cons h₁ }, have hrl₂ : reduced l₂, from reduced_of_reduced_cons h₂, rw [mul_aux_eq_reduce_append hrl₁ hrl₂, reverse_cons, append_assoc, cons_append, nil_append, ← reduce_append_reduce_eq_reduce_append _ (_ :: _), reduce_cons_cons_of_mul_eq_one ha hb h_1, reduce_append_reduce_eq_reduce_append] }, { have hrl₁ :reduced (l₁.reverse ++ [⟨i, a * b⟩]), { rw [← reduced_reverse_iff, reverse_append, reverse_reverse, reverse_singleton, singleton_append], exact reduced_cons_of_reduced_cons h₁ h_1 }, have hrl₂ :reduced ([⟨i, a * b⟩] ++ l₂), { rw [singleton_append], exact reduced_cons_of_reduced_cons h₂ h_1 }, simp only [reverse_cons, singleton_append, append_assoc, reverse_core_eq], rw [← reduce_append_reduce_eq_reduce_append, reduce_cons_cons_of_mul_ne_one ha h_1, reduce_append_reduce_eq_reduce_append, ← singleton_append, ← append_assoc], exact (reduce_eq_self_of_reduced (reduced_append_overlap hrl₁ hrl₂ (by simp))).symm } }, { suffices : reduce (l₁.reverse ++ [⟨i, a⟩, ⟨j, b⟩] ++ l₂) = l₁.reverse ++ [⟨i, a⟩, ⟨j, b⟩] ++ l₂, { simpa [eq_comm, dif_neg h, reverse_core_eq] }, have hrl₁ : reduced (l₁.reverse ++ [⟨i, a⟩, ⟨j, b⟩]), { rw [← reduced_reverse_iff], simp only [reverse_append, reverse_cons, cons_append, reverse_nil, nil_append, reverse_reverse], refine reduced_cons_cons (ne.symm h) hb h₁ }, have hrl₂ : reduced ([⟨i, a⟩, ⟨j, b⟩] ++ l₂), { simp only [cons_append, nil_append], refine reduced_cons_cons h ha h₂ }, exact reduce_eq_self_of_reduced (reduced_append_overlap hrl₁ hrl₂ (by simp)) } end protected def mul (l₁ l₂ : list (Σ i, M i)) : list (Σ i, M i) := mul_aux l₁.reverse l₂ lemma mul_eq_reduce_append {l₁ l₂ : list (Σ i, M i)} (h₁ : reduced l₁) (h₂ : reduced l₂) : coprod.pre.mul l₁ l₂ = reduce (l₁ ++ l₂) := by rw [coprod.pre.mul, mul_aux_eq_reduce_append (reduced_reverse h₁) h₂, reverse_reverse] lemma reduced_mul {l₁ l₂ : list (Σ i, M i)} (h₁ : reduced l₁) (h₂ : reduced l₂) : reduced (coprod.pre.mul l₁ l₂) := (mul_eq_reduce_append h₁ h₂).symm ▸ reduced_reduce _ protected lemma mul_assoc {l₁ l₂ l₃ : list (Σ i, M i)} (h₁ : reduced l₁) (h₂ : reduced l₂) (h₃ : reduced l₃) : pre.mul (pre.mul l₁ l₂) l₃ = pre.mul l₁ (pre.mul l₂ l₃) := begin rw [mul_eq_reduce_append (reduced_mul h₁ h₂) h₃, mul_eq_reduce_append h₁ h₂, mul_eq_reduce_append h₂ h₃, mul_eq_reduce_append h₁ (reduced_reduce _)], simp [append_assoc] end protected lemma one_mul (l : list (Σ i, M i)) : pre.mul [] l = l := rfl protected lemma mul_one {l : list (Σ i, M i)} (h : reduced l) : pre.mul l [] = l := by rw [mul_eq_reduce_append h reduced_nil, append_nil, reduce_eq_self_of_reduced h] section lift variable (f : Π i, M i →* N) def lift (l : list (Σ i, M i)) : N := l.foldl (λ n i, n * f i.1 i.2) 1 lemma lift_eq_map_prod (l : list (Σ i, M i)) : lift f l = (l.map (λ i : Σ i, M i, f i.1 i.2)).prod := begin rw [lift, ← one_mul (l.map _).prod], generalize h : (1 : N) = n, clear h, induction l with i l ih generalizing n, { simp }, { rw [foldl_cons, ih, map_cons, prod_cons, mul_assoc] } end lemma map_prod_mul_aux : ∀ (l₁ l₂ : list (Σ i, M i)), ((mul_aux l₁ l₂).map (λ i : Σ i, M i, f i.1 i.2)).prod = (l₁.reverse.map (λ i : Σ i, M i, f i.1 i.2)).prod * (l₂.map (λ i : Σ i, M i, f i.1 i.2)).prod | [] l₂ := by simp [mul_aux] | (i::l₁) [] := by simp [mul_aux] | (⟨i,a⟩::l₁) (⟨j,b⟩::l₂) := begin rw [mul_aux], split_ifs, { dsimp only at h, subst h, rw [cast_eq] at h_1, simp only [prod_nil, mul_one, reverse_cons, map, prod_cons, prod_append, map_append, map_reverse, mul_assoc], rw [← mul_assoc (f _ _), ← monoid_hom.map_mul, h_1], simp [map_prod_mul_aux] }, { dsimp only at h, subst h, simp [reverse_core_eq, mul_assoc] }, { simp [reverse_core_eq, mul_assoc] } end lemma lift_mul (l₁ l₂ : list (Σ i, M i)) : lift f (pre.mul l₁ l₂) = lift f l₁ * lift f l₂ := by simp [pre.mul, lift_eq_map_prod, map_prod_mul_aux] end lift section of variables (i : ι) (a b : M i) def of (i : ι) (a : M i) : list (Σ i, M i) := if a = 1 then [] else [⟨i, a⟩] lemma reduced_of (i : ι) (a : M i) : reduced (of i a) := begin rw of, split_ifs, { simp }, { exact reduced_singleton h } end lemma of_one : of i (1 : M i) = [] := if_pos rfl lemma of_mul : of i (a * b) = pre.mul (of i a) (of i b) := begin simp only [of, pre.mul, mul_aux], split_ifs; simp [mul_aux, *, reverse_core_eq] at * end lemma lift_of (f : Π i, M i →* N) : lift f (of i a) = f i a := begin simp [lift, of], split_ifs; simp * end end of section embedding variables {κ : Type*} {O : κ → Type*} [Π i, monoid (O i)] variables (f : ι → κ) (hf : injective f) (g : Π i, M i →* O (f i)) (hg : ∀ i a, g i a = 1 → a = 1) protected def embedding (l : list (Σ i, M i)) : list Σ i, O i := l.map (λ i, ⟨f i.1, g i.1 i.2⟩) include hf hg variables [decidable_eq κ] [Π i, decidable_eq (O i)] lemma embedding_mul_aux : ∀ (l₁ l₂ : list (Σ i, M i)), pre.embedding f g (mul_aux l₁ l₂) = mul_aux (pre.embedding f g l₁) (pre.embedding f g l₂) | [] l₂ := rfl | (i::l₁) [] := by simp [pre.embedding, mul_aux] | (⟨i,a⟩::l₁) (⟨j, b⟩::l₂) := begin rw [mul_aux], split_ifs, { dsimp only at h, subst h, have : g i a * g i b = 1, { erw [← monoid_hom.map_mul, h_1, monoid_hom.map_one] }, rw [embedding_mul_aux], simp [pre.embedding, mul_aux, this] }, { dsimp only at h, subst h, have : g i a * g i b ≠ 1, { rw [← monoid_hom.map_mul], exact mt (hg i (a * b)) h_1 }, simp [pre.embedding, mul_aux, this, reverse_core_eq] }, { dsimp only at h, simp [pre.embedding, mul_aux, reverse_core_eq, hf.eq_iff, h] } end lemma embedding_mul {l₁ l₂ : list (Σ i, M i)} : pre.embedding f g (pre.mul l₁ l₂) = pre.mul (pre.embedding f g l₁) (pre.embedding f g l₂) := begin simp [pre.mul, embedding_mul_aux _ hf _ hg], simp [pre.embedding] end lemma reduced_embedding {l : list (Σ i, M i)} (hl : reduced l) : reduced (pre.embedding f g l) := ⟨by simp [pre.embedding, list.chain'_map, hf.eq_iff, hl.1], begin simp only [pre.embedding, mem_map, and_imp, sigma.forall], rintros i a ⟨⟨j, b⟩, hjb, rfl, h⟩, rw [heq_iff_eq] at h, subst a, exact mt (hg j b) (hl.2 _ hjb) end⟩ end embedding section inv variable [Π i, decidable_eq (G i)] protected def inv (l : list (Σ i, G i)) : list (Σ i, G i) := list.reverse (l.map (λ i : Σ i, G i, ⟨i.1, i.2⁻¹⟩)) lemma reduced_inv (l : list (Σ i, G i)) (hl : reduced l) : reduced (pre.inv l) := ⟨list.chain'_reverse.2 ((list.chain'_map _).2 $ by { convert hl.1, simp [function.funext_iff, eq_comm, flip] }), begin rintros ⟨i, a⟩ hi, rw [pre.inv, mem_reverse, mem_map] at hi, rcases hi with ⟨⟨j, b⟩, hjl, h⟩, simp only at h, cases h with hij hba, subst hij, convert inv_ne_one.2 (hl.2 ⟨j, b⟩ hjl), simp * at * end⟩ protected lemma mul_left_inv_aux : ∀ l : list (Σ i, G i), mul_aux (l.map (λ i : Σ i, G i, ⟨i.1, i.2⁻¹⟩)) l = [] | [] := rfl | (i::l) := by simp [mul_aux, mul_left_inv_aux l] protected lemma mul_left_inv (l : list (Σ i, G i)) : pre.mul (pre.inv l) l = [] := by rw [pre.mul, pre.inv, reverse_reverse, pre.mul_left_inv_aux] end inv end coprod.pre
bde06be70d1f7f7b86c1c9da8ef7e4439aa8c654
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/sequences.lean
ab37790d4298f4446188cc7f84bb5e3017c9c8e6
[ "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
18,938
lean
/- Copyright (c) 2018 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Patrick Massot -/ import topology.bases import topology.subset_properties import topology.metric_space.basic /-! # Sequences in topological spaces In this file we define sequences in topological spaces and show how they are related to filters and the topology. In particular, we * define the sequential closure of a set and prove that it's contained in the closure, * define a type class "sequential_space" in which closure and sequential closure agree, * define sequential continuity and show that it coincides with continuity in sequential spaces, * provide an instance that shows that every first-countable (and in particular metric) space is a sequential space. * define sequential compactness, prove that compactness implies sequential compactness in first countable spaces, and prove they are equivalent for uniform spaces having a countable uniformity basis (in particular metric spaces). -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} local notation f ` ⟶ ` limit := tendsto f at_top (𝓝 limit) /-! ### Sequential closures, sequential continuity, and sequential spaces. -/ section topological_space variables [topological_space α] [topological_space β] /-- A sequence converges in the sence of topological spaces iff the associated statement for filter holds. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma topological_space.seq_tendsto_iff {x : ℕ → α} {limit : α} : tendsto x at_top (𝓝 limit) ↔ ∀ U : set α, limit ∈ U → is_open U → ∃ N, ∀ n ≥ N, (x n) ∈ U := (at_top_basis.tendsto_iff (nhds_basis_opens limit)).trans $ by simp only [and_imp, exists_prop, true_and, set.mem_Ici, ge_iff_le, id] /-- The sequential closure of a subset M ⊆ α of a topological space α is the set of all p ∈ α which arise as limit of sequences in M. -/ def sequential_closure (M : set α) : set α := {p | ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ M) ∧ (x ⟶ p)} lemma subset_sequential_closure (M : set α) : M ⊆ sequential_closure M := assume p (_ : p ∈ M), show p ∈ sequential_closure M, from ⟨λ n, p, assume n, ‹p ∈ M›, tendsto_const_nhds⟩ /-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the limit belongs to `s` as well. -/ def is_seq_closed (s : set α) : Prop := s = sequential_closure s /-- A convenience lemma for showing that a set is sequentially closed. -/ lemma is_seq_closed_of_def {A : set α} (h : ∀(x : ℕ → α) (p : α), (∀ n : ℕ, x n ∈ A) → (x ⟶ p) → p ∈ A) : is_seq_closed A := show A = sequential_closure A, from subset.antisymm (subset_sequential_closure A) (show ∀ p, p ∈ sequential_closure A → p ∈ A, from (assume p ⟨x, _, _⟩, show p ∈ A, from h x p ‹∀ n : ℕ, ((x n) ∈ A)› ‹(x ⟶ p)›)) /-- The sequential closure of a set is contained in the closure of that set. The converse is not true. -/ lemma sequential_closure_subset_closure (M : set α) : sequential_closure M ⊆ closure M := assume p ⟨x, xM, xp⟩, mem_closure_of_tendsto at_top_ne_bot xp (univ_mem_sets' xM) /-- A set is sequentially closed if it is closed. -/ lemma is_seq_closed_of_is_closed (M : set α) (_ : is_closed M) : is_seq_closed M := suffices sequential_closure M ⊆ M, from set.eq_of_subset_of_subset (subset_sequential_closure M) this, calc sequential_closure M ⊆ closure M : sequential_closure_subset_closure M ... = M : is_closed.closure_eq ‹is_closed M› /-- The limit of a convergent sequence in a sequentially closed set is in that set.-/ lemma mem_of_is_seq_closed {A : set α} (_ : is_seq_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : (x ⟶ limit)) : limit ∈ A := have limit ∈ sequential_closure A, from show ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ A) ∧ (x ⟶ limit), from ⟨x, ‹∀ n, x n ∈ A›, ‹(x ⟶ limit)›⟩, eq.subst (eq.symm ‹is_seq_closed A›) ‹limit ∈ sequential_closure A› /-- The limit of a convergent sequence in a closed set is in that set.-/ lemma mem_of_is_closed_sequential {A : set α} (_ : is_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : x ⟶ limit) : limit ∈ A := mem_of_is_seq_closed (is_seq_closed_of_is_closed A ‹is_closed A›) ‹∀ n, x n ∈ A› ‹(x ⟶ limit)› /-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be formalised by demanding that the sequential closure and the closure coincide. The following statements show that other topological properties can be deduced from sequences in sequential spaces. -/ class sequential_space (α : Type*) [topological_space α] : Prop := (sequential_closure_eq_closure : ∀ M : set α, sequential_closure M = closure M) /-- In a sequential space, a set is closed iff it's sequentially closed. -/ lemma is_seq_closed_iff_is_closed [sequential_space α] {M : set α} : is_seq_closed M ↔ is_closed M := iff.intro (assume _, closure_eq_iff_is_closed.mp (eq.symm (calc M = sequential_closure M : by assumption ... = closure M : sequential_space.sequential_closure_eq_closure M))) (is_seq_closed_of_is_closed M) /-- In a sequential space, a point belongs to the closure of a set iff it is a limit of a sequence taking values in this set. -/ lemma mem_closure_iff_seq_limit [sequential_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ s) ∧ (x ⟶ a) := by { rw ← sequential_space.sequential_closure_eq_closure, exact iff.rfl } /-- A function between topological spaces is sequentially continuous if it commutes with limit of convergent sequences. -/ def sequentially_continuous (f : α → β) : Prop := ∀ (x : ℕ → α), ∀ {limit : α}, (x ⟶ limit) → (f∘x ⟶ f limit) /- A continuous function is sequentially continuous. -/ lemma continuous.to_sequentially_continuous {f : α → β} (_ : continuous f) : sequentially_continuous f := assume x limit (_ : x ⟶ limit), have tendsto f (𝓝 limit) (𝓝 (f limit)), from continuous.tendsto ‹continuous f› limit, show (f ∘ x) ⟶ (f limit), from tendsto.comp this ‹(x ⟶ limit)› /-- In a sequential space, continuity and sequential continuity coincide. -/ lemma continuous_iff_sequentially_continuous {f : α → β} [sequential_space α] : continuous f ↔ sequentially_continuous f := iff.intro (assume _, ‹continuous f›.to_sequentially_continuous) (assume : sequentially_continuous f, show continuous f, from suffices h : ∀ {A : set β}, is_closed A → is_seq_closed (f ⁻¹' A), from continuous_iff_is_closed.mpr (assume A _, is_seq_closed_iff_is_closed.mp $ h ‹is_closed A›), assume A (_ : is_closed A), is_seq_closed_of_def $ assume (x : ℕ → α) p (_ : ∀ n, f (x n) ∈ A) (_ : x ⟶ p), have (f ∘ x) ⟶ (f p), from ‹sequentially_continuous f› x ‹(x ⟶ p)›, show f p ∈ A, from mem_of_is_closed_sequential ‹is_closed A› ‹∀ n, f (x n) ∈ A› ‹(f∘x ⟶ f p)›) end topological_space namespace topological_space namespace first_countable_topology variables [topological_space α] [first_countable_topology α] /-- Every first-countable space is sequential. -/ @[priority 100] -- see Note [lower instance priority] instance : sequential_space α := ⟨show ∀ M, sequential_closure M = closure M, from assume M, suffices closure M ⊆ sequential_closure M, from set.subset.antisymm (sequential_closure_subset_closure M) this, -- For every p ∈ closure M, we need to construct a sequence x in M that converges to p: assume (p : α) (hp : p ∈ closure M), -- Since we are in a first-countable space, the neighborhood filter around `p` has a decreasing -- basis `U` indexed by `ℕ`. let ⟨U, hU ⟩ := (nhds_generated_countable p).has_antimono_basis in -- Since `p ∈ closure M`, there is an element in each `M ∩ U i` have hp : ∀ (i : ℕ), ∃ (y : α), y ∈ M ∧ y ∈ U i, by simpa using (mem_closure_iff_nhds_basis hU.1).mp hp, begin -- The axiom of (countable) choice builds our sequence from the later fact choose u hu using hp, rw forall_and_distrib at hu, -- It clearly takes values in `M` use [u, hu.1], -- and converges to `p` because the basis is decreasing. apply hU.tendsto hu.2, end⟩ end first_countable_topology end topological_space section seq_compact open topological_space topological_space.first_countable_topology variables [topological_space α] /-- A set `s` is sequentially compact if every sequence taking values in `s` has a converging subsequence. -/ def seq_compact (s : set α) := ∀ ⦃u : ℕ → α⦄, (∀ n, u n ∈ s) → ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) /-- A space `α` is sequentially compact if every sequence in `α` has a converging subsequence. -/ class seq_compact_space (α : Type*) [topological_space α] : Prop := (seq_compact_univ : seq_compact (univ : set α)) lemma seq_compact.subseq_of_frequently_in {s : set α} (hs : seq_compact s) {u : ℕ → α} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨ψ, hψ, huψ⟩ := extraction_of_frequently_at_top hu, ⟨x, x_in, φ, hφ, h⟩ := hs huψ in ⟨x, x_in, ψ ∘ φ, hψ.comp hφ, h⟩ lemma seq_compact_space.tendsto_subseq [seq_compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨x, _, φ, mono, h⟩ := seq_compact_space.seq_compact_univ (by simp : ∀ n, u n ∈ univ) in ⟨x, φ, mono, h⟩ section first_countable_topology variables [first_countable_topology α] open topological_space.first_countable_topology lemma compact.seq_compact {s : set α} (hs : compact s) : seq_compact s := λ u u_in, let ⟨x, x_in, hx⟩ := hs (map u at_top) (map_ne_bot $ at_top_ne_bot) (le_principal_iff.mpr (univ_mem_sets' u_in : _)) in ⟨x, x_in, tendsto_subseq hx⟩ lemma compact.tendsto_subseq' {s : set α} {u : ℕ → α} (hs : compact s) (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.seq_compact.subseq_of_frequently_in hu lemma compact.tendsto_subseq {s : set α} {u : ℕ → α} (hs : compact s) (hu : ∀ n, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.seq_compact hu @[priority 100] -- see Note [lower instance priority] instance first_countable_topology.seq_compact_of_compact [compact_space α] : seq_compact_space α := ⟨compact_univ.seq_compact⟩ lemma compact_space.tendsto_subseq [compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := seq_compact_space.tendsto_subseq u end first_countable_topology end seq_compact section uniform_space_seq_compact open_locale uniformity open uniform_space prod variables [uniform_space β] {s : set β} lemma lebesgue_number_lemma_seq {ι : Type*} {c : ι → set β} (hs : seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) (hU : is_countably_generated (𝓤 β)) : ∃ V ∈ 𝓤 β, symmetric_rel V ∧ ∀ x ∈ s, ∃ i, ball x V ⊆ c i := begin classical, obtain ⟨V, hV, Vsymm⟩ : ∃ V : ℕ → set (β × β), (𝓤 β).has_antimono_basis (λ _, true) V ∧ ∀ n, swap ⁻¹' V n = V n, from uniform_space.has_seq_basis hU, clear hU, suffices : ∃ n, ∀ x ∈ s, ∃ i, ball x (V n) ⊆ c i, { cases this with n hn, exact ⟨V n, hV.to_has_basis.mem_of_mem trivial, Vsymm n, hn⟩ }, by_contradiction H, obtain ⟨x, x_in, hx⟩ : ∃ x : ℕ → β, (∀ n, x n ∈ s) ∧ ∀ n i, ¬ ball (x n) (V n) ⊆ c i, { push_neg at H, choose x hx using H, exact ⟨x, forall_and_distrib.mp hx⟩ }, clear H, obtain ⟨x₀, x₀_in, φ, φ_mono, hlim⟩ : ∃ (x₀ ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ (x ∘ φ ⟶ x₀), from hs x_in, clear hs, obtain ⟨i₀, x₀_in⟩ : ∃ i₀, x₀ ∈ c i₀, { rcases hc₂ x₀_in with ⟨_, ⟨i₀, rfl⟩, x₀_in_c⟩, exact ⟨i₀, x₀_in_c⟩ }, clear hc₂, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ball x₀ (V n₀) ⊆ c i₀, { rcases (nhds_basis_uniformity hV.to_has_basis).mem_iff.mp (is_open_iff_mem_nhds.mp (hc₁ i₀) _ x₀_in) with ⟨n₀, _, h⟩, use n₀, rwa ← ball_eq_of_symmetry (Vsymm n₀) at h }, clear hc₁, obtain ⟨W, W_in, hWW⟩ : ∃ W ∈ 𝓤 β, W ○ W ⊆ V n₀, from comp_mem_uniformity_sets (hV.to_has_basis.mem_of_mem trivial), obtain ⟨N, x_φ_N_in, hVNW⟩ : ∃ N, x (φ N) ∈ ball x₀ W ∧ V (φ N) ⊆ W, { obtain ⟨N₁, h₁⟩ : ∃ N₁, ∀ n ≥ N₁, x (φ n) ∈ ball x₀ W, from (tendsto_at_top' (λ (b : ℕ), (x ∘ φ) b) (𝓝 x₀)).mp hlim _ (mem_nhds_left x₀ W_in), obtain ⟨N₂, h₂⟩ : ∃ N₂, V (φ N₂) ⊆ W, { rcases hV.to_has_basis.mem_iff.mp W_in with ⟨N, _, hN⟩, use N, exact subset.trans (hV.decreasing trivial trivial $ φ_mono.id_le _) hN }, have : φ N₂ ≤ φ (max N₁ N₂), from φ_mono.le_iff_le.mpr (le_max_right _ _), exact ⟨max N₁ N₂, h₁ _ (le_max_left _ _), subset.trans (hV.decreasing trivial trivial this) h₂⟩ }, suffices : ball (x (φ N)) (V (φ N)) ⊆ c i₀, from hx (φ N) i₀ this, calc ball (x $ φ N) (V $ φ N) ⊆ ball (x $ φ N) W : preimage_mono hVNW ... ⊆ ball x₀ (V n₀) : ball_subset_of_comp_subset x_φ_N_in hWW ... ⊆ c i₀ : hn₀, end lemma seq_compact.totally_bounded (h : seq_compact s) : totally_bounded s := begin classical, apply totally_bounded_of_forall_symm, unfold seq_compact at h, contrapose! h, rcases h with ⟨V, V_in, V_symm, h⟩, simp_rw [not_subset] at h, have : ∀ (t : set β), finite t → ∃ a, a ∈ s ∧ a ∉ ⋃ y ∈ t, ball y V, { intros t ht, obtain ⟨a, a_in, H⟩ : ∃ a ∈ s, ∀ (x : β), x ∈ t → (x, a) ∉ V, by simpa [ht] using h t, use [a, a_in], intro H', obtain ⟨x, x_in, hx⟩ := mem_bUnion_iff.mp H', exact H x x_in hx }, cases seq_of_forall_finite_exists this with u hu, clear h this, simp [forall_and_distrib] at hu, cases hu with u_in hu, use [u, u_in], clear u_in, intros x x_in φ, rw ← imp_iff_not_or, intros hφ huφ, obtain ⟨N, hN⟩ : ∃ N, ∀ p q, p ≥ N → q ≥ N → (u (φ p), u (φ q)) ∈ V, from (cauchy_seq_of_tendsto_nhds _ huφ).mem_entourage V_in, specialize hN N (N+1) (le_refl N) (nat.le_succ N), specialize hu (φ $ N+1) (φ N) (hφ $ lt_add_one N), exact hu hN, end protected lemma seq_compact.compact (h : is_countably_generated $ 𝓤 β) (hs : seq_compact s) : compact s := begin classical, rw compact_iff_finite_subcover, intros ι U Uop s_sub, rcases lebesgue_number_lemma_seq hs Uop s_sub h with ⟨V, V_in, Vsymm, H⟩, rcases totally_bounded_iff_subset.mp hs.totally_bounded V V_in with ⟨t,t_sub, tfin, ht⟩, have : ∀ x : t, ∃ (i : ι), ball x.val V ⊆ U i, { rintros ⟨x, x_in⟩, exact H x (t_sub x_in) }, choose i hi using this, haveI : fintype t := tfin.fintype, use finset.image i finset.univ, transitivity ⋃ y ∈ t, ball y V, { intros x x_in, specialize ht x_in, rw mem_bUnion_iff at *, simp_rw ball_eq_of_symmetry Vsymm, exact ht }, { apply bUnion_subset_bUnion, intros x x_in, exact ⟨i ⟨x, x_in⟩, finset.mem_image_of_mem _ (finset.mem_univ _), hi ⟨x, x_in⟩⟩ }, end protected lemma uniform_space.compact_iff_seq_compact (h : is_countably_generated $ 𝓤 β) : compact s ↔ seq_compact s := begin haveI := uniform_space.first_countable_topology h, exact ⟨λ H, H.seq_compact, λ H, seq_compact.compact h H⟩ end lemma uniform_space.compact_space_iff_seq_compact_space (H : is_countably_generated $ 𝓤 β) : compact_space β ↔ seq_compact_space β := have key : compact univ ↔ seq_compact univ := uniform_space.compact_iff_seq_compact H, ⟨λ ⟨h⟩, ⟨key.mp h⟩, λ ⟨h⟩, ⟨key.mpr h⟩⟩ end uniform_space_seq_compact section metric_seq_compact variables [metric_space β] {s : set β} open metric /-- A version of Bolzano-Weistrass: in a metric space, compact s ↔ seq_compact s -/ lemma metric.compact_iff_seq_compact : compact s ↔ seq_compact s := uniform_space.compact_iff_seq_compact emetric.uniformity_has_countable_basis /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. This version assumes only that the sequence is frequently in some bounded set. -/ lemma tendsto_subseq_of_frequently_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := begin have hcs : compact (closure s) := compact_iff_closed_bounded.mpr ⟨is_closed_closure, bounded_closure_of_bounded hs⟩, replace hcs : seq_compact (closure s), by rwa metric.compact_iff_seq_compact at hcs, have hu' : ∃ᶠ n in at_top, u n ∈ closure s, { apply frequently.mono hu, intro n, apply subset_closure }, exact hcs.subseq_of_frequently_in hu', end /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. -/ lemma tendsto_subseq_of_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∀ n, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := tendsto_subseq_of_frequently_bounded hs $ frequently_of_forall at_top_ne_bot hu lemma metric.compact_space_iff_seq_compact_space : compact_space β ↔ seq_compact_space β := uniform_space.compact_space_iff_seq_compact_space emetric.uniformity_has_countable_basis @[nolint ge_or_gt] -- see Note [nolint_ge] lemma seq_compact.lebesgue_number_lemma_of_metric {ι : Type*} {c : ι → set β} (hs : seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := begin rcases lebesgue_number_lemma_seq hs hc₁ hc₂ emetric.uniformity_has_countable_basis with ⟨V, V_in, _, hV⟩, rcases uniformity_basis_dist.mem_iff.mp V_in with ⟨δ, δ_pos, h⟩, use [δ, δ_pos], intros x x_in, rcases hV x x_in with ⟨i, hi⟩, use i, have := ball_mono h x, rw ball_eq_ball' at this, exact subset.trans this hi, end end metric_seq_compact
c550601c8194b0f8469fe5e5d595f6af850e0a99
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/determinant.lean
544c15df1f2f02d629ffd86a601e7e782a714a41
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,761
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.free_module.pid import linear_algebra.matrix.basis import linear_algebra.matrix.diagonal import linear_algebra.matrix.to_linear_equiv import linear_algebra.matrix.reindex import linear_algebra.multilinear.basic import linear_algebra.dual import ring_theory.algebra_tower /-! # Determinant of families of vectors This file defines the determinant of an endomorphism, and of a family of vectors with respect to some basis. For the determinant of a matrix, see the file `linear_algebra.matrix.determinant`. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map * `linear_map.det`: the determinant of an endomorphism `f : End R M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) ## Tags basis, det, determinant -/ noncomputable theory open_locale big_operators open_locale matrix open linear_map open submodule universes u v w open linear_map matrix variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {M' : Type*} [add_comm_group M'] [module R M'] variables {ι : Type*} [decidable_eq ι] [fintype ι] variables (e : basis ι R M) section conjugate variables {A : Type*} [comm_ring A] variables {m n : Type*} [fintype m] [fintype n] /-- If `R^m` and `R^n` are linearly equivalent, then `m` and `n` are also equivalent. -/ def equiv_of_pi_lequiv_pi {R : Type*} [comm_ring R] [integral_domain R] (e : (m → R) ≃ₗ[R] (n → R)) : m ≃ n := basis.index_equiv (basis.of_equiv_fun e.symm) (pi.basis_fun _ _) namespace matrix /-- If `M` and `M'` are each other's inverse matrices, they are square matrices up to equivalence of types. -/ def index_equiv_of_inv [integral_domain A] [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : m ≃ n := equiv_of_pi_lequiv_pi (to_lin'_of_inv hMM' hM'M) lemma det_comm [decidable_eq n] (M N : matrix n n A) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- If there exists a two-sided inverse `M'` for `M` (indexed differently), then `det (N ⬝ M) = det (M ⬝ N)`. -/ lemma det_comm' [integral_domain A] [decidable_eq m] [decidable_eq n] {M : matrix n m A} {N : matrix m n A} {M' : matrix m n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N) = det (N ⬝ M) := -- Although `m` and `n` are different a priori, we will show they have the same cardinality. -- This turns the problem into one for square matrices, which is easy. let e := index_equiv_of_inv hMM' hM'M in by rw [← det_minor_equiv_self e, minor_mul_equiv _ _ _ (equiv.refl n) _, det_comm, ← minor_mul_equiv, equiv.coe_refl, minor_id_id] /-- If `M'` is a two-sided inverse for `M` (indexed differently), `det (M ⬝ N ⬝ M') = det N`. -/ lemma det_conj [integral_domain A] [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} {N : matrix n n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N ⬝ M') = det N := by rw [← det_comm' hM'M hMM', ← matrix.mul_assoc, hM'M, matrix.one_mul] end matrix end conjugate namespace linear_map /-! ### Determinant of a linear map -/ variables {A : Type*} [comm_ring A] [integral_domain A] [module A M] variables {κ : Type*} [fintype κ] /-- The determinant of `linear_map.to_matrix` does not depend on the choice of basis. -/ lemma det_to_matrix_eq_det_to_matrix [decidable_eq κ] (b : basis ι A M) (c : basis κ A M) (f : M →ₗ[A] M) : det (linear_map.to_matrix b b f) = det (linear_map.to_matrix c c f) := by rw [← linear_map_to_matrix_mul_basis_to_matrix c b c, ← basis_to_matrix_mul_linear_map_to_matrix b c b, matrix.det_conj]; rw [basis.to_matrix_mul_to_matrix, basis.to_matrix_self] /-- The determinant of an endomorphism given a basis. See `linear_map.det` for a version that populates the basis non-computably. Although the `trunc (basis ι A M)` parameter makes it slightly more convenient to switch bases, there is no good way to generalize over universe parameters, so we can't fully state in `det_aux`'s type that it does not depend on the choice of basis. Instead you can use the `det_aux_def'` lemma, or avoid mentioning a basis at all using `linear_map.det`. -/ def det_aux : trunc (basis ι A M) → (M →ₗ[A] M) →* A := trunc.lift (λ b : basis ι A M, (det_monoid_hom).comp (to_matrix_alg_equiv b : (M →ₗ[A] M) →* matrix ι ι A)) (λ b c, monoid_hom.ext $ det_to_matrix_eq_det_to_matrix b c) /-- Unfold lemma for `det_aux`. See also `det_aux_def'` which allows you to vary the basis. -/ lemma det_aux_def (b : basis ι A M) (f : M →ₗ[A] M) : linear_map.det_aux (trunc.mk b) f = matrix.det (linear_map.to_matrix b b f) := rfl -- Discourage the elaborator from unfolding `det_aux` and producing a huge term. attribute [irreducible] linear_map.det_aux lemma det_aux_def' {ι' : Type*} [fintype ι'] [decidable_eq ι'] (tb : trunc $ basis ι A M) (b' : basis ι' A M) (f : M →ₗ[A] M) : linear_map.det_aux tb f = matrix.det (linear_map.to_matrix b' b' f) := by { apply trunc.induction_on tb, intro b, rw [det_aux_def, det_to_matrix_eq_det_to_matrix b b'] } @[simp] lemma det_aux_id (b : trunc $ basis ι A M) : linear_map.det_aux b (linear_map.id) = 1 := (linear_map.det_aux b).map_one @[simp] lemma det_aux_comp (b : trunc $ basis ι A M) (f g : M →ₗ[A] M) : linear_map.det_aux b (f.comp g) = linear_map.det_aux b f * linear_map.det_aux b g := (linear_map.det_aux b).map_mul f g section open_locale classical -- Discourage the elaborator from unfolding `det` and producing a huge term by marking it -- as irreducible. /-- The determinant of an endomorphism independent of basis. If there is no finite basis on `M`, the result is `1` instead. -/ @[irreducible] protected def det : (M →ₗ[A] M) →* A := if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 lemma coe_det [decidable_eq M] : ⇑(linear_map.det : (M →ₗ[A] M) →* A) = if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 := by { ext, unfold linear_map.det, split_ifs, { congr }, -- use the correct `decidable_eq` instance refl } end -- Auxiliary lemma, the `simp` normal form goes in the other direction -- (using `linear_map.det_to_matrix`) lemma det_eq_det_to_matrix_of_finset [decidable_eq M] {s : finset M} (b : basis s A M) (f : M →ₗ[A] M) : f.det = matrix.det (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s A M), from ⟨s, ⟨b⟩⟩, by rw [linear_map.coe_det, dif_pos, det_aux_def' _ b]; assumption @[simp] lemma det_to_matrix (b : basis ι A M) (f : M →ₗ[A] M) : matrix.det (to_matrix b b f) = f.det := by { haveI := classical.dec_eq M, rw [det_eq_det_to_matrix_of_finset b.reindex_finset_range, det_to_matrix_eq_det_to_matrix b] } @[simp] lemma det_to_matrix' {ι : Type*} [fintype ι] [decidable_eq ι] (f : (ι → A) →ₗ[A] (ι → A)) : det f.to_matrix' = f.det := by simp [← to_matrix_eq_to_matrix'] /-- To show `P f.det` it suffices to consider `P (to_matrix _ _ f).det` and `P 1`. -/ @[elab_as_eliminator] lemma det_cases [decidable_eq M] {P : A → Prop} (f : M →ₗ[A] M) (hb : ∀ (s : finset M) (b : basis s A M), P (to_matrix b b f).det) (h1 : P 1) : P f.det := begin unfold linear_map.det, split_ifs with h, { convert hb _ h.some_spec.some, apply det_aux_def' }, { exact h1 } end @[simp] lemma det_comp (f g : M →ₗ[A] M) : (f.comp g).det = f.det * g.det := linear_map.det.map_mul f g @[simp] lemma det_id : (linear_map.id : M →ₗ[A] M).det = 1 := linear_map.det.map_one /-- Multiplying a map by a scalar `c` multiplies its determinant by `c ^ dim M`. -/ @[simp] lemma det_smul {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] (c : 𝕜) (f : M →ₗ[𝕜] M) : linear_map.det (c • f) = c ^ (finite_dimensional.finrank 𝕜 M) * linear_map.det f := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { haveI : finite_dimensional 𝕜 M, { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_finset_basis hs }, simp only [← det_to_matrix (finite_dimensional.fin_basis 𝕜 M), linear_equiv.map_smul, fintype.card_fin, det_smul] }, { classical, have : finite_dimensional.finrank 𝕜 M = 0 := finrank_eq_zero_of_not_exists_basis H, simp [coe_det, H, this] } end lemma det_zero' {ι : Type*} [fintype ι] [nonempty ι] (b : basis ι A M) : linear_map.det (0 : M →ₗ[A] M) = 0 := by { haveI := classical.dec_eq ι, rw [← det_to_matrix b, linear_equiv.map_zero, det_zero], assumption } /-- In a finite-dimensional vector space, the zero map has determinant `1` in dimension `0`, and `0` otherwise. -/ @[simp] lemma det_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] : linear_map.det (0 : M →ₗ[𝕜] M) = (0 : 𝕜) ^ (finite_dimensional.finrank 𝕜 M) := by simp only [← zero_smul 𝕜 (1 : M →ₗ[𝕜] M), det_smul, mul_one, monoid_hom.map_one] /-- Conjugating a linear map by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj {N : Type*} [add_comm_group N] [module A N] (f : M →ₗ[A] M) (e : M ≃ₗ[A] N) : linear_map.det ((e : M →ₗ[A] N) ∘ₗ (f ∘ₗ (e.symm : N →ₗ[A] M))) = linear_map.det f := begin classical, by_cases H : ∃ (s : finset M), nonempty (basis s A M), { rcases H with ⟨s, ⟨b⟩⟩, rw [← det_to_matrix b f, ← det_to_matrix (b.map e), to_matrix_comp (b.map e) b (b.map e), to_matrix_comp (b.map e) b b, ← matrix.mul_assoc, matrix.det_conj], { rw [← to_matrix_comp, linear_equiv.comp_coe, e.symm_trans, linear_equiv.refl_to_linear_map, to_matrix_id] }, { rw [← to_matrix_comp, linear_equiv.comp_coe, e.trans_symm, linear_equiv.refl_to_linear_map, to_matrix_id] } }, { have H' : ¬ (∃ (t : finset N), nonempty (basis t A N)), { contrapose! H, rcases H with ⟨s, ⟨b⟩⟩, exact ⟨_, ⟨(b.map e.symm).reindex_finset_range⟩⟩ }, simp only [coe_det, H, H', pi.one_apply, dif_neg, not_false_iff] } end end linear_map -- Cannot be stated using `linear_map.det` because `f` is not an endomorphism. lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (v : basis ι R M) (v' : basis ι R M') : is_unit (linear_map.to_matrix v v' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_map.to_matrix_comp v v' v f.symm f).symm end /-- Specialization of `linear_equiv.is_unit_det` -/ lemma linear_equiv.is_unit_det' {A : Type*} [comm_ring A] [integral_domain A] [module A M] (f : M ≃ₗ[A] M) : is_unit (linear_map.det (f : M →ₗ[A] M)) := by haveI := classical.dec_eq M; exact (f : M →ₗ[A] M).det_cases (λ s b, f.is_unit_det _ _) is_unit_one /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ @[simps] def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := to_lin v' v (to_matrix v v' f)⁻¹, left_inv := λ x, calc to_lin v' v (to_matrix v v' f)⁻¹ (f x) = to_lin v v ((to_matrix v v' f)⁻¹ ⬝ to_matrix v v' f) x : by { rw [to_lin_mul v v' v, to_lin_to_matrix, linear_map.comp_apply] } ... = x : by simp [h], right_inv := λ x, calc f (to_lin v' v (to_matrix v v' f)⁻¹ x) = to_lin v' v' (to_matrix v v' f ⬝ (to_matrix v v' f)⁻¹) x : by { rw [to_lin_mul v' v v', linear_map.comp_apply, to_lin_to_matrix v v'] } ... = x : by simp [h] } /-- Builds a linear equivalence from a linear map on a finite-dimensional vector space whose determinant is nonzero. -/ @[reducible] def linear_map.equiv_of_det_ne_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] [finite_dimensional 𝕜 M] (f : M →ₗ[𝕜] M) (hf : linear_map.det f ≠ 0) : M ≃ₗ[𝕜] M := have is_unit (linear_map.to_matrix (finite_dimensional.fin_basis 𝕜 M) (finite_dimensional.fin_basis 𝕜 M) f).det := by simp only [linear_map.det_to_matrix, is_unit_iff_ne_zero.2 hf], linear_equiv.of_is_unit_det this /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def basis.det : alternating_map R M R ι := { to_fun := λ v, det (e.to_matrix v), map_add' := begin intros v i x y, simp only [e.to_matrix_update, linear_equiv.map_add], apply det_update_column_add end, map_smul' := begin intros u i c x, simp only [e.to_matrix_update, algebra.id.smul_eq_mul, linear_equiv.map_smul], apply det_update_column_smul end, map_eq_zero_of_eq' := begin intros v i j h hij, rw [←function.update_eq_self i v, h, ←det_transpose, e.to_matrix_update, ←update_row_transpose, ←e.to_matrix_transpose_apply], apply det_zero_of_row_eq hij, rw [update_row_ne hij.symm, update_row_self], end } lemma basis.det_apply (v : ι → M) : e.det v = det (e.to_matrix v) := rfl lemma basis.det_self : e.det e = 1 := by simp [e.det_apply] lemma is_basis_iff_det {v : ι → M} : linear_independent R v ∧ span R (set.range v) = ⊤ ↔ is_unit (e.det v) := begin split, { rintro ⟨hli, hspan⟩, set v' := basis.mk hli hspan with v'_eq, rw e.det_apply, convert linear_equiv.is_unit_det (linear_equiv.refl _ _) v' e using 2, ext i j, simp }, { intro h, rw [basis.det_apply, basis.to_matrix_eq_to_matrix_constr] at h, set v' := basis.map e (linear_equiv.of_is_unit_det h) with v'_def, have : ⇑ v' = v, { ext i, rw [v'_def, basis.map_apply, linear_equiv.of_is_unit_det_apply, e.constr_basis] }, rw ← this, exact ⟨v'.linear_independent, v'.span_eq⟩ }, end lemma basis.is_unit_det (e' : basis ι R M) : is_unit (e.det e') := (is_basis_iff_det e).mp ⟨e'.linear_independent, e'.span_eq⟩ variables {A : Type*} [comm_ring A] [integral_domain A] [module A M] @[simp] lemma basis.det_comp (e : basis ι A M) (f : M →ₗ[A] M) (v : ι → M) : e.det (f ∘ v) = f.det * e.det v := by { rw [basis.det_apply, basis.det_apply, ← f.det_to_matrix e, ← matrix.det_mul, e.to_matrix_eq_to_matrix_constr (f ∘ v), e.to_matrix_eq_to_matrix_constr v, ← to_matrix_comp, e.constr_comp] } lemma basis.det_reindex {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).det v = b.det (v ∘ e) := by rw [basis.det_apply, basis.to_matrix_reindex', det_reindex_alg_equiv, basis.det_apply] lemma basis.det_reindex_symm {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι → M) (e : ι' ≃ ι) : (b.reindex e.symm).det (v ∘ e) = b.det v := by rw [basis.det_reindex, function.comp.assoc, e.self_comp_symm, function.comp.right_id] @[simp] lemma basis.det_map (b : basis ι R M) (f : M ≃ₗ[R] M') (v : ι → M') : (b.map f).det v = b.det (f.symm ∘ v) := by { rw [basis.det_apply, basis.to_matrix_map, basis.det_apply] }
6b38933961b1497c28a7591e2bae1c8b75a518fd
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/field_theory/perfect_closure.lean
3f58ea6d77938403e731597010afd4c2d23b868c
[ "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
16,641
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.char_p import data.equiv.ring import algebra.group_with_zero.power import algebra.iterate_hom /-! # The perfect closure of a field -/ universes u v open function section defs variables (K : Type u) [field K] (p : ℕ) [fact p.prime] [char_p K p] /-- A perfect field is a field of characteristic p that has p-th root. -/ class perfect_field (K : Type u) [field K] (p : ℕ) [fact p.prime] [char_p K p] : Type u := (pth_root' : K → K) (frobenius_pth_root' : ∀ x, frobenius K p (pth_root' x) = x) /-- Frobenius automorphism of a perfect field. -/ def frobenius_equiv [perfect_field K p] : K ≃+* K := { inv_fun := perfect_field.pth_root' p, left_inv := λ x, frobenius_inj K p $ perfect_field.frobenius_pth_root' _, right_inv := perfect_field.frobenius_pth_root', .. frobenius K p } /-- `p`-th root of a number in a `perfect_field` as a `ring_hom`. -/ def pth_root [perfect_field K p] : K →+* K := (frobenius_equiv K p).symm.to_ring_hom end defs section variables {K : Type u} [field K] {L : Type v} [field L] (f : K →* L) (g : K →+* L) {p : ℕ} [fact p.prime] [char_p K p] [perfect_field K p] [char_p L p] [perfect_field L p] @[simp] lemma coe_frobenius_equiv : ⇑(frobenius_equiv K p) = frobenius K p := rfl @[simp] lemma coe_frobenius_equiv_symm : ⇑(frobenius_equiv K p).symm = pth_root K p := rfl @[simp] theorem frobenius_pth_root (x : K) : frobenius K p (pth_root K p x) = x := (frobenius_equiv K p).apply_symm_apply x @[simp] theorem pth_root_frobenius (x : K) : pth_root K p (frobenius K p x) = x := (frobenius_equiv K p).symm_apply_apply x theorem left_inverse_pth_root_frobenius : left_inverse (pth_root K p) (frobenius K p) := pth_root_frobenius theorem eq_pth_root_iff {x y : K} : x = pth_root K p y ↔ frobenius K p x = y := (frobenius_equiv K p).to_equiv.eq_symm_apply theorem pth_root_eq_iff {x y : K} : pth_root K p x = y ↔ x = frobenius K p y := (frobenius_equiv K p).to_equiv.symm_apply_eq theorem monoid_hom.map_pth_root (x : K) : f (pth_root K p x) = pth_root L p (f x) := eq_pth_root_iff.2 $ by rw [← f.map_frobenius, frobenius_pth_root] theorem monoid_hom.map_iterate_pth_root (x : K) (n : ℕ) : f (pth_root K p^[n] x) = (pth_root L p^[n] (f x)) := semiconj.iterate_right f.map_pth_root n x theorem ring_hom.map_pth_root (x : K) : g (pth_root K p x) = pth_root L p (g x) := g.to_monoid_hom.map_pth_root x theorem ring_hom.map_iterate_pth_root (x : K) (n : ℕ) : g (pth_root K p^[n] x) = (pth_root L p^[n] (g x)) := g.to_monoid_hom.map_iterate_pth_root x n end section variables (K : Type u) [comm_ring K] (p : ℕ) [fact p.prime] [char_p K p] /-- `perfect_closure K p` is the quotient by this relation. -/ @[mk_iff] inductive perfect_closure.r : (ℕ × K) → (ℕ × K) → Prop | intro : ∀ n x, perfect_closure.r (n, x) (n+1, frobenius K p x) /-- The perfect closure is the smallest extension that makes frobenius surjective. -/ def perfect_closure : Type u := quot (perfect_closure.r K p) end namespace perfect_closure variables (K : Type u) section ring variables [comm_ring K] (p : ℕ) [fact p.prime] [char_p K p] /-- Constructor for `perfect_closure`. -/ def mk (x : ℕ × K) : perfect_closure K p := quot.mk (r K p) x @[simp] lemma quot_mk_eq_mk (x : ℕ × K) : (quot.mk (r K p) x : perfect_closure K p) = mk K p x := rfl variables {K p} /-- Lift a function `ℕ × K → L` to a function on `perfect_closure K p`. -/ @[elab_as_eliminator] def lift_on {L : Type*} (x : perfect_closure K p) (f : ℕ × K → L) (hf : ∀ x y, r K p x y → f x = f y) : L := quot.lift_on x f hf @[simp] lemma lift_on_mk {L : Sort*} (f : ℕ × K → L) (hf : ∀ x y, r K p x y → f x = f y) (x : ℕ × K) : (mk K p x).lift_on f hf = f x := rfl @[elab_as_eliminator] lemma induction_on (x : perfect_closure K p) {q : perfect_closure K p → Prop} (h : ∀ x, q (mk K p x)) : q x := quot.induction_on x h variables (K p) private lemma mul_aux_left (x1 x2 y : ℕ × K) (H : r K p x1 x2) : mk K p (x1.1 + y.1, ((frobenius K p)^[y.1] x1.2) * ((frobenius K p)^[x1.1] y.2)) = mk K p (x2.1 + y.1, ((frobenius K p)^[y.1] x2.2) * ((frobenius K p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro n x := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_mul, nat.succ_add]; apply r.intro end private lemma mul_aux_right (x y1 y2 : ℕ × K) (H : r K p y1 y2) : mk K p (x.1 + y1.1, ((frobenius K p)^[y1.1] x.2) * ((frobenius K p)^[x.1] y1.2)) = mk K p (x.1 + y2.1, ((frobenius K p)^[y2.1] x.2) * ((frobenius K p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro n y := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_mul]; apply r.intro end instance : has_mul (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.lift (λ y:ℕ×K, mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) * ((frobenius K p)^[x.1] y.2))) (mul_aux_right K p x)) (λ x1 x2 (H : r K p x1 x2), funext $ λ e, quot.induction_on e $ λ y, mul_aux_left K p x1 x2 y H)⟩ @[simp] lemma mk_mul_mk (x y : ℕ × K) : mk K p x * mk K p y = mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) * ((frobenius K p)^[x.1] y.2)) := rfl instance : comm_monoid (perfect_closure K p) := { mul_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, mul_assoc, ring_hom.iterate_map_mul, ← iterate_add_apply, add_comm, add_left_comm], one := mk K p (0, 1), one_mul := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_one, iterate_zero_apply, one_mul, zero_add]), mul_one := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_one, iterate_zero_apply, mul_one, add_zero]), mul_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm, mul_comm])), .. (infer_instance : has_mul (perfect_closure K p)) } lemma one_def : (1 : perfect_closure K p) = mk K p (0, 1) := rfl instance : inhabited (perfect_closure K p) := ⟨1⟩ private lemma add_aux_left (x1 x2 y : ℕ × K) (H : r K p x1 x2) : mk K p (x1.1 + y.1, ((frobenius K p)^[y.1] x1.2) + ((frobenius K p)^[x1.1] y.2)) = mk K p (x2.1 + y.1, ((frobenius K p)^[y.1] x2.2) + ((frobenius K p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro n x := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_add, nat.succ_add]; apply r.intro end private lemma add_aux_right (x y1 y2 : ℕ × K) (H : r K p y1 y2) : mk K p (x.1 + y1.1, ((frobenius K p)^[y1.1] x.2) + ((frobenius K p)^[x.1] y1.2)) = mk K p (x.1 + y2.1, ((frobenius K p)^[y2.1] x.2) + ((frobenius K p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro n y := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_add]; apply r.intro end instance : has_add (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.lift (λ y:ℕ×K, mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) + ((frobenius K p)^[x.1] y.2))) (add_aux_right K p x)) (λ x1 x2 (H : r K p x1 x2), funext $ λ e, quot.induction_on e $ λ y, add_aux_left K p x1 x2 y H)⟩ @[simp] lemma mk_add_mk (x y : ℕ × K) : mk K p x + mk K p y = mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) + ((frobenius K p)^[x.1] y.2)) := rfl instance : has_neg (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, mk K p (x.1, -x.2)) (λ x y (H : r K p x y), match x, y, H with | _, _, r.intro n x := quot.sound $ by rw ← frobenius_neg; apply r.intro end)⟩ @[simp] lemma neg_mk (x : ℕ × K) : - mk K p x = mk K p (x.1, -x.2) := rfl instance : has_zero (perfect_closure K p) := ⟨mk K p (0, 0)⟩ lemma zero_def : (0 : perfect_closure K p) = mk K p (0, 0) := rfl theorem mk_zero (n : ℕ) : mk K p (n, 0) = 0 := by induction n with n ih; [refl, rw ← ih]; symmetry; apply quot.sound; have := r.intro n (0:K); rwa [frobenius_zero K p] at this theorem r.sound (m n : ℕ) (x y : K) (H : frobenius K p^[m] x = y) : mk K p (n, x) = mk K p (m + n, y) := by subst H; induction m with m ih; [simp only [zero_add, iterate_zero_apply], rw [ih, nat.succ_add, iterate_succ']]; apply quot.sound; apply r.intro instance : comm_ring (perfect_closure K p) := { add_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, ring_hom.iterate_map_add, ← iterate_add_apply, add_comm, add_left_comm], zero := 0, zero_add := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_zero, iterate_zero_apply, zero_add]), add_zero := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_zero, iterate_zero_apply, add_zero]), add_left_neg := λ e, quot.induction_on e (λ ⟨n, x⟩, by simp only [quot_mk_eq_mk, neg_mk, mk_add_mk, ring_hom.iterate_map_neg, add_left_neg, mk_zero]), add_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm])), left_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm, add_left_comm]; apply r.sound; simp only [ring_hom.iterate_map_mul, ring_hom.iterate_map_add, ← iterate_add_apply, mul_add, add_comm, add_left_comm], right_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm _ s, add_left_comm _ s]; apply r.sound; simp only [ring_hom.iterate_map_mul, ring_hom.iterate_map_add, ← iterate_add_apply, add_mul, add_comm, add_left_comm], .. (infer_instance : has_add (perfect_closure K p)), .. (infer_instance : has_neg (perfect_closure K p)), .. (infer_instance : comm_monoid (perfect_closure K p)) } theorem eq_iff' (x y : ℕ × K) : mk K p x = mk K p y ↔ ∃ z, (frobenius K p^[y.1 + z] x.2) = (frobenius K p^[x.1 + z] y.2) := begin split, { intro H, replace H := quot.exact _ H, induction H, case eqv_gen.rel : x y H { cases H with n x, exact ⟨0, rfl⟩ }, case eqv_gen.refl : H { exact ⟨0, rfl⟩ }, case eqv_gen.symm : x y H ih { cases ih with w ih, exact ⟨w, ih.symm⟩ }, case eqv_gen.trans : x y z H1 H2 ih1 ih2 { cases ih1 with z1 ih1, cases ih2 with z2 ih2, existsi z2+(y.1+z1), rw [← add_assoc, iterate_add_apply, ih1], rw [← iterate_add_apply, add_comm, iterate_add_apply, ih2], rw [← iterate_add_apply], simp only [add_comm, add_left_comm] } }, intro H, cases x with m x, cases y with n y, cases H with z H, dsimp only at H, rw [r.sound K p (n+z) m x _ rfl, r.sound K p (m+z) n y _ rfl, H], rw [add_assoc, add_comm, add_comm z] end theorem nat_cast (n x : ℕ) : (x : perfect_closure K p) = mk K p (n, x) := begin induction n with n ih, { induction x with x ih, {refl}, rw [nat.cast_succ, nat.cast_succ, ih], refl }, rw ih, apply quot.sound, conv {congr, skip, skip, rw ← frobenius_nat_cast K p x}, apply r.intro end theorem int_cast (x : ℤ) : (x : perfect_closure K p) = mk K p (0, x) := by induction x; simp only [int.cast_of_nat, int.cast_neg_succ_of_nat, nat_cast K p 0]; refl theorem nat_cast_eq_iff (x y : ℕ) : (x : perfect_closure K p) = y ↔ (x : K) = y := begin split; intro H, { rw [nat_cast K p 0, nat_cast K p 0, eq_iff'] at H, cases H with z H, simpa only [zero_add, iterate_fixed (frobenius_nat_cast K p _)] using H }, rw [nat_cast K p 0, nat_cast K p 0, H] end instance : char_p (perfect_closure K p) p := begin constructor, intro x, rw ← char_p.cast_eq_zero_iff K, rw [← nat.cast_zero, nat_cast_eq_iff, nat.cast_zero] end theorem frobenius_mk (x : ℕ × K) : (frobenius (perfect_closure K p) p : perfect_closure K p → perfect_closure K p) (mk K p x) = mk _ _ (x.1, x.2^p) := begin simp only [frobenius_def], cases x with n x, dsimp only, suffices : ∀ p':ℕ, mk K p (n, x) ^ p' = mk K p (n, x ^ p'), { apply this }, intro p, induction p with p ih, case nat.zero { apply r.sound, rw [(frobenius _ _).iterate_map_one, pow_zero] }, case nat.succ { rw [pow_succ, ih], symmetry, apply r.sound, simp only [pow_succ, (frobenius _ _).iterate_map_mul] } end /-- Embedding of `K` into `perfect_closure K p` -/ def of : K →+* perfect_closure K p := { to_fun := λ x, mk _ _ (0, x), map_one' := rfl, map_mul' := λ x y, rfl, map_zero' := rfl, map_add' := λ x y, rfl } lemma of_apply (x : K) : of K p x = mk _ _ (0, x) := rfl end ring theorem eq_iff [integral_domain K] (p : ℕ) [fact p.prime] [char_p K p] (x y : ℕ × K) : quot.mk (r K p) x = quot.mk (r K p) y ↔ (frobenius K p^[y.1] x.2) = (frobenius K p^[x.1] y.2) := (eq_iff' K p x y).trans ⟨λ ⟨z, H⟩, (frobenius_inj K p).iterate z $ by simpa only [add_comm, iterate_add] using H, λ H, ⟨0, H⟩⟩ section field variables [field K] (p : ℕ) [fact p.prime] [char_p K p] instance : has_inv (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.mk (r K p) (x.1, x.2⁻¹)) (λ x y (H : r K p x y), match x, y, H with | _, _, r.intro n x := quot.sound $ by { simp only [frobenius_def], rw ← inv_pow', apply r.intro } end)⟩ instance : field (perfect_closure K p) := { exists_pair_ne := ⟨0, 1, λ H, zero_ne_one ((eq_iff _ _ _ _).1 H)⟩, mul_inv_cancel := λ e, induction_on e $ λ ⟨m, x⟩ H, have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2 (by simp only [(frobenius _ _).iterate_map_one, (frobenius K p).iterate_map_zero, iterate_zero_apply, ← (frobenius _ p).iterate_map_mul] at this ⊢; rw [mul_inv_cancel this, (frobenius _ _).iterate_map_one]), inv_zero := congr_arg (quot.mk (r K p)) (by rw [inv_zero]), .. (infer_instance : has_inv (perfect_closure K p)), .. (infer_instance : comm_ring (perfect_closure K p)) } instance : perfect_field (perfect_closure K p) p := { pth_root' := λ e, lift_on e (λ x, mk K p (x.1 + 1, x.2)) (λ x y H, match x, y, H with | _, _, r.intro n x := quot.sound (r.intro _ _) end), frobenius_pth_root' := λ e, induction_on e (λ ⟨n, x⟩, by { simp only [lift_on_mk, frobenius_mk], exact (quot.sound $ r.intro _ _).symm }) } theorem eq_pth_root (x : ℕ × K) : mk K p x = (pth_root (perfect_closure K p) p^[x.1] (of K p x.2)) := begin rcases x with ⟨m, x⟩, induction m with m ih, {refl}, rw [iterate_succ_apply', ← ih]; refl end /-- Given a field `K` of characteristic `p` and a perfect field `L` of the same characteristic, any homomorphism `K →+* L` can be lifted to `perfect_closure K p`. -/ def lift (L : Type v) [field L] [char_p L p] [perfect_field L p] : (K →+* L) ≃ (perfect_closure K p →+* L) := begin have := left_inverse_pth_root_frobenius.iterate, refine_struct { .. }, field to_fun { intro f, refine_struct { .. }, field to_fun { refine λ e, lift_on e (λ x, pth_root L p^[x.1] (f x.2)) _, rintro a b ⟨n⟩, simp only [f.map_frobenius, iterate_succ_apply, pth_root_frobenius] }, field map_one' { exact f.map_one }, field map_zero' { exact f.map_zero }, field map_mul' { rintro ⟨x⟩ ⟨y⟩, simp only [quot_mk_eq_mk, lift_on_mk, mk_mul_mk, ring_hom.map_iterate_frobenius, ring_hom.iterate_map_mul, ring_hom.map_mul], rw [iterate_add_apply, this _ _, add_comm, iterate_add_apply, this _ _] }, field map_add' { rintro ⟨x⟩ ⟨y⟩, simp only [quot_mk_eq_mk, lift_on_mk, mk_add_mk, ring_hom.map_iterate_frobenius, ring_hom.iterate_map_add, ring_hom.map_add], rw [iterate_add_apply, this _ _, add_comm x.1, iterate_add_apply, this _ _] } }, field inv_fun { exact λ f, f.comp (of K p) }, field left_inv { intro f, ext x, refl }, field right_inv { intro f, ext ⟨x⟩, simp only [ring_hom.coe_mk, quot_mk_eq_mk, ring_hom.comp_apply, lift_on_mk], rw [eq_pth_root, ring_hom.map_iterate_pth_root] } end end field end perfect_closure
25f228aa4e561067b8a3256df8d678d1825c8cf4
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/free_abelian_group.lean
069e6160df8e16f576b32fa7209b6943e6dc4be1
[ "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
19,142
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.group.pi import group_theory.free_group import group_theory.abelianization import algebra.module.basic -- we use the ℤ-module structure on an add_comm_group in punit_equiv /-! # Free abelian groups The free abelian group on a type `α`, defined as the abelianisation of the free group on `α`. The free abelian group on `α` can be abstractly defined as the left adjoint of the forgetful functor from abelian groups to types. Alternatively, one could define it as the functions `α → ℤ` which send all but finitely many `(a : α)` to `0`, under pointwise addition. In this file, it is defined as the abelianisation of the free group on `α`. All the constructions and theorems required to show the adjointness of the construction and the forgetful functor are proved in this file, but the category-theoretic adjunction statement is in `algebra.category.Group.adjunctions` . ## Main definitions Here we use the following variables: `(α β : Type*) (A : Type*) [add_comm_group A]` * `free_abelian_group α` : the free abelian group on a type `α`. As an abelian group it is `α →₀ ℤ`, the functions from `α` to `ℤ` such that all but finitely many elements get mapped to zero, however this is not how it is implemented. * `lift f : free_abelian_group α →+ A` : the group homomorphism induced by the map `f : α → A`. * `map (f : α → β) : free_abelian_group α →+ free_abelian_group β` : functoriality of `free_abelian_group` * `instance [monoid α] : semigroup (free_abelian_group α)` * `instance [comm_monoid α] : comm_ring (free_abelian_group α)` It has been suggested that we would be better off refactoring this file and using `finsupp` instead. ## Implementation issues The definition is `def free_abelian_group : Type u := additive $ abelianization $ free_group α` Chris Hughes has suggested that this all be rewritten in terms of `finsupp`. Johan Commelin has written all the API relating the definition to `finsupp` in the lean-liquid repo. The lemmas `map_pure`, `map_of`, `map_zero`, `map_add`, `map_neg` and `map_sub` are proved about the `functor.map` `<$>` construction, and need `α` and `β` to be in the same universe. But `free_abelian_group.map (f : α → β)` is defined to be the `add_group` homomorphism `free_abelian_group α →+ free_abelian_group β` (with `α` and `β` now allowed to be in different universes), so `(map f).map_add` etc can be used to prove that `free_abelian_group.map` preserves addition. The functions `map_id`, `map_id_apply`, `map_comp`, `map_comp_apply` and `map_of_apply` are about `free_abelian_group.map`. -/ universes u v variables (α : Type u) /-- The free abelian group on a type. -/ def free_abelian_group : Type u := additive $ abelianization $ free_group α instance : add_comm_group (free_abelian_group α) := @additive.add_comm_group _ $ abelianization.comm_group _ instance : inhabited (free_abelian_group α) := ⟨0⟩ variable {α} namespace free_abelian_group /-- The canonical map from α to `free_abelian_group α` -/ def of (x : α) : free_abelian_group α := abelianization.of $ free_group.of x /-- The map `free_abelian_group α →+ A` induced by a map of types `α → A`. -/ def lift {β : Type v} [add_comm_group β] : (α → β) ≃ (free_abelian_group α →+ β) := (@free_group.lift _ (multiplicative β) _).trans $ (@abelianization.lift _ _ (multiplicative β) _).trans monoid_hom.to_additive namespace lift variables {β : Type v} [add_comm_group β] (f : α → β) open free_abelian_group @[simp] protected lemma of (x : α) : lift f (of x) = f x := begin convert @abelianization.lift.of (free_group α) _ (multiplicative β) _ _ _, convert free_group.lift.of.symm end protected theorem unique (g : free_abelian_group α →+ β) (hg : ∀ x, g (of x) = f x) {x} : g x = lift f x := add_monoid_hom.congr_fun ((lift.symm_apply_eq).mp (funext hg : g ∘ of = f)) _ /-- See note [partially-applied ext lemmas]. -/ @[ext] protected theorem ext (g h : free_abelian_group α →+ β) (H : ∀ x, g (of x) = h (of x)) : g = h := lift.symm.injective $ funext H lemma map_hom {α β γ} [add_comm_group β] [add_comm_group γ] (a : free_abelian_group α) (f : α → β) (g : β →+ γ) : g (lift f a) = lift (g ∘ f) a := begin suffices : (g.comp (lift f)) a = lift (g ∘ f) a, exact this, apply @lift.unique, assume a, show g ((lift f) (of a)) = g (f a), simp only [(∘), lift.of], end end lift section open_locale classical lemma of_injective : function.injective (of : α → free_abelian_group α) := λ x y hoxy, classical.by_contradiction $ assume hxy : x ≠ y, let f : free_abelian_group α →+ ℤ := lift (λ z, if x = z then (1 : ℤ) else 0) in have hfx1 : f (of x) = 1, from (lift.of _ _).trans $ if_pos rfl, have hfy1 : f (of y) = 1, from hoxy ▸ hfx1, have hfy0 : f (of y) = 0, from (lift.of _ _).trans $ if_neg hxy, one_ne_zero $ hfy1.symm.trans hfy0 end local attribute [instance] quotient_group.left_rel @[elab_as_eliminator] protected theorem induction_on {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ of x) (Cn : ∀ x, C (of x) → C (-of x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := quotient.induction_on' z $ λ x, quot.induction_on x $ λ L, list.rec_on L C0 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cp _ _ (Cn _ (C1 x)) ih) (Cp _ _ (C1 x) ih) theorem lift.add' {α β} [add_comm_group β] (a : free_abelian_group α) (f g : α → β) : lift (f + g) a = lift f a + lift g a := begin refine free_abelian_group.induction_on a _ _ _ _, { simp only [(lift _).map_zero, zero_add] }, { assume x, simp only [lift.of, pi.add_apply] }, { assume x h, simp only [(lift _).map_neg, lift.of, pi.add_apply, neg_add] }, { assume x y hx hy, simp only [(lift _).map_add, hx, hy, add_add_add_comm] } end /-- If `g : free_abelian_group X` and `A` is an abelian group then `lift_add_group_hom g` is the additive group homomorphism sending a function `X → A` to the term of type `A` corresponding to the evaluation of the induced map `free_abelian_group X → A` at `g`. -/ @[simps] def lift_add_group_hom {α} (β) [add_comm_group β] (a : free_abelian_group α) : (α → β) →+ β := add_monoid_hom.mk' (λ f, lift f a) (lift.add' a) section monad variables {β : Type u} instance : monad free_abelian_group.{u} := { pure := λ α, of, bind := λ α β x f, lift f x } @[elab_as_eliminator] protected theorem induction_on' {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ pure x) (Cn : ∀ x, C (pure x) → C (-pure x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := free_abelian_group.induction_on z C0 C1 Cn Cp @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_abelian_group α) = pure (f x) := rfl @[simp] lemma map_zero (f : α → β) : f <$> (0 : free_abelian_group α) = 0 := (lift (of ∘ f)).map_zero @[simp] lemma map_add (f : α → β) (x y : free_abelian_group α) : f <$> (x + y) = f <$> x + f <$> y := (lift _).map_add _ _ @[simp] lemma map_neg (f : α → β) (x : free_abelian_group α) : f <$> (-x) = -(f <$> x) := (lift _).map_neg _ @[simp] lemma map_sub (f : α → β) (x y : free_abelian_group α) : f <$> (x - y) = f <$> x - f <$> y := (lift _).map_sub _ _ @[simp] lemma map_of (f : α → β) (y : α) : f <$> of y = of (f y) := rfl @[simp] lemma pure_bind (f : α → free_abelian_group β) (x) : pure x >>= f = f x := lift.of _ _ @[simp] lemma zero_bind (f : α → free_abelian_group β) : 0 >>= f = 0 := (lift f).map_zero @[simp] lemma add_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x + y >>= f = (x >>= f) + (y >>= f) := (lift _).map_add _ _ @[simp] lemma neg_bind (f : α → free_abelian_group β) (x : free_abelian_group α) : -x >>= f = -(x >>= f) := (lift _).map_neg _ @[simp] lemma sub_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x - y >>= f = (x >>= f) - (y >>= f) := (lift _).map_sub _ _ @[simp] lemma pure_seq (f : α → β) (x : free_abelian_group α) : pure f <*> x = f <$> x := pure_bind _ _ @[simp] lemma zero_seq (x : free_abelian_group α) : (0 : free_abelian_group (α → β)) <*> x = 0 := zero_bind _ @[simp] lemma add_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f + g <*> x = (f <*> x) + (g <*> x) := add_bind _ _ _ @[simp] lemma neg_seq (f : free_abelian_group (α → β)) (x : free_abelian_group α) : -f <*> x = -(f <*> x) := neg_bind _ _ @[simp] lemma sub_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f - g <*> x = (f <*> x) - (g <*> x) := sub_bind _ _ _ /-- If `f : free_abelian_group (α → β)`, then `f <*>` is an additive morphism `free_abelian_group α →+ free_abelian_group β`. -/ def seq_add_group_hom (f : free_abelian_group (α → β)) : free_abelian_group α →+ free_abelian_group β := add_monoid_hom.mk' ((<*>) f) (λ x y, show lift (<$> (x+y)) _ = _, by { simp only [map_add], exact lift.add' f _ _, }) @[simp] lemma seq_zero (f : free_abelian_group (α → β)) : f <*> 0 = 0 := (seq_add_group_hom f).map_zero @[simp] lemma seq_add (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x + y) = (f <*> x) + (f <*> y) := (seq_add_group_hom f).map_add x y @[simp] lemma seq_neg (f : free_abelian_group (α → β)) (x : free_abelian_group α) : f <*> (-x) = -(f <*> x) := (seq_add_group_hom f).map_neg x @[simp] lemma seq_sub (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x - y) = (f <*> x) - (f <*> y) := (seq_add_group_hom f).map_sub x y instance : is_lawful_monad free_abelian_group.{u} := { id_map := λ α x, free_abelian_group.induction_on' x (map_zero id) (λ x, map_pure id x) (λ x ih, by rw [map_neg, ih]) (λ x y ihx ihy, by rw [map_add, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_abelian_group.induction_on' x (by iterate 3 { rw zero_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw neg_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw add_bind }; rw [ihx, ihy]) } instance : is_comm_applicative free_abelian_group.{u} := { commutative_prod := λ α β x y, free_abelian_group.induction_on' x (by rw [map_zero, zero_seq, seq_zero]) (λ p, by rw [map_pure, pure_seq]; exact free_abelian_group.induction_on' y (by rw [map_zero, map_zero, zero_seq]) (λ q, by rw [map_pure, map_pure, pure_seq, map_pure]) (λ q ih, by rw [map_neg, map_neg, neg_seq, ih]) (λ y₁ y₂ ih1 ih2, by rw [map_add, map_add, add_seq, ih1, ih2])) (λ p ih, by rw [map_neg, neg_seq, seq_neg, ih]) (λ x₁ x₂ ih1 ih2, by rw [map_add, add_seq, seq_add, ih1, ih2]) } end monad universe w variables {β : Type v} {γ : Type w} /-- The additive group homomorphism `free_abelian_group α →+ free_abelian_group β` induced from a map `α → β` -/ def map (f : α → β) : free_abelian_group α →+ free_abelian_group β := lift (of ∘ f) lemma lift_comp {α} {β} {γ} [add_comm_group γ] (f : α → β) (g : β → γ) (x : free_abelian_group α) : lift (g ∘ f) x = lift g (map f x) := begin apply free_abelian_group.induction_on x, { exact add_monoid_hom.map_zero _ }, { intro y, refl }, { intros x h, simp only [h, add_monoid_hom.map_neg] }, { intros x y h₁ h₂, simp only [h₁, h₂, add_monoid_hom.map_add] } end lemma map_id : map id = add_monoid_hom.id (free_abelian_group α) := eq.symm $ lift.ext _ _ $ λ x, lift.unique of (add_monoid_hom.id _) $ λ y, add_monoid_hom.id_apply _ _ lemma map_id_apply (x : free_abelian_group α) : map id x = x := by {rw map_id, refl } lemma map_comp {f : α → β} {g : β → γ} : map (g ∘ f) = (map g).comp (map f) := eq.symm $ lift.ext _ _ $ λ x, eq.symm $ lift_comp _ _ _ lemma map_comp_apply {f : α → β} {g : β → γ} (x : free_abelian_group α) : map (g ∘ f) x = (map g) ((map f) x) := by { rw map_comp, refl } -- version of map_of which uses `map` @[simp] lemma map_of_apply {f : α → β} (a : α) : map f (of a) = of (f a) := rfl variable (α) section monoid variables {R : Type*} [monoid α] [ring R] instance : semigroup (free_abelian_group α) := { mul := λ x, lift $ λ x₂, lift (λ x₁, of $ x₁ * x₂) x, mul_assoc := λ x y z, begin unfold has_mul.mul, refine free_abelian_group.induction_on z (by simp) _ _ _, { intros L3, rw [lift.of, lift.of], refine free_abelian_group.induction_on y (by simp) _ _ _, { intros L2, iterate 3 { rw lift.of }, refine free_abelian_group.induction_on x (by simp) _ _ _, { intros L1, iterate 3 { rw lift.of }, congr' 1, exact mul_assoc _ _ _ }, { intros L1 ih, iterate 3 { rw (lift _).map_neg }, rw ih }, { intros x1 x2 ih1 ih2, iterate 3 { rw (lift _).map_add }, rw [ih1, ih2] } }, { intros L2 ih, iterate 4 { rw (lift _).map_neg }, rw ih }, { intros y1 y2 ih1 ih2, iterate 4 { rw (lift _).map_add }, rw [ih1, ih2] } }, { intros L3 ih, iterate 3 { rw (lift _).map_neg }, rw ih }, { intros z1 z2 ih1 ih2, iterate 2 { rw (lift _).map_add }, rw [ih1, ih2], exact ((lift _).map_add _ _).symm } end } variable {α} lemma mul_def (x y : free_abelian_group α) : x * y = lift (λ x₂, lift (λ x₁, of (x₁ * x₂)) x) y := rfl lemma of_mul_of (x y : α) : of x * of y = of (x * y) := rfl lemma of_mul (x y : α) : of (x * y) = of x * of y := rfl variable (α) instance : ring (free_abelian_group α) := { one := free_abelian_group.of 1, mul_one := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, rw lift.of, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, erw [lift.of], congr' 1, exact mul_one L }, { intros L ih, rw [(lift _).map_neg, ih] }, { intros x1 x2 ih1 ih2, rw [(lift _).map_add, ih1, ih2] } end, one_mul := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, rw [lift.of, lift.of], congr' 1, exact one_mul L }, { intros L ih, rw [(lift _).map_neg, ih] }, { intros x1 x2 ih1 ih2, rw [(lift _).map_add, ih1, ih2] } end, left_distrib := λ x y z, (lift _).map_add _ _, right_distrib := λ x y z, begin unfold has_mul.mul semigroup.mul, refine free_abelian_group.induction_on z rfl _ _ _, { intros L, iterate 3 { rw lift.of }, rw (lift _).map_add, refl }, { intros L ih, iterate 3 { rw (lift _).map_neg }, rw [ih, neg_add], refl }, { intros z1 z2 ih1 ih2, iterate 3 { rw (lift _).map_add }, rw [ih1, ih2], rw [add_assoc, add_assoc], congr' 1, apply add_left_comm } end, .. free_abelian_group.add_comm_group α, .. free_abelian_group.semigroup α } variable {α} /-- `free_abelian_group.of` is a `monoid_hom` when `α` is a `monoid`. -/ def of_mul_hom : α →* free_abelian_group α := { to_fun := of, map_one' := rfl, map_mul' := of_mul } @[simp] lemma of_mul_hom_coe : (of_mul_hom : α → free_abelian_group α) = of := rfl /-- If `f` preserves multiplication, then so does `lift f`. -/ def lift_monoid : (α →* R) ≃ (free_abelian_group α →+* R) := { to_fun := λ f, { map_one' := (lift.of f _).trans f.map_one, map_mul' := λ x y, begin simp only [add_monoid_hom.to_fun_eq_coe], refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros L2, rw mul_def x, simp only [lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros L1, iterate 3 { rw lift.of }, exact f.map_mul _ _ }, { intros L1 ih, iterate 3 { rw (lift _).map_neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw (lift _).map_add }, rw [ih1, ih2, add_mul] } }, { intros L2 ih, rw [mul_neg, add_monoid_hom.map_neg, add_monoid_hom.map_neg, mul_neg, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, mul_add, ih1, ih2] }, end, .. lift f }, inv_fun := λ F, monoid_hom.comp ↑F of_mul_hom, left_inv := λ f, monoid_hom.ext $ lift.of _, right_inv := λ F, ring_hom.coe_add_monoid_hom_injective $ lift.apply_symm_apply (↑F : free_abelian_group α →+ R) } @[simp] lemma lift_monoid_coe_add_monoid_hom (f : α →* R) : ↑(lift_monoid f) = lift f := rfl @[simp] lemma lift_monoid_coe (f : α →* R) : ⇑(lift_monoid f) = lift f := rfl @[simp] lemma lift_monoid_symm_coe (f : free_abelian_group α →+* R) : ⇑(lift_monoid.symm f) = lift.symm ↑f := rfl lemma one_def : (1 : free_abelian_group α) = of 1 := rfl lemma of_one : (of 1 : free_abelian_group α) = 1 := rfl end monoid instance [comm_monoid α] : comm_ring (free_abelian_group α) := { mul_comm := λ x y, begin refine free_abelian_group.induction_on x (zero_mul y) _ _ _, { intros s, refine free_abelian_group.induction_on y (zero_mul _).symm _ _ _, { intros t, unfold has_mul.mul semigroup.mul ring.mul, iterate 4 { rw lift.of }, congr' 1, exact mul_comm _ _ }, { intros t ih, rw [mul_neg, ih, neg_mul_eq_neg_mul] }, { intros y1 y2 ih1 ih2, rw [mul_add, add_mul, ih1, ih2] } }, { intros s ih, rw [neg_mul, ih, neg_mul_eq_mul_neg] }, { intros x1 x2 ih1 ih2, rw [add_mul, mul_add, ih1, ih2] } end, .. free_abelian_group.ring α } instance pempty_unique : unique (free_abelian_group pempty) := { default := 0, uniq := λ x, free_abelian_group.induction_on x rfl (λ x, pempty.elim x) (λ x, pempty.elim x) (by { rintros - - rfl rfl, simp }) } /-- The free abelian group on a type with one term is isomorphic to `ℤ`. -/ def punit_equiv (T : Type*) [unique T] : free_abelian_group T ≃+ ℤ := { to_fun := free_abelian_group.lift (λ _, (1 : ℤ)), inv_fun := λ n, n • of (inhabited.default), left_inv := λ z, free_abelian_group.induction_on z (by simp only [zero_smul, add_monoid_hom.map_zero]) (unique.forall_iff.2 $ by simp only [one_smul, lift.of]) (unique.forall_iff.2 $ by simp) (λ x y hx hy, by { simp only [add_monoid_hom.map_add, add_smul] at *, rw [hx, hy]}), right_inv := λ n, begin rw [add_monoid_hom.map_zsmul, lift.of], exact zsmul_int_one n end, map_add' := add_monoid_hom.map_add _ } /-- Isomorphic types have isomorphic free abelian groups. -/ def equiv_of_equiv {α β : Type*} (f : α ≃ β) : free_abelian_group α ≃+ free_abelian_group β := { to_fun := map f, inv_fun := map f.symm, left_inv := begin intros x, rw [← map_comp_apply, equiv.symm_comp_self, map_id], refl, end, right_inv := begin intros x, rw [← map_comp_apply, equiv.self_comp_symm, map_id], refl, end, map_add' := add_monoid_hom.map_add _ } end free_abelian_group
23aaae3bb3ce1a32a9e1e3598a2f155da534f906
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/smt_begin_end1.lean
9db40378edbe8247b45635b8dd0b51b647c51a29
[ "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
728
lean
constant p : nat → nat → Prop constant f : nat → nat axiom pf (a : nat) : p (f a) (f a) → p a a example (a b c : nat) : a = b → p (f a) (f b) → p a b := begin [smt] intros, have h : p (f a) (f a), trace_state, add_fact (pf _ h) end example (p q : Prop) : p ∨ q → p ∨ ¬q → ¬p ∨ q → ¬p ∨ ¬q → false := begin [smt] by_cases p, end example (a b c : nat) : a = b → p (f a) (f b) → p a b := begin intro h, subst h, begin [smt] intros, have h₁ : p (f a) (f a), trace_state, add_fact (pf _ h₁) end end example (p q : Prop) : p ∨ q → p ∨ ¬q → ¬p ∨ q → p ∧ q := begin [smt] intros, tactic.split, { by_cases p }, { by_cases p } end
a82b77109afbacb426217626cc489266757703b9
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/finset/lattice.lean
3c721d8305246d2e6dc85da3ce93c973609b3fc6
[ "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
16,659
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.fold import data.multiset.lattice /-! # Lattice operations on multisets -/ variables {α β γ : Type*} namespace finset open multiset /-! ### sup -/ section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b := sup_singleton lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := begin apply iff.trans multiset.sup_le, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := sup_le_iff.2 lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := sup_le_iff.1 (le_refl _) _ hb lemma sup_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.sup f ≤ s.sup g := sup_le (λ b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [semilattice_sup_bot γ] {s : finset β} {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [g_sup] {contextual := tt}) lemma comp_sup_eq_sup_comp_of_is_total [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) /-! ### inf -/ section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_val : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀b ∈ s, a ≤ f b := @sup_le_iff (order_dual α) _ _ _ _ _ @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b := inf_singleton lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := @sup_union (order_dual α) _ _ _ _ _ _ theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := le_inf_iff.1 (le_refl _) _ hb lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := le_inf_iff.2 lemma inf_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.inf f ≤ s.inf g := le_inf (λ b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf_iff [h : is_total α (≤)] {a : α} (ha : a < ⊤) : a < s.inf f ↔ (∀b ∈ s, a < f b) := @sup_lt_iff (order_dual α) _ _ _ _ (@is_total.swap α _ h) _ ha lemma comp_inf_eq_inf_comp [semilattice_inf_top γ] {s : finset β} {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp (order_dual α) _ (order_dual γ) _ _ _ _ _ g_inf top lemma comp_inf_eq_inf_comp_of_is_total [h : is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := @sup_eq_supr _ (order_dual β) _ _ _ /-! ### max and min of finite sets -/ section max_min variables [decidable_linear_order α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `option α`. -/ def min' (s : finset α) (H : s.nonempty) : α := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `option α`. -/ def max' (s : finset α) (H : s.nonempty) : α := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset α) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' H ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' H < s.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le s H i H1, have H6 := le_max' s H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le s H j H2, have H6 := le_max' s H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ lemma min'_lt_max'_of_card (h₂ : 1 < card s) : s.min' H < s.max' H := begin apply lt_of_not_ge, intro a, apply not_le_of_lt h₂ (le_of_eq _), rw card_eq_one, use max' s H, rw eq_singleton_iff_unique_mem, refine ⟨max'_mem _ _, λ t Ht, le_antisymm (le_max' s H t Ht) (le_trans a (min'_le s H t Ht))⟩, end end max_min section exists_max_min variables [linear_order α] lemma exists_max_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := begin letI := classical.DLO α, cases max_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩, end lemma exists_min_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := @exists_max_image (order_dual α) β _ s f h end exists_max_min end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset section lattice variables {ι : Sort*} [complete_lattice α] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := @supr_eq_supr_finset (order_dual α) _ _ _ end lattice namespace set variables {ι : Sort*} lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := infi_eq_infi_finset s end set namespace finset /-! ### Interaction with big lattice/set operations -/ section lattice lemma supr_coe [has_Sup β] (f : α → β) (s : finset α) : (⨆ x ∈ (↑s : set α), f x) = ⨆ x ∈ s, f x := rfl lemma infi_coe [has_Inf β] (f : α → β) (s : finset α) : (⨅ x ∈ (↑s : set α), f x) = ⨅ x ∈ s, f x := rfl variables [complete_lattice β] theorem supr_singleton (a : α) (s : α → β) : (⨆ x ∈ ({a} : finset α), s x) = s a := by simp theorem infi_singleton (a : α) (s : α → β) : (⨅ x ∈ ({a} : finset α), s x) = s a := by simp variables [decidable_eq α] theorem supr_union {f : α → β} {s t : finset α} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := by simp [supr_or, supr_sup_eq] theorem infi_union {f : α → β} {s t : finset α} : (⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) := by simp [infi_or, infi_inf_eq] lemma supr_insert (a : α) (s : finset α) (t : α → β) : (⨆ x ∈ insert a s, t x) = t a ⊔ (⨆ x ∈ s, t x) := by { rw insert_eq, simp only [supr_union, finset.supr_singleton] } lemma infi_insert (a : α) (s : finset α) (t : α → β) : (⨅ x ∈ insert a s, t x) = t a ⊓ (⨅ x ∈ s, t x) := by { rw insert_eq, simp only [infi_union, finset.infi_singleton] } lemma supr_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) := by rw [← supr_coe, coe_image, supr_image, supr_coe] lemma infi_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨅ x ∈ s.image f, g x) = (⨅ y ∈ s, g (f y)) := by rw [← infi_coe, coe_image, infi_image, infi_coe] end lattice @[simp] theorem bUnion_coe (s : finset α) (t : α → set β) : (⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x := rfl @[simp] theorem bInter_coe (s : finset α) (t : α → set β) : (⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x := rfl @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton a s @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : finset α), s x) = s a := infi_singleton a s variables [decidable_eq α] lemma bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union lemma bInter_inter (s t : finset α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union @[simp] lemma bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := supr_insert a s t @[simp] lemma bInter_insert (a : α) (s : finset α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := infi_insert a s t @[simp] lemma bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) := supr_finset_image @[simp] lemma bInter_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋂ x ∈ s.image f, g x) = (⋂ y ∈ s, g (f y)) := infi_finset_image end finset
080337eee5ad97c9f7d25a959b615cedb4ffd945
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/unsigned/basic.lean
c070966bad51ce633b9662255c5ab87c1c89c58e
[ "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
861
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.data.fin.basic open nat def unsigned_sz : nat := succ 4294967295 def unsigned := fin unsigned_sz namespace unsigned /- We cannot use tactic dec_trivial here because the tactic framework has not been defined yet. -/ private lemma zero_lt_unsigned_sz : 0 < unsigned_sz := zero_lt_succ _ /- Later, we define of_nat using mod, the following version is used to define the metaprogramming system. -/ protected def of_nat' (n : nat) : unsigned := if h : n < unsigned_sz then ⟨n, h⟩ else ⟨0, zero_lt_unsigned_sz⟩ def to_nat (c : unsigned) : nat := c.val end unsigned instance : decidable_eq unsigned := have decidable_eq (fin unsigned_sz), from fin.decidable_eq _, this
2831e866d64bf4ae739ee7c2099869e86f23f0e2
7571914d3f4d9677288f35ab1a53a2ad70a62bd7
/library/init/meta/interactive_base.lean
2204d3e88ec1b58501e17a4980675baad4ada324
[ "Apache-2.0" ]
permissive
picrin/lean-1
a395fed5287995f09a15a190bb24609919a0727f
b50597228b42a7eaa01bf8cb7a4fb1a98e7a8aab
refs/heads/master
1,610,757,735,162
1,502,008,413,000
1,502,008,413,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,079
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.data.option.instances import init.meta.lean.parser init.meta.tactic init.meta.has_reflect open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace interactive /-- (parse p) as the parameter type of an interactive tactic will instruct the Lean parser to run `p` when parsing the parameter and to pass the parsed value as an argument to the tactic. -/ @[reducible] meta def parse {α : Type} [has_reflect α] (p : parser α) : Type := α inductive loc : Type | wildcard : loc | ns : list (option name) → loc meta instance : has_reflect loc | loc.wildcard := `(_) | (loc.ns xs) := `(_) meta def loc.include_goal : loc → bool | loc.wildcard := tt | (loc.ns ls) := (ls.map option.is_none).bor meta def loc.get_locals : loc → tactic (list expr) | loc.wildcard := tactic.local_context | (loc.ns xs) := xs.mfoldl (λ ls n, match n with | none := pure ls | some n := do l ← tactic.get_local n, pure $ l :: ls end) [] meta def loc.apply (hyp_tac : expr → tactic unit) (goal_tac : tactic unit) (l : loc) : tactic unit := do hs ← l.get_locals, hs.mmap' hyp_tac, if l.include_goal then goal_tac else pure () meta def loc.try_apply (hyp_tac : expr → tactic unit) (goal_tac : tactic unit) (l : loc) : tactic unit := do hs ← l.get_locals, let hts := hs.map hyp_tac, tactic.try_lst $ if l.include_goal then hts ++ [goal_tac] else hts /-- Use `desc` as the interactive description of `p`. -/ meta def with_desc {α : Type} (desc : format) (p : parser α) : parser α := p namespace types variables {α β : Type} -- optimized pretty printer meta def brackets (l r : string) (p : parser α) := tk l *> p <* tk r meta def list_of (p : parser α) := brackets "[" "]" $ sep_by (skip_info (tk ",")) p /-- A 'tactic expression', which uses right-binding power 2 so that it is terminated by '<|>' (rbp 2), ';' (rbp 1), and ',' (rbp 0). It should be used for any (potentially) trailing expression parameters. -/ meta def texpr := parser.pexpr 2 /-- Parse an identifier or a '_' -/ meta def ident_ : parser name := ident <|> tk "_" *> return `_ meta def using_ident := (tk "using" *> ident)? meta def with_ident_list := (tk "with" *> ident_*) <|> return [] meta def without_ident_list := (tk "without" *> ident*) <|> return [] meta def location := (tk "at" *> (tk "*" *> return loc.wildcard <|> (loc.ns <$> (((with_desc "⊢" $ tk "⊢" <|> tk "|-") *> return none) <|> some <$> ident)*))) <|> return (loc.ns [none]) meta def pexpr_list := list_of (parser.pexpr 0) meta def opt_pexpr_list := pexpr_list <|> return [] meta def pexpr_list_or_texpr := pexpr_list <|> list.ret <$> texpr meta def only_flag : parser bool := (tk "only" *> return tt) <|> return ff end types precedence only:0 open expr format tactic types private meta def maybe_paren : list format → format | [] := "" | [f] := f | fs := paren (join fs) private meta def unfold (e : expr) : tactic expr := do (expr.const f_name f_lvls) ← return e.get_app_fn | failed, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, head_beta (expr.mk_app new_f e.get_app_args) private meta def concat (f₁ f₂ : list format) := if f₁.empty then f₂ else if f₂.empty then f₁ else f₁ ++ [" "] ++ f₂ private meta def parser_desc_aux : expr → tactic (list format) | `(ident) := return ["id"] | `(ident_) := return ["id"] | `(parser.pexpr) := return ["expr"] | `(tk %%c) := list.ret <$> to_fmt <$> eval_expr string c | `(cur_pos) := return [] | `(pure ._) := return [] | `(._ <$> %%p) := parser_desc_aux p | `(skip_info %%p) := parser_desc_aux p | `(set_goal_info_pos %%p) := parser_desc_aux p | `(with_desc %%desc %%p) := list.ret <$> eval_expr format desc | `(%%p₁ <*> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(%%p₁ <* %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(%%p₁ *> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(many %%p) := do f ← parser_desc_aux p, return [maybe_paren f ++ "*"] | `(optional %%p) := do f ← parser_desc_aux p, return [maybe_paren f ++ "?"] | `(sep_by %%sep %%p) := do f₁ ← parser_desc_aux sep, f₂ ← parser_desc_aux p, return [maybe_paren f₂ ++ join f₁, " ..."] | `(%%p₁ <|> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ if f₁.empty then [maybe_paren f₂ ++ "?"] else if f₂.empty then [maybe_paren f₁ ++ "?"] else [paren $ join $ f₁ ++ [to_fmt " | "] ++ f₂] | `(brackets %%l %%r %%p) := do f ← parser_desc_aux p, l ← eval_expr string l, r ← eval_expr string r, -- much better than the naive [l, " ", f, " ", r] return [to_fmt l ++ join f ++ to_fmt r] | e := do e' ← (do e' ← unfold e, guard $ e' ≠ e, return e') <|> (do f ← pp e, fail $ to_fmt "don't know how to pretty print " ++ f), parser_desc_aux e' meta def param_desc : expr → tactic format | `(parse %%p) := join <$> parser_desc_aux p | `(opt_param %%t ._) := (++ "?") <$> pp t | e := if is_constant e ∧ (const_name e).components.ilast = `itactic then return $ to_fmt "{ tactic }" else paren <$> pp e private meta constant parse_binders_core (rbp : ℕ) : parser (list pexpr) meta def parse_binders (rbp := std.prec.max) := with_desc "<binders>" (parse_binders_core rbp) meta constant decl_attributes : Type meta constant decl_attributes.apply : decl_attributes → name → parser unit meta structure decl_modifiers := (is_private : bool) (is_protected : bool) (is_meta : bool) (is_mutual : bool) (is_noncomputable : bool) meta structure decl_meta_info := (attrs : decl_attributes) (modifiers : decl_modifiers) (doc_string : option string) meta structure single_inductive_decl := (attrs : decl_attributes) (sig : expr) (intros : list expr) meta def single_inductive_decl.name (d : single_inductive_decl) : name := d.sig.app_fn.const_name meta structure inductive_decl := (u_names : list name) (params : list expr) (decls : list single_inductive_decl) /-- Parses and elaborates a single or multiple mutual inductive declarations (without the `inductive` keyword), depending on `is_mutual` -/ meta constant inductive_decl.parse : decl_meta_info → parser inductive_decl end interactive section macros open interaction_monad open interactive private meta def parse_format : string → list char → parser pexpr | acc [] := pure ``(to_fmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_format "" s, pure ``(to_fmt %%(reflect acc) ++ format.line ++ %%f) | acc ('{'::'{'::s) := parse_format (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_format "" s, pure ``(to_fmt %%(reflect acc) ++ to_fmt %%e ++ %%f) | acc (c::s) := parse_format (acc.str c) s reserve prefix `format! `:100 @[user_notation] meta def format_macro (_ : parse $ tk "format!") (s : string) : parser pexpr := parse_format "" s.to_list private meta def parse_sformat : string → list char → parser pexpr | acc [] := pure $ pexpr.of_expr (reflect acc) | acc ('{'::'{'::s) := parse_sformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_sformat "" s, pure ``(%%(reflect acc) ++ to_string %%e ++ %%f) | acc (c::s) := parse_sformat (acc.str c) s reserve prefix `sformat! `:100 @[user_notation] meta def sformat_macro (_ : parse $ tk "sformat!") (s : string) : parser pexpr := parse_sformat "" s.to_list end macros
a84745d0f34088c4087ed64a0dfab5700cc5cfc4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/list/infix.lean
1d8d58e50fd64dbb6a9b34f76279e32f061f4779
[ "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
21,368
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.basic /-! # Prefixes, subfixes, infixes This file proves properties about * `list.prefix`: `l₁` is a prefix of `l₂` if `l₂` starts with `l₁`. * `list.subfix`: `l₁` is a subfix of `l₂` if `l₂` ends with `l₁`. * `list.infix`: `l₁` is an infix of `l₂` if `l₁` is a prefix of some subfix of `l₂`. * `list.inits`: The list of prefixes of a list. * `list.tails`: The list of prefixes of a list. * `insert` on lists All those (except `insert`) are defined in `data.list.defs`. ## Notation `l₁ <+: l₂`: `l₁` is a prefix of `l₂`. `l₁ <:+ l₂`: `l₁` is a subfix of `l₂`. `l₁ <:+: l₂`: `l₁` is an infix of `l₂`. -/ open nat variables {α β : Type*} namespace list variables {l l₁ l₂ l₃ : list α} {a b : α} {m n : ℕ} /-! ### prefix, suffix, infix -/ section fix @[simp] lemma prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] lemma suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ lemma infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] lemma infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append lemma is_prefix.is_infix : l₁ <+: l₂ → l₁ <:+: l₂ := λ ⟨t, h⟩, ⟨[], t, h⟩ lemma is_suffix.is_infix : l₁ <:+ l₂ → l₁ <:+: l₂ := λ ⟨t, h⟩, ⟨t, [], by rw [h, append_nil]⟩ lemma nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ lemma nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ lemma nil_infix (l : list α) : [] <:+: l := (nil_prefix _).is_infix @[refl] lemma prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] lemma suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[refl] lemma infix_refl (l : list α) : l <:+: l := (prefix_refl l).is_infix lemma prefix_rfl : l <+: l := prefix_refl _ lemma suffix_rfl : l <:+ l := suffix_refl _ lemma infix_rfl : l <:+: l := infix_refl _ @[simp] lemma suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] lemma prefix_concat (a : α) (l) : l <+: concat l a := by simp lemma infix_cons : l₁ <:+: l₂ → l₁ <:+: a :: l₂ := λ ⟨L₁, L₂, h⟩, ⟨a :: L₁, L₂, h ▸ rfl⟩ lemma infix_concat : l₁ <:+: l₂ → l₁ <:+: concat l₂ a := λ ⟨L₁, L₂, h⟩, ⟨L₁, concat L₂ a, by simp_rw [←h, concat_eq_append, append_assoc]⟩ @[trans] lemma is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] lemma is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] lemma is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ protected lemma is_infix.sublist : l₁ <:+: l₂ → l₁ <+ l₂ := λ ⟨s, t, h⟩, by { rw [← h], exact (sublist_append_right _ _).trans (sublist_append_left _ _) } protected lemma is_infix.subset (hl : l₁ <:+: l₂) : l₁ ⊆ l₂ := hl.sublist.subset protected lemma is_prefix.sublist (h : l₁ <+: l₂) : l₁ <+ l₂ := h.is_infix.sublist protected lemma is_prefix.subset (hl : l₁ <+: l₂) : l₁ ⊆ l₂ := hl.sublist.subset protected lemma is_suffix.sublist (h : l₁ <:+ l₂) : l₁ <+ l₂ := h.is_infix.sublist protected lemma is_suffix.subset (hl : l₁ <:+ l₂) : l₁ ⊆ l₂ := hl.sublist.subset @[simp] lemma reverse_suffix : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ @[simp] lemma reverse_prefix : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] @[simp] lemma reverse_infix : reverse l₁ <:+: reverse l₂ ↔ l₁ <:+: l₂ := ⟨λ ⟨s, t, e⟩, ⟨reverse t, reverse s, by rw [← reverse_reverse l₁, append_assoc, ← reverse_append, ← reverse_append, e, reverse_reverse]⟩, λ ⟨s, t, e⟩, ⟨reverse t, reverse s, by rw [append_assoc, ← reverse_append, ← reverse_append, e]⟩⟩ alias reverse_prefix ↔ _ is_suffix.reverse alias reverse_suffix ↔ _ is_prefix.reverse alias reverse_infix ↔ _ is_infix.reverse lemma is_infix.length_le (h : l₁ <:+: l₂) : l₁.length ≤ l₂.length := h.sublist.length_le lemma is_prefix.length_le (h : l₁ <+: l₂) : l₁.length ≤ l₂.length := h.sublist.length_le lemma is_suffix.length_le (h : l₁ <:+ l₂) : l₁.length ≤ l₂.length := h.sublist.length_le lemma eq_nil_of_infix_nil (h : l <:+: []) : l = [] := eq_nil_of_sublist_nil h.sublist @[simp] lemma infix_nil_iff : l <:+: [] ↔ l = [] := ⟨λ h, eq_nil_of_sublist_nil h.sublist, λ h, h ▸ infix_rfl⟩ alias infix_nil_iff ↔ eq_nil_of_infix_nil _ @[simp] lemma prefix_nil_iff : l <+: [] ↔ l = [] := ⟨λ h, eq_nil_of_infix_nil h.is_infix, λ h, h ▸ prefix_rfl⟩ @[simp] lemma suffix_nil_iff : l <:+ [] ↔ l = [] := ⟨λ h, eq_nil_of_infix_nil h.is_infix, λ h, h ▸ suffix_rfl⟩ alias prefix_nil_iff ↔ eq_nil_of_prefix_nil _ alias suffix_nil_iff ↔ eq_nil_of_suffix_nil _ lemma infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ ⟨._, ⟨t, rfl⟩, s, e⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ lemma eq_of_infix_of_length_eq (h : l₁ <:+: l₂) : l₁.length = l₂.length → l₁ = l₂ := h.sublist.eq_of_length lemma eq_of_prefix_of_length_eq (h : l₁ <+: l₂) : l₁.length = l₂.length → l₁ = l₂ := h.sublist.eq_of_length lemma eq_of_suffix_of_length_eq (h : l₁ <:+ l₂) : l₁.length = l₂.length → l₁ = l₂ := h.sublist.eq_of_length lemma prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a :: l₁) (b :: l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end lemma prefix_or_prefix_of_prefix (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) lemma suffix_of_suffix_length_le (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) lemma suffix_or_suffix_of_suffix (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 lemma suffix_cons_iff : l₁ <:+ a :: l₂ ↔ l₁ = a :: l₂ ∨ l₁ <:+ l₂ := begin split, { rintro ⟨⟨hd, tl⟩, hl₃⟩, { exact or.inl hl₃ }, { simp only [cons_append] at hl₃, exact or.inr ⟨_, hl₃.2⟩ } }, { rintro (rfl | hl₁), { exact (a :: l₂).suffix_refl }, { exact hl₁.trans (l₂.suffix_cons _) } } end lemma infix_cons_iff : l₁ <:+: a :: l₂ ↔ l₁ <+: a :: l₂ ∨ l₁ <:+: l₂ := begin split, { rintro ⟨⟨hd, tl⟩, t, hl₃⟩, { exact or.inl ⟨t, hl₃⟩ }, { simp only [cons_append] at hl₃, exact or.inr ⟨_, t, hl₃.2⟩ } }, { rintro (h | hl₁), { exact h.is_infix }, { exact infix_cons hl₁ } } end lemma infix_of_mem_join : ∀ {L : list (list α)}, l ∈ L → l <:+: join L | (_ :: L) (or.inl rfl) := infix_append [] _ _ | (l' :: L) (or.inr h) := is_infix.trans (infix_of_mem_join h) $ (suffix_append _ _).is_infix lemma prefix_append_right_inj (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] lemma prefix_cons_inj (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a] lemma take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ lemma drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ lemma take_sublist (n) (l : list α) : take n l <+ l := (take_prefix n l).sublist lemma drop_sublist (n) (l : list α) : drop n l <+ l := (drop_suffix n l).sublist lemma take_subset (n) (l : list α) : take n l ⊆ l := (take_sublist n l).subset lemma drop_subset (n) (l : list α) : drop n l ⊆ l := (drop_sublist n l).subset lemma mem_of_mem_take (h : a ∈ l.take n) : a ∈ l := take_subset n l h lemma mem_of_mem_drop (h : a ∈ l.drop n) : a ∈ l := drop_subset n l h lemma take_while_prefix (p : α → Prop) [decidable_pred p] : l.take_while p <+: l := ⟨l.drop_while p, take_while_append_drop p l⟩ lemma drop_while_suffix (p : α → Prop) [decidable_pred p] : l.drop_while p <:+ l := ⟨l.take_while p, take_while_append_drop p l⟩ lemma init_prefix : ∀ (l : list α), l.init <+: l | [] := ⟨nil, by rw [init, list.append_nil]⟩ | (a :: l) := ⟨_, init_append_last (cons_ne_nil a l)⟩ lemma tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix lemma init_sublist (l : list α) : l.init <+ l := (init_prefix l).sublist lemma tail_sublist (l : list α) : l.tail <+ l := (tail_suffix l).sublist lemma init_subset (l : list α) : l.init ⊆ l := (init_sublist l).subset lemma tail_subset (l : list α) : tail l ⊆ l := (tail_sublist l).subset lemma mem_of_mem_init (h : a ∈ l.init) : a ∈ l := init_subset l h lemma mem_of_mem_tail (h : a ∈ l.tail) : a ∈ l := tail_subset l h lemma prefix_iff_eq_append : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ lemma suffix_iff_eq_append : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, add_tsub_cancel_right, take_left], λ e, ⟨_, e⟩⟩ lemma prefix_iff_eq_take : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ lemma suffix_iff_eq_drop : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a :: l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a :: l₁) (b :: l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_prefix l₁ l₂) (by rw [← h, prefix_cons_inj]) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a :: l₁) [] := is_false $ mt (sublist.length_le ∘ is_suffix.sublist) dec_trivial | l₁ (b :: l₂) := decidable_of_decidable_of_iff (@or.decidable _ _ _ (l₁.decidable_suffix l₂)) suffix_cons_iff.symm instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a :: l₁) [] := is_false $ λ ⟨s, t, te⟩, by simp at te; exact te | l₁ (b :: l₂) := decidable_of_decidable_of_iff (@or.decidable _ _ (l₁.decidable_prefix (b :: l₂)) (l₁.decidable_infix l₂)) infix_cons_iff.symm lemma prefix_take_le_iff {L : list (list (option α))} (hm : m < L.length) : L.take m <+: L.take n ↔ m ≤ n := begin simp only [prefix_iff_eq_take, length_take], induction m with m IH generalizing L n, { simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] }, cases L with l ls, { exact (not_lt_bot hm).elim }, cases n, { refine iff_of_false _ (zero_lt_succ _).not_le, rw [take_zero, take_nil], simp only [take], exact not_false }, { simp only [length] at hm, specialize @IH ls n (nat.lt_of_succ_lt_succ hm), simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH, simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take], exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ } end lemma cons_prefix_iff : a :: l₁ <+: b :: l₂ ↔ a = b ∧ l₁ <+: l₂ := begin split, { rintro ⟨L, hL⟩, simp only [cons_append] at hL, exact ⟨hL.left, ⟨L, hL.right⟩⟩ }, { rintro ⟨rfl, h⟩, rwa [prefix_cons_inj] } end lemma is_prefix.map (h : l₁ <+: l₂) (f : α → β) : l₁.map f <+: l₂.map f := begin induction l₁ with hd tl hl generalizing l₂, { simp only [nil_prefix, map_nil] }, { cases l₂ with hd₂ tl₂, { simpa only using eq_nil_of_prefix_nil h }, { rw cons_prefix_iff at h, simp only [h, prefix_cons_inj, hl, map] } } end lemma is_prefix.filter_map (h : l₁ <+: l₂) (f : α → option β) : l₁.filter_map f <+: l₂.filter_map f := begin induction l₁ with hd₁ tl₁ hl generalizing l₂, { simp only [nil_prefix, filter_map_nil] }, { cases l₂ with hd₂ tl₂, { simpa only using eq_nil_of_prefix_nil h }, { rw cons_prefix_iff at h, rw [←@singleton_append _ hd₁ _, ←@singleton_append _ hd₂ _, filter_map_append, filter_map_append, h.left, prefix_append_right_inj], exact hl h.right } } end lemma is_prefix.reduce_option {l₁ l₂ : list (option α)} (h : l₁ <+: l₂) : l₁.reduce_option <+: l₂.reduce_option := h.filter_map id lemma is_prefix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <+: l₂) : l₁.filter p <+: l₂.filter p := begin obtain ⟨xs, rfl⟩ := h, rw filter_append, exact prefix_append _ _ end lemma is_suffix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <:+ l₂) : l₁.filter p <:+ l₂.filter p := begin obtain ⟨xs, rfl⟩ := h, rw filter_append, exact suffix_append _ _ end lemma is_infix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <:+: l₂) : l₁.filter p <:+: l₂.filter p := begin obtain ⟨xs, ys, rfl⟩ := h, rw [filter_append, filter_append], exact infix_append _ _ _ end instance : is_partial_order (list α) (<+:) := { refl := prefix_refl, trans := λ _ _ _, is_prefix.trans, antisymm := λ _ _ h₁ h₂, eq_of_prefix_of_length_eq h₁ $ h₁.length_le.antisymm h₂.length_le } instance : is_partial_order (list α) (<:+) := { refl := suffix_refl, trans := λ _ _ _, is_suffix.trans, antisymm := λ _ _ h₁ h₂, eq_of_suffix_of_length_eq h₁ $ h₁.length_le.antisymm h₂.length_le } instance : is_partial_order (list α) (<:+:) := { refl := infix_refl, trans := λ _ _ _, is_infix.trans, antisymm := λ _ _ h₁ h₂, eq_of_infix_of_length_eq h₁ $ h₁.length_le.antisymm h₂.length_le } end fix section inits_tails @[simp] lemma mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λ h, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a :: t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λ o, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λ mi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b :: s), ⟨r, hr⟩ := list.no_confusion hr $ λ ba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] lemma mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λ h, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a :: t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λ o, match s, t, o with | ._, t, or.inl rfl := suffix_rfl | s, ._, or.inr ⟨l, rfl⟩ := ⟨a :: l, rfl⟩ end, λ e, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b :: l, he⟩ := list.no_confusion he (λ ab lt, or.inr ⟨l, lt⟩) end⟩ lemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) := by simp lemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails := by simp @[simp] lemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l) | [] [] := by simp | [] (a :: t) := by simp | (a :: s) t := by simp [inits_append s t] @[simp] lemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail | [] [] := by simp | [] (a :: t) := by simp | (a :: s) t := by simp [tails_append s t] -- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'` lemma inits_eq_tails : ∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l) | [] := by simp | (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff] lemma tails_eq_inits : ∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l) | [] := by simp | (a :: l) := by simp [tails_eq_inits l, append_left_inj] lemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) := by { rw tails_eq_inits l, simp [reverse_involutive.comp_self] } lemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) := by { rw inits_eq_tails l, simp [reverse_involutive.comp_self] } lemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) := by { rw inits_eq_tails l, simp [reverse_involutive.comp_self] } lemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) := by { rw tails_eq_inits l, simp [reverse_involutive.comp_self] } @[simp] lemma length_tails (l : list α) : length (tails l) = length l + 1 := begin induction l with x l IH, { simp }, { simpa using IH } end @[simp] lemma length_inits (l : list α) : length (inits l) = length l + 1 := by simp [inits_eq_tails] @[simp] lemma nth_le_tails (l : list α) (n : ℕ) (hn : n < length (tails l)) : nth_le (tails l) n hn = l.drop n := begin induction l with x l IH generalizing n, { simp }, { cases n, { simp }, { simpa using IH n _ } } end @[simp] lemma nth_le_inits (l : list α) (n : ℕ) (hn : n < length (inits l)) : nth_le (inits l) n hn = l.take n := begin induction l with x l IH generalizing n, { simp }, { cases n, { simp }, { simpa using IH n _ } } end end inits_tails /-! ### insert -/ section insert variable [decidable_eq α] @[simp] lemma insert_nil (a : α) : insert a nil = [a] := rfl lemma insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] lemma insert_of_mem (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] lemma insert_of_not_mem (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] lemma mem_insert_iff : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, { simp only [insert_of_not_mem h', mem_cons_iff] } end @[simp] lemma suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] lemma infix_insert (a : α) (l : list α) : l <:+: insert a l := (suffix_insert a l).is_infix lemma sublist_insert (a : α) (l : list α) : l <+ l.insert a := (suffix_insert a l).sublist lemma subset_insert (a : α) (l : list α) : l ⊆ l.insert a := (sublist_insert a l).subset @[simp] lemma mem_insert_self (a : α) (l : list α) : a ∈ l.insert a := mem_insert_iff.2 $ or.inl rfl lemma mem_insert_of_mem (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) lemma eq_or_mem_of_mem_insert (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] lemma length_insert_of_mem (h : a ∈ l) : (insert a l).length = l.length := congr_arg _ $ insert_of_mem h @[simp] lemma length_insert_of_not_mem (h : a ∉ l) : (insert a l).length = l.length + 1 := congr_arg _ $ insert_of_not_mem h end insert lemma mem_of_mem_suffix (hx : a ∈ l₁) (hl : l₁ <:+ l₂) : a ∈ l₂ := hl.subset hx end list
fb7a22a96f680d7183c67aa9a6733b8ee5361783
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/omega/nat/preterm.lean
81d0d260ae27d9328be97f4855843260707c3d7e
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
4,875
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Linear natural number arithmetic terms in pre-normalized form. -/ import tactic.omega.term open tactic namespace omega namespace nat /-- The shadow syntax for arithmetic terms. All constants are reified to `cst` (e.g., `5` is reified to `cst 5`) and all other atomic terms are reified to `exp` (e.g., `5 * (list.length l)` is reified to `exp 5 \`(list.length l)`). `exp` accepts a coefficient of type `nat` as its first argument because multiplication by constant is allowed by the omega test. -/ meta inductive exprterm : Type | cst : nat → exprterm | exp : nat → expr → exprterm | add : exprterm → exprterm → exprterm | sub : exprterm → exprterm → exprterm /-- Similar to `exprterm`, except that all exprs are now replaced with de Brujin indices of type `nat`. This is akin to generalizing over the terms represented by the said exprs. -/ @[derive has_reflect, derive decidable_eq, derive inhabited] inductive preterm : Type | cst : nat → preterm | var : nat → nat → preterm | add : preterm → preterm → preterm | sub : preterm → preterm → preterm localized "notation `&` k := omega.nat.preterm.cst k" in omega.nat localized "infix ` ** ` : 300 := omega.nat.preterm.var" in omega.nat localized "notation t ` +* ` s := omega.nat.preterm.add t s" in omega.nat localized "notation t ` -* ` s := omega.nat.preterm.sub t s" in omega.nat namespace preterm /-- Helper tactic for proof by induction over preterms -/ meta def induce (tac : tactic unit := tactic.skip) : tactic unit := `[ intro t, induction t with m m n t s iht ihs t s iht ihs; tac] /-- Preterm evaluation -/ def val (v : nat → nat) : preterm → nat | (& i) := i | (i ** n) := if i = 1 then v n else (v n) * i | (t1 +* t2) := t1.val + t2.val | (t1 -* t2) := t1.val - t2.val @[simp] lemma val_const {v : nat → nat} {m : nat} : (& m).val v = m := rfl @[simp] lemma val_var {v : nat → nat} {m n : nat} : (m ** n).val v = m * (v n) := begin simp only [val], by_cases h1 : m = 1, rw [if_pos h1, h1, one_mul], rw [if_neg h1, mul_comm], end @[simp] lemma val_add {v : nat → nat} {t s : preterm} : (t +* s).val v = t.val v + s.val v := rfl @[simp] lemma val_sub {v : nat → nat} {t s : preterm} : (t -* s).val v = t.val v - s.val v := rfl /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index | (t1 -* t2) := max t1.fresh_index t2.fresh_index /-- If variable assignments `v` and `w` agree on all variables that occur in term `t`, the value of `t` under `v` and `w` are identical. -/ lemma val_constant (v w : nat → nat) : ∀ t : preterm, (∀ x < t.fresh_index, v x = w x) → t.val v = t.val w | (& n) h1 := rfl | (m ** n) h1 := begin simp only [val_var], apply congr_arg (λ y, m * y), apply h1 _ (lt_add_one _) end | (t +* s) h1 := begin simp only [val_add], have ht := val_constant t (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_left _ _))), have hs := val_constant s (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_right _ _))), rw [ht, hs] end | (t -* s) h1 := begin simp only [val_sub], have ht := val_constant t (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_left _ _))), have hs := val_constant s (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_right _ _))), rw [ht, hs] end def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" | (t1 -* t2) := "(" ++ t1.repr ++ " - " ++ t2.repr ++ ")" @[simp] def add_one (t : preterm) : preterm := t +* (&1) /-- Preterm is free of subtractions -/ def sub_free : preterm → Prop | (& m) := true | (m ** n) := true | (t +* s) := t.sub_free ∧ s.sub_free | (_ -* _) := false end preterm open_locale list.func -- get notation for list.func.set /-- Return a term (which is in canonical form by definition) that is equivalent to the input preterm -/ @[simp] def canonize : preterm → term | (& m) := ⟨↑m, []⟩ | (m ** n) := ⟨0, [] {n ↦ ↑m}⟩ | (t +* s) := term.add (canonize t) (canonize s) | (_ -* _) := ⟨0, []⟩ @[simp] lemma val_canonize {v : nat → nat} : ∀ {t : preterm}, t.sub_free → (canonize t).val (λ x, ↑(v x)) = t.val v | (& i) h1 := by simp only [canonize, preterm.val_const, term.val, coeffs.val_nil, add_zero] | (i ** n) h1 := by simp only [preterm.val_var, coeffs.val_set, term.val, zero_add, int.coe_nat_mul, canonize] | (t +* s) h1 := by simp only [val_canonize h1.left, val_canonize h1.right, int.coe_nat_add, canonize, term.val_add, preterm.val_add] end nat end omega
1027150d650cdd9f65b4aa426b5e8b78f4ee73f1
e1440579fb0723caf9edf1ed07aee74bbf4f5ce7
/lean-experiments/stumps-learnable/src/lib/util.lean
6df103ed2d4b3259a844a892588cff707734775b
[ "Apache-2.0" ]
permissive
palmskog/coq-proba
1ecc5b7f399894ea14d6094a31a063280a122099
f73e2780871e2a3dd83b7ce9d3aed19f499f07e5
refs/heads/master
1,599,620,504,720
1,572,960,008,000
1,572,960,008,000
221,326,479
0
0
Apache-2.0
1,573,598,769,000
1,573,598,768,000
null
UTF-8
Lean
false
false
10,007
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import data.set import analysis.complex.exponential import .attributed.dvector import lib.basic import topology.constructions local attribute [instance] classical.prop_decidable open nnreal real ennreal set lattice open topological_space open measure_theory lemma lc_nnreal: ∀ a: nnreal, ∀ b: nnreal, a + b = 1 → a = (1:nnreal) - b := assume a b h, h ▸ (nnreal.add_sub_cancel).symm lemma super_dumb: ∀ δ: nnreal, δ > (0:nnreal) → (1:nnreal) - δ ≤ (1: nnreal) := assume h, by simp lemma coe_pmeas: ∀ a: ennreal, ∀ b: ennreal, a ≤ (1:ennreal) → b ≤ (1: ennreal) → a ≤ b → ennreal.to_nnreal a ≤ ennreal.to_nnreal b := begin intros a b h₁ h₂ h₃, rw [← coe_le_coe, coe_to_nnreal,coe_to_nnreal], assumption, rw ←ennreal.lt_top_iff_ne_top, exact lt_of_le_of_lt h₂ (ennreal.lt_top_iff_ne_top.2 one_ne_top), rw ←ennreal.lt_top_iff_ne_top, exact lt_of_le_of_lt h₁ (ennreal.lt_top_iff_ne_top.2 one_ne_top), end lemma pow_preserves_order: ∀ n: ℕ, ∀ a: nnreal, ∀ b: nnreal, a ≤ b → a^n ≤ b^n := begin intros n a b h, induction n with k ih, {by simp}, {simp [pow_succ], exact mul_le_mul h ih (zero_le _) (zero_le _)}, end lemma not_eq_prop: ∀ A: Prop, ∀ B: Prop, (¬ (A ↔ B)) ↔ ((¬ (A → B)) ∨ (¬ (B → A))) := begin intros, split; intros, finish, finish, end lemma nnreal_sub_trans: ∀ a: nnreal, ∀ b: nnreal, a ≥ b → 1 - a ≤ 1 - b := begin intros, rw nnreal.sub_le_iff_le_add, simp, by_cases (b ≤ 1), { have h: 1 + (a - b) = a + (1 - b), { calc 1 + (a - b) = 1 + a - b : by rw [←nnreal.eq_iff,nnreal.coe_add, (nnreal.coe_sub _ _ a_1), ←add_sub_assoc, nnreal.coe_sub _, nnreal.coe_add]; exact le_add_of_le_of_nonneg h (zero_le _) ... = a + 1 - b : by rw add_comm ... = a + (1 - b) : by rw [←nnreal.eq_iff,nnreal.coe_add, (nnreal.coe_sub _ _ h), ←add_sub_assoc,nnreal.coe_sub _, nnreal.coe_add];exact le_add_of_le_of_nonneg a_1 (zero_le _), }, rw h.symm, cases b, cases a, dsimp at *, simp at *, }, { simp at h, rw nnreal.sub_eq_zero, swap, exact le_of_lt h, simp, transitivity b, exact le_of_lt h, assumption, } end lemma prod_rw {α: Type} {β: Type}: ∀ P₁: α → Prop, ∀ P₂: β → Prop, { v : α × β | P₁ v.fst ∧ P₂ v.snd} = set.prod {x: α | P₁ x} {x: β | P₂ x} := begin intros, unfold set.prod, rw ext_iff, intro, repeat {rw mem_set_of_eq}, end lemma dfin_1_projn {α: Type}: ∀ P: α → Prop, ∀ x: vec α 0, (∀ (i: dfin 1), P (kth_projn x i)) ↔ P x := begin intros, split; intros, { simp at *, apply a, exact dfin.fz, }, { simp at *, assumption, }, end lemma dfin_1_projn' {α: Type}: ∀ P: α → Prop, { x: vec α 0 | ∀ (i: dfin 1), P (kth_projn x i)} = {x: α | P x} := begin intros, rw ext_iff, intro, repeat {rw mem_set_of_eq}, rw dfin_1_projn, trivial, end lemma is_measurable_simple_vec {α: Type} [measurable_space α]: ∀ P: α → Prop, is_measurable {x: α | P x} → ∀ n, is_measurable {v: vec α n | ∀ (i: dfin (nat.succ n)), P(kth_projn v i)} := begin intros, induction n; intros, { rw dfin_1_projn', assumption, }, { dunfold vec, conv { congr, congr, funext, rw dfin_succ_prop_iff_fst_and_rst, skip, }, have PROD := prod_rw (λ x, P x) (λ x, ∀ (i: dfin (nat.succ n_n)), P(kth_projn x i)), simp at PROD, rw PROD, clear PROD, apply is_measurable_set_prod; try {assumption}, }, end /- Move these results back to where vec was defined (../to_mathlib.lean)-/ noncomputable instance vec_topo: ∀ n: ℕ, topological_space (vec nnreal n) := begin intro, induction n, { dunfold vec, apply_instance, }, { unfold vec, have PROD := @prod.topological_space nnreal (vec nnreal n_n) _ n_ih, assumption, }, end instance vec_second_countable : ∀ n:ℕ, second_countable_topology (vec nnreal n) := begin intros n, induction n with k ih, dsimp [vec], apply_instance, dsimp [vec], haveI := second_countable_topology nnreal, apply_instance, end lemma vec.measurable_space_eq_borel (n : ℕ) : vec.measurable_space n = measure_theory.borel (vec nnreal n) := begin induction n with k ih, refl, dsimp [vec], rw ←measure_theory.borel_prod, rw prod.measurable_space, rw ←ih, refl, end lemma test''' : ∀ n: ℕ, ∀ f: nnreal × vec nnreal n → nnreal, ∀ g: nnreal × vec nnreal n → nnreal, continuous f → continuous g → is_measurable {p: nnreal × (vec nnreal n) | f p < g p} := begin intros n f g hf hg, convert measure_theory.is_measurable_of_is_open _, haveI := vec_second_countable n, swap, change topological_space (vec nnreal (nat.succ n)), apply_instance, swap, exact is_open_lt hf hg, rw prod.measurable_space, rw ←measure_theory.borel_prod, rw vec.measurable_space_eq_borel n, refl, end lemma to_nnreal_sub {r₁ r₂ : ennreal} (h₁ : r₁ < ⊤) (h₂ : r₂ < ⊤) : (r₁ - r₂).to_nnreal = r₁.to_nnreal - r₂.to_nnreal := by rw [← ennreal.coe_eq_coe, ennreal.coe_sub, ennreal.coe_to_nnreal (ne_top_of_lt h₂), ennreal.coe_to_nnreal (ne_top_of_lt h₁), ennreal.coe_to_nnreal ((lt_top_iff_ne_top.1 (lt_of_le_of_lt (sub_le_self _ _) h₁)))] section to_borel_space /- Move these back to borel_space.lean -/ variables {α : Type*} [linear_order α] [topological_space α] [ordered_topology α] {a b c : α} lemma is_measurable_Ioc : is_measurable (Ioc a b) := (is_measurable_of_is_open (is_open_lt continuous_const continuous_id)).inter (is_measurable_of_is_closed (is_closed_le continuous_id continuous_const)) lemma is_measurable_Icc : is_measurable (Icc a b) := is_measurable_of_is_closed $ is_closed_Icc lemma is_measurable_Ioi : is_measurable (Ioi a) := is_measurable_of_is_open $ is_open_lt continuous_const continuous_id end to_borel_space lemma Ioi_complement: ∀ x: nnreal, Ioi x = - (Iio x ∪ {x}) := begin intros, rw ext_iff, intro, unfold Ioi, unfold Iio, simp, repeat {rw mem_set_of_eq}, split; intro, { push_neg, split, { by_contradiction, simp at *, rw a_1 at a, have FOO: ¬ (x < x), simp, contradiction, }, { exact le_of_lt a, }, }, { push_neg at a, cases a, by_contradiction, have FOO: ¬ (x ≤ x_1), { simp, simp at a, exact lt_of_le_of_ne a a_left, }, contradiction, }, end lemma Icc_diff_Ioc: ∀ a: nnreal, ∀ b: nnreal, ∀ c: nnreal, a ≤ b → b ≤ c → (Icc a c \ Icc a b) = Ioc b c := begin unfold Icc, unfold Ioc, introv H1 H2, rw ext_iff, intro, rw mem_diff, repeat {rw mem_set_of_eq at *,}, split; intros, { cases a_1, cases a_1_left, finish, }, { cases a_1, split, { split, { transitivity b, assumption, exact le_of_lt a_1_left, }, { assumption, }, }, { simp, intro, assumption, }, }, end lemma mono_simple {μ: probability_measure nnreal}: ∀ a: nnreal, ∀ b: nnreal, a ≤ b → μ (Icc 0 a) ≤ μ (Icc 0 b) := begin intros, apply probability_measure.prob_mono, unfold Icc, rw subset_def, intros, rw mem_set_of_eq at *, cases a_2, split, assumption, transitivity a; assumption, end lemma log_le_log_nnreal: ∀ x: nnreal, ∀ y: nnreal, x > 0 → y > 0 → (x ≤ y ↔ log x ≤ log y) := begin intros, rw log_le_log, refl, assumption, assumption, end lemma log_pow_nnreal: ∀ x: nnreal, x > 0 → ∀ n: ℕ, log(x^n) = n * log(x) := begin intros, apply exp_injective, rw exp_nat_mul, rw exp_log, rw exp_log, assumption, exact pow_pos a n, end lemma pow_coe: ∀ a: nnreal, ∀ n: ℕ, a.val ^ n = (a ^ n).val := begin intros, induction n, simp, refl, have pow_nnreal: ∀ a: nnreal, ∀ n: ℕ, a ^ (nat.succ n) = a * a ^ n, intros, exact rfl, rw pow_nnreal, have mul_coe: ∀ a: nnreal, ∀ b: nnreal, (a * b).val = a.val * b.val, intros, refl, rw mul_coe, rw ← n_ih, refl, end lemma sub_nnreal: ∀ a: nnreal, ∀ b: nnreal, a ≥ b → (a - b).val = a.val - b.val := begin intros a b h, change (↑(a-b) = ↑a - ↑b), rw nnreal.coe_sub _ _ h, end lemma ite_equals_union_interval: ∀ θ > 0, ∀ y: nnreal, {x: nnreal | ite (to_bool(x ≤ y)) x 0 < θ} = Ico 0 θ ∪ Ioi y := begin intros, unfold Ico, unfold Ioi, rw ext_iff, intro, rw mem_union, repeat {rw mem_set_of_eq}, split; intro, { split_ifs at a, { left, split, tidy, }, { right, tidy, }, }, { cases a, { cases a, split_ifs; assumption, }, { split_ifs, { by_contradiction, have GEQ: ¬ (y < x), { simp, simp at h, assumption, }, contradiction, }, { assumption, }, }, }, end
ef28a022ca6dd306fbd45fa881627e4e2529dc3b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/content.lean
b7c6e0d7cff915a2aeb36e7afc334b0c9647d5a3
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
19,372
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.measure.measure_space import measure_theory.measure.regular import topology.sets.compacts /-! # Contents > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we work with *contents*. A content `λ` is a function from a certain class of subsets (such as the compact subsets) to `ℝ≥0` that is * additive: If `K₁` and `K₂` are disjoint sets in the domain of `λ`, then `λ(K₁ ∪ K₂) = λ(K₁) + λ(K₂)`; * subadditive: If `K₁` and `K₂` are in the domain of `λ`, then `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)`; * monotone: If `K₁ ⊆ K₂` are in the domain of `λ`, then `λ(K₁) ≤ λ(K₂)`. We show that: * Given a content `λ` on compact sets, let us define a function `λ*` on open sets, by letting `λ* U` be the supremum of `λ K` for `K` included in `U`. This is a countably subadditive map that vanishes at `∅`. In Halmos (1950) this is called the *inner content* `λ*` of `λ`, and formalized as `inner_content`. * Given an inner content, we define an outer measure `μ*`, by letting `μ* E` be the infimum of `λ* U` over the open sets `U` containing `E`. This is indeed an outer measure. It is formalized as `outer_measure`. * Restricting this outer measure to Borel sets gives a regular measure `μ`. We define bundled contents as `content`. In this file we only work on contents on compact sets, and inner contents on open sets, and both contents and inner contents map into the extended nonnegative reals. However, in other applications other choices can be made, and it is not a priori clear what the best interface should be. ## Main definitions For `μ : content G`, we define * `μ.inner_content` : the inner content associated to `μ`. * `μ.outer_measure` : the outer measure associated to `μ`. * `μ.measure` : the Borel measure associated to `μ`. We prove that, on a locally compact space, the measure `μ.measure` is regular. ## References * Paul Halmos (1950), Measure Theory, §53 * <https://en.wikipedia.org/wiki/Content_(measure_theory)> -/ universes u v w noncomputable theory open set topological_space open_locale nnreal ennreal measure_theory namespace measure_theory variables {G : Type w} [topological_space G] /-- A content is an additive function on compact sets taking values in `ℝ≥0`. It is a device from which one can define a measure. -/ structure content (G : Type w) [topological_space G] := (to_fun : compacts G → ℝ≥0) (mono' : ∀ (K₁ K₂ : compacts G), (K₁ : set G) ⊆ K₂ → to_fun K₁ ≤ to_fun K₂) (sup_disjoint' : ∀ (K₁ K₂ : compacts G), disjoint (K₁ : set G) K₂ → to_fun (K₁ ⊔ K₂) = to_fun K₁ + to_fun K₂) (sup_le' : ∀ (K₁ K₂ : compacts G), to_fun (K₁ ⊔ K₂) ≤ to_fun K₁ + to_fun K₂) instance : inhabited (content G) := ⟨{ to_fun := λ K, 0, mono' := by simp, sup_disjoint' := by simp, sup_le' := by simp }⟩ /-- Although the `to_fun` field of a content takes values in `ℝ≥0`, we register a coercion to functions taking values in `ℝ≥0∞` as most constructions below rely on taking suprs and infs, which is more convenient in a complete lattice, and aim at constructing a measure. -/ instance : has_coe_to_fun (content G) (λ _, compacts G → ℝ≥0∞) := ⟨λ μ s, μ.to_fun s⟩ namespace content variable (μ : content G) lemma apply_eq_coe_to_fun (K : compacts G) : μ K = μ.to_fun K := rfl lemma mono (K₁ K₂ : compacts G) (h : (K₁ : set G) ⊆ K₂) : μ K₁ ≤ μ K₂ := by simp [apply_eq_coe_to_fun, μ.mono' _ _ h] lemma sup_disjoint (K₁ K₂ : compacts G) (h : disjoint (K₁ : set G) K₂) : μ (K₁ ⊔ K₂) = μ K₁ + μ K₂ := by simp [apply_eq_coe_to_fun, μ.sup_disjoint' _ _ h] lemma sup_le (K₁ K₂ : compacts G) : μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂ := by { simp only [apply_eq_coe_to_fun], norm_cast, exact μ.sup_le' _ _ } lemma lt_top (K : compacts G) : μ K < ∞ := ennreal.coe_lt_top lemma empty : μ ⊥ = 0 := begin have := μ.sup_disjoint' ⊥ ⊥, simpa [apply_eq_coe_to_fun] using this, end /-- Constructing the inner content of a content. From a content defined on the compact sets, we obtain a function defined on all open sets, by taking the supremum of the content of all compact subsets. -/ def inner_content (U : opens G) : ℝ≥0∞ := ⨆ (K : compacts G) (h : (K : set G) ⊆ U), μ K lemma le_inner_content (K : compacts G) (U : opens G) (h2 : (K : set G) ⊆ U) : μ K ≤ μ.inner_content U := le_supr_of_le K $ le_supr _ h2 lemma inner_content_le (U : opens G) (K : compacts G) (h2 : (U : set G) ⊆ K) : μ.inner_content U ≤ μ K := supr₂_le $ λ K' hK', μ.mono _ _ (subset.trans hK' h2) lemma inner_content_of_is_compact {K : set G} (h1K : is_compact K) (h2K : is_open K) : μ.inner_content ⟨K, h2K⟩ = μ ⟨K, h1K⟩ := le_antisymm (supr₂_le $ λ K' hK', μ.mono _ ⟨K, h1K⟩ hK') (μ.le_inner_content _ _ subset.rfl) lemma inner_content_bot : μ.inner_content ⊥ = 0 := begin refine le_antisymm _ (zero_le _), rw ←μ.empty, refine supr₂_le (λ K hK, _), have : K = ⊥, { ext1, rw [subset_empty_iff.mp hK, compacts.coe_bot] }, rw this, refl' end /-- This is "unbundled", because that it required for the API of `induced_outer_measure`. -/ lemma inner_content_mono ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) : μ.inner_content ⟨U, hU⟩ ≤ μ.inner_content ⟨V, hV⟩ := bsupr_mono $ λ K hK, hK.trans h2 lemma inner_content_exists_compact {U : opens G} (hU : μ.inner_content U ≠ ∞) {ε : ℝ≥0} (hε : ε ≠ 0) : ∃ K : compacts G, (K : set G) ⊆ U ∧ μ.inner_content U ≤ μ K + ε := begin have h'ε := ennreal.coe_ne_zero.2 hε, cases le_or_lt (μ.inner_content U) ε, { exact ⟨⊥, empty_subset _, le_add_left h⟩ }, have := ennreal.sub_lt_self hU h.ne_bot h'ε, conv at this {to_rhs, rw inner_content }, simp only [lt_supr_iff] at this, rcases this with ⟨U, h1U, h2U⟩, refine ⟨U, h1U, _⟩, rw [← tsub_le_iff_right], exact le_of_lt h2U end /-- The inner content of a supremum of opens is at most the sum of the individual inner contents. -/ lemma inner_content_Sup_nat [t2_space G] (U : ℕ → opens G) : μ.inner_content (⨆ (i : ℕ), U i) ≤ ∑' (i : ℕ), μ.inner_content (U i) := begin have h3 : ∀ (t : finset ℕ) (K : ℕ → compacts G), μ (t.sup K) ≤ t.sum (λ i, μ (K i)), { intros t K, refine finset.induction_on t _ _, { simp only [μ.empty, nonpos_iff_eq_zero, finset.sum_empty, finset.sup_empty], }, { intros n s hn ih, rw [finset.sup_insert, finset.sum_insert hn], exact le_trans (μ.sup_le _ _) (add_le_add_left ih _) }}, refine supr₂_le (λ K hK, _), obtain ⟨t, ht⟩ := K.is_compact.elim_finite_subcover _ (λ i, (U i).is_open) _, swap, { rwa [← opens.coe_supr] }, rcases K.is_compact.finite_compact_cover t (coe ∘ U) (λ i _, (U _).is_open) (by simp only [ht]) with ⟨K', h1K', h2K', h3K'⟩, let L : ℕ → compacts G := λ n, ⟨K' n, h1K' n⟩, convert le_trans (h3 t L) _, { ext1, rw [compacts.coe_finset_sup, finset.sup_eq_supr], exact h3K' }, refine le_trans (finset.sum_le_sum _) (ennreal.sum_le_tsum t), intros i hi, refine le_trans _ (le_supr _ (L i)), refine le_trans _ (le_supr _ (h2K' i)), refl' end /-- The inner content of a union of sets is at most the sum of the individual inner contents. This is the "unbundled" version of `inner_content_Sup_nat`. It required for the API of `induced_outer_measure`. -/ lemma inner_content_Union_nat [t2_space G] ⦃U : ℕ → set G⦄ (hU : ∀ (i : ℕ), is_open (U i)) : μ.inner_content ⟨⋃ (i : ℕ), U i, is_open_Union hU⟩ ≤ ∑' (i : ℕ), μ.inner_content ⟨U i, hU i⟩ := by { have := μ.inner_content_Sup_nat (λ i, ⟨U i, hU i⟩), rwa [opens.supr_def] at this } lemma inner_content_comap (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (U : opens G) : μ.inner_content (opens.comap f.to_continuous_map U) = μ.inner_content U := begin refine (compacts.equiv f).surjective.supr_congr _ (λ K, supr_congr_Prop image_subset_iff _), intro hK, simp only [equiv.coe_fn_mk, subtype.mk_eq_mk, ennreal.coe_eq_coe, compacts.equiv], apply h, end @[to_additive] lemma is_mul_left_invariant_inner_content [group G] [topological_group G] (h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G) (U : opens G) : μ.inner_content (opens.comap (homeomorph.mul_left g).to_continuous_map U) = μ.inner_content U := by convert μ.inner_content_comap (homeomorph.mul_left g) (λ K, h g) U @[to_additive] lemma inner_content_pos_of_is_mul_left_invariant [t2_space G] [group G] [topological_group G] (h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (K : compacts G) (hK : μ K ≠ 0) (U : opens G) (hU : (U : set G).nonempty) : 0 < μ.inner_content U := begin have : (interior (U : set G)).nonempty, rwa [U.is_open.interior_eq], rcases compact_covered_by_mul_left_translates K.2 this with ⟨s, hs⟩, suffices : μ K ≤ s.card * μ.inner_content U, { exact (ennreal.mul_pos_iff.mp $ hK.bot_lt.trans_le this).2 }, have : (K : set G) ⊆ ↑⨆ (g ∈ s), opens.comap (homeomorph.mul_left g).to_continuous_map U, { simpa only [opens.supr_def, opens.coe_comap, subtype.coe_mk] }, refine (μ.le_inner_content _ _ this).trans _, refine (rel_supr_sum (μ.inner_content) (μ.inner_content_bot) (≤) (μ.inner_content_Sup_nat) _ _).trans _, simp only [μ.is_mul_left_invariant_inner_content h3, finset.sum_const, nsmul_eq_mul, le_refl] end lemma inner_content_mono' ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) : μ.inner_content ⟨U, hU⟩ ≤ μ.inner_content ⟨V, hV⟩ := bsupr_mono $ λ K hK, hK.trans h2 section outer_measure /-- Extending a content on compact sets to an outer measure on all sets. -/ protected def outer_measure : outer_measure G := induced_outer_measure (λ U hU, μ.inner_content ⟨U, hU⟩) is_open_empty μ.inner_content_bot variables [t2_space G] lemma outer_measure_opens (U : opens G) : μ.outer_measure U = μ.inner_content U := induced_outer_measure_eq' (λ _, is_open_Union) μ.inner_content_Union_nat μ.inner_content_mono U.2 lemma outer_measure_of_is_open (U : set G) (hU : is_open U) : μ.outer_measure U = μ.inner_content ⟨U, hU⟩ := μ.outer_measure_opens ⟨U, hU⟩ lemma outer_measure_le (U : opens G) (K : compacts G) (hUK : (U : set G) ⊆ K) : μ.outer_measure U ≤ μ K := (μ.outer_measure_opens U).le.trans $ μ.inner_content_le U K hUK lemma le_outer_measure_compacts (K : compacts G) : μ K ≤ μ.outer_measure K := begin rw [content.outer_measure, induced_outer_measure_eq_infi], { exact le_infi (λ U, le_infi $ λ hU, le_infi $ μ.le_inner_content K ⟨U, hU⟩) }, { exact μ.inner_content_Union_nat }, { exact μ.inner_content_mono } end lemma outer_measure_eq_infi (A : set G) : μ.outer_measure A = ⨅ (U : set G) (hU : is_open U) (h : A ⊆ U), μ.inner_content ⟨U, hU⟩ := induced_outer_measure_eq_infi _ μ.inner_content_Union_nat μ.inner_content_mono A lemma outer_measure_interior_compacts (K : compacts G) : μ.outer_measure (interior K) ≤ μ K := (μ.outer_measure_opens $ opens.interior K).le.trans $ μ.inner_content_le _ _ interior_subset lemma outer_measure_exists_compact {U : opens G} (hU : μ.outer_measure U ≠ ∞) {ε : ℝ≥0} (hε : ε ≠ 0) : ∃ K : compacts G, (K : set G) ⊆ U ∧ μ.outer_measure U ≤ μ.outer_measure K + ε := begin rw [μ.outer_measure_opens] at hU ⊢, rcases μ.inner_content_exists_compact hU hε with ⟨K, h1K, h2K⟩, exact ⟨K, h1K, le_trans h2K $ add_le_add_right (μ.le_outer_measure_compacts K) _⟩, end lemma outer_measure_exists_open {A : set G} (hA : μ.outer_measure A ≠ ∞) {ε : ℝ≥0} (hε : ε ≠ 0) : ∃ U : opens G, A ⊆ U ∧ μ.outer_measure U ≤ μ.outer_measure A + ε := begin rcases induced_outer_measure_exists_set _ _ μ.inner_content_mono hA (ennreal.coe_ne_zero.2 hε) with ⟨U, hU, h2U, h3U⟩, exact ⟨⟨U, hU⟩, h2U, h3U⟩, swap, exact μ.inner_content_Union_nat end lemma outer_measure_preimage (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (A : set G) : μ.outer_measure (f ⁻¹' A) = μ.outer_measure A := begin refine induced_outer_measure_preimage _ μ.inner_content_Union_nat μ.inner_content_mono _ (λ s, f.is_open_preimage) _, intros s hs, convert μ.inner_content_comap f h ⟨s, hs⟩ end lemma outer_measure_lt_top_of_is_compact [locally_compact_space G] {K : set G} (hK : is_compact K) : μ.outer_measure K < ∞ := begin rcases exists_compact_superset hK with ⟨F, h1F, h2F⟩, calc μ.outer_measure K ≤ μ.outer_measure (interior F) : outer_measure.mono' _ h2F ... ≤ μ ⟨F, h1F⟩ : by apply μ.outer_measure_le ⟨interior F, is_open_interior⟩ ⟨F, h1F⟩ interior_subset ... < ⊤ : μ.lt_top _ end @[to_additive] lemma is_mul_left_invariant_outer_measure [group G] [topological_group G] (h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G) (A : set G) : μ.outer_measure ((λ h, g * h) ⁻¹' A) = μ.outer_measure A := by convert μ.outer_measure_preimage (homeomorph.mul_left g) (λ K, h g) A lemma outer_measure_caratheodory (A : set G) : measurable_set[μ.outer_measure.caratheodory] A ↔ ∀ (U : opens G), μ.outer_measure (U ∩ A) + μ.outer_measure (U \ A) ≤ μ.outer_measure U := begin rw [opens.forall], apply induced_outer_measure_caratheodory, apply inner_content_Union_nat, apply inner_content_mono' end @[to_additive] lemma outer_measure_pos_of_is_mul_left_invariant [group G] [topological_group G] (h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (K : compacts G) (hK : μ K ≠ 0) {U : set G} (h1U : is_open U) (h2U : U.nonempty) : 0 < μ.outer_measure U := by { convert μ.inner_content_pos_of_is_mul_left_invariant h3 K hK ⟨U, h1U⟩ h2U, exact μ.outer_measure_opens ⟨U, h1U⟩ } variables [S : measurable_space G] [borel_space G] include S /-- For the outer measure coming from a content, all Borel sets are measurable. -/ lemma borel_le_caratheodory : S ≤ μ.outer_measure.caratheodory := begin rw [@borel_space.measurable_eq G _ _], refine measurable_space.generate_from_le _, intros U hU, rw μ.outer_measure_caratheodory, intro U', rw μ.outer_measure_of_is_open ((U' : set G) ∩ U) (U'.is_open.inter hU), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {L : compacts G // (L : set G) ⊆ U' ∩ U} := ⟨⟨⊥, empty_subset _⟩⟩, rw [ennreal.supr_add], refine supr_le _, rintro ⟨L, hL⟩, simp only [subset_inter_iff] at hL, have : ↑U' \ U ⊆ U' \ L := diff_subset_diff_right hL.2, refine le_trans (add_le_add_left (μ.outer_measure.mono' this) _) _, rw μ.outer_measure_of_is_open (↑U' \ L) (is_open.sdiff U'.2 L.2.is_closed), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {M : compacts G // (M : set G) ⊆ ↑U' \ L} := ⟨⟨⊥, empty_subset _⟩⟩, rw [ennreal.add_supr], refine supr_le _, rintro ⟨M, hM⟩, simp only [subset_diff] at hM, have : (↑(L ⊔ M) : set G) ⊆ U', { simp only [union_subset_iff, compacts.coe_sup, hM, hL, and_self] }, rw μ.outer_measure_of_is_open ↑U' U'.2, refine le_trans (ge_of_eq _) (μ.le_inner_content _ _ this), exact μ.sup_disjoint _ _ hM.2.symm, end /-- The measure induced by the outer measure coming from a content, on the Borel sigma-algebra. -/ protected def measure : measure G := μ.outer_measure.to_measure μ.borel_le_caratheodory lemma measure_apply {s : set G} (hs : measurable_set s) : μ.measure s = μ.outer_measure s := to_measure_apply _ _ hs /-- In a locally compact space, any measure constructed from a content is regular. -/ instance regular [locally_compact_space G] : μ.measure.regular := begin haveI : μ.measure.outer_regular, { refine ⟨λ A hA r (hr : _ < _), _⟩, rw [μ.measure_apply hA, outer_measure_eq_infi] at hr, simp only [infi_lt_iff] at hr, rcases hr with ⟨U, hUo, hAU, hr⟩, rw [← μ.outer_measure_of_is_open U hUo, ← μ.measure_apply hUo.measurable_set] at hr, exact ⟨U, hAU, hUo, hr⟩ }, haveI : is_finite_measure_on_compacts μ.measure, { refine ⟨λ K hK, _⟩, rw [measure_apply _ hK.measurable_set], exact μ.outer_measure_lt_top_of_is_compact hK }, refine ⟨λ U hU r hr, _⟩, rw [measure_apply _ hU.measurable_set, μ.outer_measure_of_is_open U hU] at hr, simp only [inner_content, lt_supr_iff] at hr, rcases hr with ⟨K, hKU, hr⟩, refine ⟨K, hKU, K.2, hr.trans_le _⟩, exact (μ.le_outer_measure_compacts K).trans (le_to_measure_apply _ _ _) end end outer_measure section regular_contents /-- A content `μ` is called regular if for every compact set `K`, `μ(K) = inf {μ(K') : K ⊂ int K' ⊂ K'`. See Paul Halmos (1950), Measure Theory, §54-/ def content_regular := ∀ ⦃K : topological_space.compacts G⦄, μ K = ⨅ (K' : topological_space.compacts G) (hK: (K : set G) ⊆ interior (K' : set G) ), μ K' lemma content_regular_exists_compact (H : content_regular μ) (K : topological_space.compacts G) {ε : nnreal} (hε : ε ≠ 0) : ∃ (K' : topological_space.compacts G), (K.carrier ⊆ interior K'.carrier) ∧ μ K' ≤ μ K + ε := begin by_contra hc, simp only [not_exists, not_and, not_le] at hc, have lower_bound_infi : μ K + ε ≤ ⨅ (K' : topological_space.compacts G) (h: (K : set G) ⊆ interior (K' : set G) ), μ K' := le_infi (λ K', le_infi ( λ K'_hyp, le_of_lt (hc K' K'_hyp))), rw ← H at lower_bound_infi, exact (lt_self_iff_false (μ K)).mp (lt_of_le_of_lt' lower_bound_infi (ennreal.lt_add_right (ne_top_of_lt (μ.lt_top K)) (ennreal.coe_ne_zero.mpr hε))), end variables [measurable_space G] [t2_space G] [borel_space G] /--If `μ` is a regular content, then the measure induced by `μ` will agree with `μ` on compact sets.-/ lemma measure_eq_content_of_regular (H : measure_theory.content.content_regular μ) (K : topological_space.compacts G) : μ.measure ↑K = μ K := begin refine le_antisymm _ _, { apply ennreal.le_of_forall_pos_le_add, intros ε εpos content_K_finite, obtain ⟨ K', K'_hyp ⟩ := content_regular_exists_compact μ H K (ne_bot_of_gt εpos), calc μ.measure ↑K ≤ μ.measure (interior ↑K') : _ ... ≤ μ K' : _ ... ≤ μ K + ε : K'_hyp.right, { rw [μ.measure_apply ((is_open_interior).measurable_set), μ.measure_apply K.is_compact.measurable_set], exact μ.outer_measure.mono K'_hyp.left }, { rw μ.measure_apply (is_open.measurable_set is_open_interior), exact μ.outer_measure_interior_compacts K' } }, { rw (μ.measure_apply (is_compact.measurable_set K.is_compact)), exact μ.le_outer_measure_compacts K }, end end regular_contents end content end measure_theory
a01cfa53f5f62bb735c2bbec8f2ea7e4c3ea44d1
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/io_bug2.lean
5c16f4223948f0e2343121ae3b8bfcf396c706f0
[ "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
136
lean
import system.io open io def main : io unit := do put_ln "t1", (x, y) ← return ((1 : nat), (2 : ℕ)), put_ln "t2" #eval main
76c9abc7f8c6f42c758157c745ee8226a1aa8af1
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/finite_dimension.lean
cfdde83cd0715c3ae150c761e7c15a7293a2024d
[ "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
45,019
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 analysis.asymptotics.asymptotic_equivalent import analysis.normed_space.affine_isometry import analysis.normed_space.operator_norm import analysis.normed_space.riesz_lemma import linear_algebra.matrix.to_lin import topology.instances.matrix /-! # Finite dimensional normed spaces over complete fields Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps are continuous. Moreover, a finite-dimensional subspace is always complete and closed. ## Main results: * `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a complete field is continuous. * `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. * `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is closed * `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or `ℂ`. * `finite_dimensional_of_is_compact_closed_ball`: Riesz' theorem: if the closed unit ball is compact, then the space is finite-dimensional. ## Implementation notes The fact that all norms are equivalent is not written explicitly, as it would mean having two norms on a single space, which is not the way type classes work. However, if one has a finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm, then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to `linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence. -/ universes u v w x noncomputable theory open set finite_dimensional topological_space filter asymptotics open_locale classical big_operators filter topological_space asymptotics nnreal namespace linear_isometry open linear_map variables {R : Type*} [semiring R] variables {F E₁ : Type*} [semi_normed_group F] [normed_group E₁] [module R E₁] variables {R₁ : Type*} [field R₁] [module R₁ E₁] [module R₁ F] [finite_dimensional R₁ E₁] [finite_dimensional R₁ F] /-- A linear isometry between finite dimensional spaces of equal dimension can be upgraded to a linear isometry equivalence. -/ def to_linear_isometry_equiv (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) : E₁ ≃ₗᵢ[R₁] F := { to_linear_equiv := li.to_linear_map.linear_equiv_of_injective li.injective h, norm_map' := li.norm_map' } @[simp] lemma coe_to_linear_isometry_equiv (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) : (li.to_linear_isometry_equiv h : E₁ → F) = li := rfl @[simp] lemma to_linear_isometry_equiv_apply (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) (x : E₁) : (li.to_linear_isometry_equiv h) x = li x := rfl end linear_isometry namespace affine_isometry open affine_map variables {𝕜 : Type*} {V₁ V₂ : Type*} {P₁ P₂ : Type*} [normed_field 𝕜] [normed_group V₁] [semi_normed_group V₂] [normed_space 𝕜 V₁] [normed_space 𝕜 V₂] [metric_space P₁] [pseudo_metric_space P₂] [normed_add_torsor V₁ P₁] [normed_add_torsor V₂ P₂] variables [finite_dimensional 𝕜 V₁] [finite_dimensional 𝕜 V₂] /-- An affine isometry between finite dimensional spaces of equal dimension can be upgraded to an affine isometry equivalence. -/ def to_affine_isometry_equiv [inhabited P₁] (li : P₁ →ᵃⁱ[𝕜] P₂) (h : finrank 𝕜 V₁ = finrank 𝕜 V₂) : P₁ ≃ᵃⁱ[𝕜] P₂ := affine_isometry_equiv.mk' li (li.linear_isometry.to_linear_isometry_equiv h) (arbitrary P₁) (λ p, by simp) @[simp] lemma coe_to_affine_isometry_equiv [inhabited P₁] (li : P₁ →ᵃⁱ[𝕜] P₂) (h : finrank 𝕜 V₁ = finrank 𝕜 V₂) : (li.to_affine_isometry_equiv h : P₁ → P₂) = li := rfl @[simp] lemma to_affine_isometry_equiv_apply [inhabited P₁] (li : P₁ →ᵃⁱ[𝕜] P₂) (h : finrank 𝕜 V₁ = finrank 𝕜 V₂) (x : P₁) : (li.to_affine_isometry_equiv h) x = li x := rfl end affine_isometry /-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/ lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜] {E : Type v} [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_smul 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f := begin -- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous -- function. have : (f : (ι → 𝕜) → E) = (λx, ∑ i : ι, x i • (f (λj, if i = j then 1 else 0))), by { ext x, exact f.pi_apply_eq_sum_univ x }, rw this, refine continuous_finset_sum _ (λi hi, _), exact (continuous_apply i).smul continuous_const end /-- The space of continuous linear maps between finite-dimensional spaces is finite-dimensional. -/ instance {𝕜 E F : Type*} [field 𝕜] [topological_space 𝕜] [topological_space E] [add_comm_group E] [module 𝕜 E] [finite_dimensional 𝕜 E] [topological_space F] [add_comm_group F] [module 𝕜 F] [topological_add_group F] [has_continuous_smul 𝕜 F] [finite_dimensional 𝕜 F] : finite_dimensional 𝕜 (E →L[𝕜] F) := finite_dimensional.of_injective (continuous_linear_map.coe_lm 𝕜 : (E →L[𝕜] F) →ₗ[𝕜] (E →ₗ[𝕜] F)) continuous_linear_map.coe_injective section complete_field variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {F : Type w} [normed_group F] [normed_space 𝕜 F] {F' : Type x} [add_comm_group F'] [module 𝕜 F'] [topological_space F'] [topological_add_group F'] [has_continuous_smul 𝕜 F'] [complete_space 𝕜] /-- In finite dimension over a complete field, the canonical identification (in terms of a basis) with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that all norms are equivalent in finite dimension. This statement is superceded by the fact that every linear map on a finite-dimensional space is continuous, in `linear_map.continuous_of_finite_dimensional`. -/ lemma continuous_equiv_fun_basis {ι : Type v} [fintype ι] (ξ : basis ι 𝕜 E) : continuous ξ.equiv_fun := begin unfreezingI { induction hn : fintype.card ι with n IH generalizing ι E }, { apply ξ.equiv_fun.to_linear_map.continuous_of_bound 0 (λx, _), have : ξ.equiv_fun x = 0, by { ext i, exact (fintype.card_eq_zero_iff.1 hn).elim i }, change ∥ξ.equiv_fun x∥ ≤ 0 * ∥x∥, rw this, simp [norm_nonneg] }, { haveI : finite_dimensional 𝕜 E := of_fintype_basis ξ, -- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent -- to a standard space of dimension n, hence it is complete and therefore closed. have H₁ : ∀s : submodule 𝕜 E, finrank 𝕜 s = n → is_closed (s : set E), { assume s s_dim, let b := basis.of_vector_space 𝕜 s, have U : uniform_embedding b.equiv_fun.symm.to_equiv, { have : fintype.card (basis.of_vector_space_index 𝕜 s) = n, by { rw ← s_dim, exact (finrank_eq_card_basis b).symm }, have : continuous b.equiv_fun := IH b this, exact b.equiv_fun.symm.uniform_embedding b.equiv_fun.symm.to_linear_map.continuous_on_pi this }, have : is_complete (s : set E), from complete_space_coe_iff_is_complete.1 ((complete_space_congr U).1 (by apply_instance)), exact this.is_closed }, -- second step: any linear form is continuous, as its kernel is closed by the first step have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f, { assume f, have : finrank 𝕜 f.ker = n ∨ finrank 𝕜 f.ker = n.succ, { have Z := f.finrank_range_add_finrank_ker, rw [finrank_eq_card_basis ξ, hn] at Z, by_cases H : finrank 𝕜 f.range = 0, { right, rw H at Z, simpa using Z }, { left, have : finrank 𝕜 f.range = 1, { refine le_antisymm _ (zero_lt_iff.mpr H), simpa [finrank_self] using f.range.finrank_le }, rw [this, add_comm, nat.add_one] at Z, exact nat.succ.inj Z } }, have : is_closed (f.ker : set E), { cases this, { exact H₁ _ this }, { have : f.ker = ⊤, by { apply eq_top_of_finrank_eq, rw [finrank_eq_card_basis ξ, hn, this] }, simp [this] } }, exact linear_map.continuous_iff_is_closed_ker.2 this }, -- third step: applying the continuity to the linear form corresponding to a coefficient in the -- basis decomposition, deduce that all such coefficients are controlled in terms of the norm have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥ξ.equiv_fun x i∥ ≤ C * ∥x∥, { assume i, let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i) ∘ₗ ↑ξ.equiv_fun, let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f }, exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ }, -- fourth step: combine the bound on each coefficient to get a global bound and the continuity choose C0 hC0 using this, let C := ∑ i, C0 i, have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1), have C0_le : ∀i, C0 i ≤ C := λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _), apply ξ.equiv_fun.to_linear_map.continuous_of_bound C (λx, _), rw pi_norm_le_iff, { exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) }, { exact mul_nonneg C_nonneg (norm_nonneg _) } } end /-- Any linear map on a finite dimensional space over a complete field is continuous. -/ theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') : continuous f := begin -- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and -- argue that all linear maps there are continuous. let b := basis.of_vector_space 𝕜 E, have A : continuous b.equiv_fun := continuous_equiv_fun_basis b, have B : continuous (f.comp (b.equiv_fun.symm : (basis.of_vector_space_index 𝕜 E → 𝕜) →ₗ[𝕜] E)) := linear_map.continuous_on_pi _, have : continuous ((f.comp (b.equiv_fun.symm : (basis.of_vector_space_index 𝕜 E → 𝕜) →ₗ[𝕜] E)) ∘ b.equiv_fun) := B.comp A, convert this, ext x, dsimp, rw [basis.equiv_fun_symm_apply, basis.sum_repr] end section affine variables {PE PF : Type*} [metric_space PE] [normed_add_torsor E PE] [metric_space PF] [normed_add_torsor F PF] [finite_dimensional 𝕜 E] include E F theorem affine_map.continuous_of_finite_dimensional (f : PE →ᵃ[𝕜] PF) : continuous f := affine_map.continuous_linear_iff.1 f.linear.continuous_of_finite_dimensional theorem affine_equiv.continuous_of_finite_dimensional (f : PE ≃ᵃ[𝕜] PF) : continuous f := f.to_affine_map.continuous_of_finite_dimensional /-- Reinterpret an affine equivalence as a homeomorphism. -/ def affine_equiv.to_homeomorph_of_finite_dimensional (f : PE ≃ᵃ[𝕜] PF) : PE ≃ₜ PF := { to_equiv := f.to_equiv, continuous_to_fun := f.continuous_of_finite_dimensional, continuous_inv_fun := begin haveI : finite_dimensional 𝕜 F, from f.linear.finite_dimensional, exact f.symm.continuous_of_finite_dimensional end } @[simp] lemma affine_equiv.coe_to_homeomorph_of_finite_dimensional (f : PE ≃ᵃ[𝕜] PF) : ⇑f.to_homeomorph_of_finite_dimensional = f := rfl @[simp] lemma affine_equiv.coe_to_homeomorph_of_finite_dimensional_symm (f : PE ≃ᵃ[𝕜] PF) : ⇑f.to_homeomorph_of_finite_dimensional.symm = f.symm := rfl end affine lemma continuous_linear_map.continuous_det : continuous (λ (f : E →L[𝕜] E), f.det) := begin change continuous (λ (f : E →L[𝕜] E), (f : E →ₗ[𝕜] E).det), by_cases h : ∃ (s : finset E), nonempty (basis ↥s 𝕜 E), { rcases h with ⟨s, ⟨b⟩⟩, haveI : finite_dimensional 𝕜 E := finite_dimensional.of_finset_basis b, simp_rw linear_map.det_eq_det_to_matrix_of_finset b, refine continuous.matrix_det _, exact ((linear_map.to_matrix b b).to_linear_map.comp (continuous_linear_map.coe_lm 𝕜)).continuous_of_finite_dimensional }, { unfold linear_map.det, simpa only [h, monoid_hom.one_apply, dif_neg, not_false_iff] using continuous_const } end namespace linear_map variables [finite_dimensional 𝕜 E] /-- The continuous linear map induced by a linear map on a finite dimensional space -/ def to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F' := { to_fun := λ f, ⟨f, f.continuous_of_finite_dimensional⟩, inv_fun := coe, map_add' := λ f g, rfl, map_smul' := λ c f, rfl, left_inv := λ f, rfl, right_inv := λ f, continuous_linear_map.coe_injective rfl } @[simp] lemma coe_to_continuous_linear_map' (f : E →ₗ[𝕜] F') : ⇑f.to_continuous_linear_map = f := rfl @[simp] lemma coe_to_continuous_linear_map (f : E →ₗ[𝕜] F') : (f.to_continuous_linear_map : E →ₗ[𝕜] F') = f := rfl @[simp] lemma coe_to_continuous_linear_map_symm : ⇑(to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F').symm = coe := rfl end linear_map namespace linear_equiv variables [finite_dimensional 𝕜 E] /-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional space. -/ def to_continuous_linear_equiv (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F := { continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional, continuous_inv_fun := begin haveI : finite_dimensional 𝕜 F := e.finite_dimensional, exact e.symm.to_linear_map.continuous_of_finite_dimensional end, ..e } @[simp] lemma coe_to_continuous_linear_equiv (e : E ≃ₗ[𝕜] F) : (e.to_continuous_linear_equiv : E →ₗ[𝕜] F) = e := rfl @[simp] lemma coe_to_continuous_linear_equiv' (e : E ≃ₗ[𝕜] F) : (e.to_continuous_linear_equiv : E → F) = e := rfl @[simp] lemma coe_to_continuous_linear_equiv_symm (e : E ≃ₗ[𝕜] F) : (e.to_continuous_linear_equiv.symm : F →ₗ[𝕜] E) = e.symm := rfl @[simp] lemma coe_to_continuous_linear_equiv_symm' (e : E ≃ₗ[𝕜] F) : (e.to_continuous_linear_equiv.symm : F → E) = e.symm := rfl @[simp] lemma to_linear_equiv_to_continuous_linear_equiv (e : E ≃ₗ[𝕜] F) : e.to_continuous_linear_equiv.to_linear_equiv = e := by { ext x, refl } @[simp] lemma to_linear_equiv_to_continuous_linear_equiv_symm (e : E ≃ₗ[𝕜] F) : e.to_continuous_linear_equiv.symm.to_linear_equiv = e.symm := by { ext x, refl } end linear_equiv namespace continuous_linear_map variable [finite_dimensional 𝕜 E] /-- Builds a continuous linear equivalence from a continuous linear map on a finite-dimensional vector space whose determinant is nonzero. -/ def to_continuous_linear_equiv_of_det_ne_zero (f : E →L[𝕜] E) (hf : f.det ≠ 0) : E ≃L[𝕜] E := ((f : E →ₗ[𝕜] E).equiv_of_det_ne_zero hf).to_continuous_linear_equiv @[simp] lemma coe_to_continuous_linear_equiv_of_det_ne_zero (f : E →L[𝕜] E) (hf : f.det ≠ 0) : (f.to_continuous_linear_equiv_of_det_ne_zero hf : E →L[𝕜] E) = f := by { ext x, refl } @[simp] lemma to_continuous_linear_equiv_of_det_ne_zero_apply (f : E →L[𝕜] E) (hf : f.det ≠ 0) (x : E) : f.to_continuous_linear_equiv_of_det_ne_zero hf x = f x := rfl end continuous_linear_map /-- Any `K`-Lipschitz map from a subset `s` of a metric space `α` to a finite-dimensional real vector space `E'` can be extended to a Lipschitz map on the whole space `α`, with a slightly worse constant `C * K` where `C` only depends on `E'`. We record a working value for this constant `C` as `lipschitz_extension_constant E'`. -/ @[irreducible] def lipschitz_extension_constant (E' : Type*) [normed_group E'] [normed_space ℝ E'] [finite_dimensional ℝ E'] : ℝ≥0 := let A := (basis.of_vector_space ℝ E').equiv_fun.to_continuous_linear_equiv in max (∥A.symm.to_continuous_linear_map∥₊ * ∥A.to_continuous_linear_map∥₊) 1 lemma lipschitz_extension_constant_pos (E' : Type*) [normed_group E'] [normed_space ℝ E'] [finite_dimensional ℝ E'] : 0 < lipschitz_extension_constant E' := by { rw lipschitz_extension_constant, exact zero_lt_one.trans_le (le_max_right _ _) } /-- Any `K`-Lipschitz map from a subset `s` of a metric space `α` to a finite-dimensional real vector space `E'` can be extended to a Lipschitz map on the whole space `α`, with a slightly worse constant `lipschitz_extension_constant E' * K`. -/ theorem lipschitz_on_with.extend_finite_dimension {α : Type*} [pseudo_metric_space α] {E' : Type*} [normed_group E'] [normed_space ℝ E'] [finite_dimensional ℝ E'] {s : set α} {f : α → E'} {K : ℝ≥0} (hf : lipschitz_on_with K f s) : ∃ (g : α → E'), lipschitz_with (lipschitz_extension_constant E' * K) g ∧ eq_on f g s := begin /- This result is already known for spaces `ι → ℝ`. We use a continuous linear equiv between `E'` and such a space to transfer the result to `E'`. -/ let ι : Type* := basis.of_vector_space_index ℝ E', let A := (basis.of_vector_space ℝ E').equiv_fun.to_continuous_linear_equiv, have LA : lipschitz_with (∥A.to_continuous_linear_map∥₊) A, by apply A.lipschitz, have L : lipschitz_on_with (∥A.to_continuous_linear_map∥₊ * K) (A ∘ f) s := LA.comp_lipschitz_on_with hf, obtain ⟨g, hg, gs⟩ : ∃ g : α → (ι → ℝ), lipschitz_with (∥A.to_continuous_linear_map∥₊ * K) g ∧ eq_on (A ∘ f) g s := L.extend_pi, refine ⟨A.symm ∘ g, _, _⟩, { have LAsymm : lipschitz_with (∥A.symm.to_continuous_linear_map∥₊) A.symm, by apply A.symm.lipschitz, apply (LAsymm.comp hg).weaken, rw [lipschitz_extension_constant, ← mul_assoc], refine mul_le_mul' (le_max_left _ _) le_rfl }, { assume x hx, have : A (f x) = g x := gs hx, simp only [(∘), ← this, A.symm_apply_apply] } end lemma linear_map.exists_antilipschitz_with [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F) (hf : f.ker = ⊥) : ∃ K > 0, antilipschitz_with K f := begin cases subsingleton_or_nontrivial E; resetI, { exact ⟨1, zero_lt_one, antilipschitz_with.of_subsingleton⟩ }, { rw linear_map.ker_eq_bot at hf, let e : E ≃L[𝕜] f.range := (linear_equiv.of_injective f hf).to_continuous_linear_equiv, exact ⟨_, e.nnnorm_symm_pos, e.antilipschitz⟩ } end protected lemma linear_independent.eventually {ι} [fintype ι] {f : ι → E} (hf : linear_independent 𝕜 f) : ∀ᶠ g in 𝓝 f, linear_independent 𝕜 g := begin simp only [fintype.linear_independent_iff'] at hf ⊢, rcases linear_map.exists_antilipschitz_with _ hf with ⟨K, K0, hK⟩, have : tendsto (λ g : ι → E, ∑ i, ∥g i - f i∥) (𝓝 f) (𝓝 $ ∑ i, ∥f i - f i∥), from tendsto_finset_sum _ (λ i hi, tendsto.norm $ ((continuous_apply i).tendsto _).sub tendsto_const_nhds), simp only [sub_self, norm_zero, finset.sum_const_zero] at this, refine (this.eventually (gt_mem_nhds $ inv_pos.2 K0)).mono (λ g hg, _), replace hg : ∑ i, ∥g i - f i∥₊ < K⁻¹, by { rw ← nnreal.coe_lt_coe, push_cast, exact hg }, rw linear_map.ker_eq_bot, refine (hK.add_sub_lipschitz_with (lipschitz_with.of_dist_le_mul $ λ v u, _) hg).injective, simp only [dist_eq_norm, linear_map.lsum_apply, pi.sub_apply, linear_map.sum_apply, linear_map.comp_apply, linear_map.proj_apply, linear_map.smul_right_apply, linear_map.id_apply, ← finset.sum_sub_distrib, ← smul_sub, ← sub_smul, nnreal.coe_sum, coe_nnnorm, finset.sum_mul], refine norm_sum_le_of_le _ (λ i _, _), rw [norm_smul, mul_comm], exact mul_le_mul_of_nonneg_left (norm_le_pi_norm (v - u) i) (norm_nonneg _) end lemma is_open_set_of_linear_independent {ι : Type*} [fintype ι] : is_open {f : ι → E | linear_independent 𝕜 f} := is_open_iff_mem_nhds.2 $ λ f, linear_independent.eventually lemma is_open_set_of_nat_le_rank (n : ℕ) : is_open {f : E →L[𝕜] F | ↑n ≤ rank (f : E →ₗ[𝕜] F)} := begin simp only [le_rank_iff_exists_linear_independent_finset, set_of_exists, ← exists_prop], refine is_open_bUnion (λ t ht, _), have : continuous (λ f : E →L[𝕜] F, (λ x : (t : set E), f x)), from continuous_pi (λ x, (continuous_linear_map.apply 𝕜 F (x : E)).continuous), exact is_open_set_of_linear_independent.preimage this end /-- Two finite-dimensional normed spaces are continuously linearly equivalent if they have the same (finite) dimension. -/ theorem finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) : nonempty (E ≃L[𝕜] F) := (nonempty_linear_equiv_of_finrank_eq cond).map linear_equiv.to_continuous_linear_equiv /-- Two finite-dimensional normed spaces are continuously linearly equivalent if and only if they have the same (finite) dimension. -/ theorem finite_dimensional.nonempty_continuous_linear_equiv_iff_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] : nonempty (E ≃L[𝕜] F) ↔ finrank 𝕜 E = finrank 𝕜 F := ⟨ λ ⟨h⟩, h.to_linear_equiv.finrank_eq, λ h, finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq h ⟩ /-- A continuous linear equivalence between two finite-dimensional normed spaces of the same (finite) dimension. -/ def continuous_linear_equiv.of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) : E ≃L[𝕜] F := (linear_equiv.of_finrank_eq E F cond).to_continuous_linear_equiv variables {ι : Type*} [fintype ι] /-- Construct a continuous linear map given the value at a finite basis. -/ def basis.constrL (v : basis ι 𝕜 E) (f : ι → F) : E →L[𝕜] F := by haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v; exact (v.constr 𝕜 f).to_continuous_linear_map @[simp, norm_cast] lemma basis.coe_constrL (v : basis ι 𝕜 E) (f : ι → F) : (v.constrL f : E →ₗ[𝕜] F) = v.constr 𝕜 f := rfl /-- The continuous linear equivalence between a vector space over `𝕜` with a finite basis and functions from its basis indexing type to `𝕜`. -/ def basis.equiv_funL (v : basis ι 𝕜 E) : E ≃L[𝕜] (ι → 𝕜) := { continuous_to_fun := begin haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v, exact v.equiv_fun.to_linear_map.continuous_of_finite_dimensional, end, continuous_inv_fun := begin change continuous v.equiv_fun.symm.to_fun, exact v.equiv_fun.symm.to_linear_map.continuous_of_finite_dimensional, end, ..v.equiv_fun } @[simp] lemma basis.constrL_apply (v : basis ι 𝕜 E) (f : ι → F) (e : E) : (v.constrL f) e = ∑ i, (v.equiv_fun e i) • f i := v.constr_apply_fintype 𝕜 _ _ @[simp] lemma basis.constrL_basis (v : basis ι 𝕜 E) (f : ι → F) (i : ι) : (v.constrL f) (v i) = f i := v.constr_basis 𝕜 _ _ lemma basis.op_nnnorm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) {u : E →L[𝕜] F} (M : ℝ≥0) (hu : ∀ i, ∥u (v i)∥₊ ≤ M) : ∥u∥₊ ≤ fintype.card ι • ∥v.equiv_funL.to_continuous_linear_map∥₊ * M := u.op_nnnorm_le_bound _ $ λ e, begin set φ := v.equiv_funL.to_continuous_linear_map, calc ∥u e∥₊ = ∥u (∑ i, v.equiv_fun e i • v i)∥₊ : by rw [v.sum_equiv_fun] ... = ∥∑ i, (v.equiv_fun e i) • (u $ v i)∥₊ : by simp [u.map_sum, linear_map.map_smul] ... ≤ ∑ i, ∥(v.equiv_fun e i) • (u $ v i)∥₊ : nnnorm_sum_le _ _ ... = ∑ i, ∥v.equiv_fun e i∥₊ * ∥u (v i)∥₊ : by simp only [nnnorm_smul] ... ≤ ∑ i, ∥v.equiv_fun e i∥₊ * M : finset.sum_le_sum (λ i hi, mul_le_mul_of_nonneg_left (hu i) (zero_le _)) ... = (∑ i, ∥v.equiv_fun e i∥₊) * M : finset.sum_mul.symm ... ≤ fintype.card ι • (∥φ∥₊ * ∥e∥₊) * M : (suffices _, from mul_le_mul_of_nonneg_right this (zero_le M), calc ∑ i, ∥v.equiv_fun e i∥₊ ≤ fintype.card ι • ∥φ e∥₊ : pi.sum_nnnorm_apply_le_nnnorm _ ... ≤ fintype.card ι • (∥φ∥₊ * ∥e∥₊) : nsmul_le_nsmul_of_le_right (φ.le_op_nnnorm e) _) ... = fintype.card ι • ∥φ∥₊ * M * ∥e∥₊ : by simp only [smul_mul_assoc, mul_right_comm], end lemma basis.op_norm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) {u : E →L[𝕜] F} {M : ℝ} (hM : 0 ≤ M) (hu : ∀ i, ∥u (v i)∥ ≤ M) : ∥u∥ ≤ fintype.card ι • ∥v.equiv_funL.to_continuous_linear_map∥ * M := by simpa using nnreal.coe_le_coe.mpr (v.op_nnnorm_le ⟨M, hM⟩ hu) /-- A weaker version of `basis.op_nnnorm_le` that abstracts away the value of `C`. -/ lemma basis.exists_op_nnnorm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) : ∃ C > (0 : ℝ≥0), ∀ {u : E →L[𝕜] F} (M : ℝ≥0), (∀ i, ∥u (v i)∥₊ ≤ M) → ∥u∥₊ ≤ C*M := ⟨ max (fintype.card ι • ∥v.equiv_funL.to_continuous_linear_map∥₊) 1, zero_lt_one.trans_le (le_max_right _ _), λ u M hu, (v.op_nnnorm_le M hu).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (zero_le M)⟩ /-- A weaker version of `basis.op_norm_le` that abstracts away the value of `C`. -/ lemma basis.exists_op_norm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) : ∃ C > (0 : ℝ), ∀ {u : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥u (v i)∥ ≤ M) → ∥u∥ ≤ C*M := let ⟨C, hC, h⟩ := v.exists_op_nnnorm_le in ⟨C, hC, λ u, subtype.forall'.mpr h⟩ instance [finite_dimensional 𝕜 E] [second_countable_topology F] : second_countable_topology (E →L[𝕜] F) := begin set d := finite_dimensional.finrank 𝕜 E, suffices : ∀ ε > (0 : ℝ), ∃ n : (E →L[𝕜] F) → fin d → ℕ, ∀ (f g : E →L[𝕜] F), n f = n g → dist f g ≤ ε, from metric.second_countable_of_countable_discretization (λ ε ε_pos, ⟨fin d → ℕ, by apply_instance, this ε ε_pos⟩), intros ε ε_pos, obtain ⟨u : ℕ → F, hu : dense_range u⟩ := exists_dense_seq F, let v := finite_dimensional.fin_basis 𝕜 E, obtain ⟨C : ℝ, C_pos : 0 < C, hC : ∀ {φ : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥φ (v i)∥ ≤ M) → ∥φ∥ ≤ C * M⟩ := v.exists_op_norm_le, have h_2C : 0 < 2*C := mul_pos zero_lt_two C_pos, have hε2C : 0 < ε/(2*C) := div_pos ε_pos h_2C, have : ∀ φ : E →L[𝕜] F, ∃ n : fin d → ℕ, ∥φ - (v.constrL $ u ∘ n)∥ ≤ ε/2, { intros φ, have : ∀ i, ∃ n, ∥φ (v i) - u n∥ ≤ ε/(2*C), { simp only [norm_sub_rev], intro i, have : φ (v i) ∈ closure (range u) := hu _, obtain ⟨n, hn⟩ : ∃ n, ∥u n - φ (v i)∥ < ε / (2 * C), { rw mem_closure_iff_nhds_basis metric.nhds_basis_ball at this, specialize this (ε/(2*C)) hε2C, simpa [dist_eq_norm] }, exact ⟨n, le_of_lt hn⟩ }, choose n hn using this, use n, replace hn : ∀ i : fin d, ∥(φ - (v.constrL $ u ∘ n)) (v i)∥ ≤ ε / (2 * C), by simp [hn], have : C * (ε / (2 * C)) = ε/2, { rw [eq_div_iff (two_ne_zero : (2 : ℝ) ≠ 0), mul_comm, ← mul_assoc, mul_div_cancel' _ (ne_of_gt h_2C)] }, specialize hC (le_of_lt hε2C) hn, rwa this at hC }, choose n hn using this, set Φ := λ φ : E →L[𝕜] F, (v.constrL $ u ∘ (n φ)), change ∀ z, dist z (Φ z) ≤ ε/2 at hn, use n, intros x y hxy, calc dist x y ≤ dist x (Φ x) + dist (Φ x) y : dist_triangle _ _ _ ... = dist x (Φ x) + dist y (Φ y) : by simp [Φ, hxy, dist_comm] ... ≤ ε : by linarith [hn x, hn y] end /-- Any finite-dimensional vector space over a complete field is complete. We do not register this as an instance to avoid an instance loop when trying to prove the completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ variables (𝕜 E) lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E := begin set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm, have : uniform_embedding e.to_linear_equiv.to_equiv.symm := e.symm.uniform_embedding, exact (complete_space_congr this).1 (by apply_instance) end variables {𝕜 E} /-- A finite-dimensional subspace is complete. -/ lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_complete (s : set E) := complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s) /-- A finite-dimensional subspace is closed. -/ lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_closed (s : set E) := s.complete_of_finite_dimensional.is_closed lemma affine_subspace.closed_of_finite_dimensional {P : Type*} [metric_space P] [normed_add_torsor E P] (s : affine_subspace 𝕜 P) [finite_dimensional 𝕜 s.direction] : is_closed (s : set P) := s.is_closed_direction_iff.mp s.direction.closed_of_finite_dimensional section riesz /-- In an infinite dimensional space, given a finite number of points, one may find a point with norm at most `R` which is at distance at least `1` of all these points. -/ theorem exists_norm_le_le_norm_sub_of_finset {c : 𝕜} (hc : 1 < ∥c∥) {R : ℝ} (hR : ∥c∥ < R) (h : ¬ (finite_dimensional 𝕜 E)) (s : finset E) : ∃ (x : E), ∥x∥ ≤ R ∧ ∀ y ∈ s, 1 ≤ ∥y - x∥ := begin let F := submodule.span 𝕜 (s : set E), haveI : finite_dimensional 𝕜 F := module.finite_def.2 ((submodule.fg_top _).2 (submodule.fg_def.2 ⟨s, finset.finite_to_set _, rfl⟩)), have Fclosed : is_closed (F : set E) := submodule.closed_of_finite_dimensional _, have : ∃ x, x ∉ F, { contrapose! h, have : (⊤ : submodule 𝕜 E) = F, by { ext x, simp [h] }, have : finite_dimensional 𝕜 (⊤ : submodule 𝕜 E), by rwa this, refine module.finite_def.2 ((submodule.fg_top _).1 (module.finite_def.1 this)) }, obtain ⟨x, xR, hx⟩ : ∃ (x : E), ∥x∥ ≤ R ∧ ∀ (y : E), y ∈ F → 1 ≤ ∥x - y∥ := riesz_lemma_of_norm_lt hc hR Fclosed this, have hx' : ∀ (y : E), y ∈ F → 1 ≤ ∥y - x∥, { assume y hy, rw ← norm_neg, simpa using hx y hy }, exact ⟨x, xR, λ y hy, hx' _ (submodule.subset_span hy)⟩, end /-- In an infinite-dimensional normed space, there exists a sequence of points which are all bounded by `R` and at distance at least `1`. For a version not assuming `c` and `R`, see `exists_seq_norm_le_one_le_norm_sub`. -/ theorem exists_seq_norm_le_one_le_norm_sub' {c : 𝕜} (hc : 1 < ∥c∥) {R : ℝ} (hR : ∥c∥ < R) (h : ¬ (finite_dimensional 𝕜 E)) : ∃ f : ℕ → E, (∀ n, ∥f n∥ ≤ R) ∧ (∀ m n, m ≠ n → 1 ≤ ∥f m - f n∥) := begin haveI : is_symm E (λ (x y : E), 1 ≤ ∥x - y∥), { constructor, assume x y hxy, rw ← norm_neg, simpa }, apply exists_seq_of_forall_finset_exists' (λ (x : E), ∥x∥ ≤ R) (λ (x : E) (y : E), 1 ≤ ∥x - y∥), assume s hs, exact exists_norm_le_le_norm_sub_of_finset hc hR h s, end theorem exists_seq_norm_le_one_le_norm_sub (h : ¬ (finite_dimensional 𝕜 E)) : ∃ (R : ℝ) (f : ℕ → E), (1 < R) ∧ (∀ n, ∥f n∥ ≤ R) ∧ (∀ m n, m ≠ n → 1 ≤ ∥f m - f n∥) := begin obtain ⟨c, hc⟩ : ∃ (c : 𝕜), 1 < ∥c∥ := normed_field.exists_one_lt_norm 𝕜, have A : ∥c∥ < ∥c∥ + 1, by linarith, rcases exists_seq_norm_le_one_le_norm_sub' hc A h with ⟨f, hf⟩, exact ⟨∥c∥ + 1, f, hc.trans A, hf.1, hf.2⟩ end variable (𝕜) /-- **Riesz's theorem**: if a closed ball with center zero of positive radius is compact in a vector space, then the space is finite-dimensional. -/ theorem finite_dimensional_of_is_compact_closed_ball₀ {r : ℝ} (rpos : 0 < r) (h : is_compact (metric.closed_ball (0 : E) r)) : finite_dimensional 𝕜 E := begin by_contra hfin, obtain ⟨R, f, Rgt, fle, lef⟩ : ∃ (R : ℝ) (f : ℕ → E), (1 < R) ∧ (∀ n, ∥f n∥ ≤ R) ∧ (∀ m n, m ≠ n → 1 ≤ ∥f m - f n∥) := exists_seq_norm_le_one_le_norm_sub hfin, have rRpos : 0 < r / R := div_pos rpos (zero_lt_one.trans Rgt), obtain ⟨c, hc⟩ : ∃ (c : 𝕜), 0 < ∥c∥ ∧ ∥c∥ < (r / R) := normed_field.exists_norm_lt _ rRpos, let g := λ (n : ℕ), c • f n, have A : ∀ n, g n ∈ metric.closed_ball (0 : E) r, { assume n, simp only [norm_smul, dist_zero_right, metric.mem_closed_ball], calc ∥c∥ * ∥f n∥ ≤ (r / R) * R : mul_le_mul hc.2.le (fle n) (norm_nonneg _) rRpos.le ... = r : by field_simp [(zero_lt_one.trans Rgt).ne'] }, obtain ⟨x, hx, φ, φmono, φlim⟩ : ∃ (x : E) (H : x ∈ metric.closed_ball (0 : E) r) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (g ∘ φ) at_top (𝓝 x) := h.tendsto_subseq A, have B : cauchy_seq (g ∘ φ) := φlim.cauchy_seq, obtain ⟨N, hN⟩ : ∃ (N : ℕ), ∀ (n : ℕ), N ≤ n → dist ((g ∘ φ) n) ((g ∘ φ) N) < ∥c∥ := metric.cauchy_seq_iff'.1 B (∥c∥) hc.1, apply lt_irrefl (∥c∥), calc ∥c∥ ≤ dist (g (φ (N+1))) (g (φ N)) : begin conv_lhs { rw [← mul_one (∥c∥)] }, simp only [g, dist_eq_norm, ←smul_sub, norm_smul, -mul_one], apply mul_le_mul_of_nonneg_left (lef _ _ (ne_of_gt _)) (norm_nonneg _), exact φmono (nat.lt_succ_self N) end ... < ∥c∥ : hN (N+1) (nat.le_succ N) end /-- **Riesz's theorem**: if a closed ball of positive radius is compact in a vector space, then the space is finite-dimensional. -/ theorem finite_dimensional_of_is_compact_closed_ball {r : ℝ} (rpos : 0 < r) {c : E} (h : is_compact (metric.closed_ball c r)) : finite_dimensional 𝕜 E := begin apply finite_dimensional_of_is_compact_closed_ball₀ 𝕜 rpos, have : continuous (λ x, -c + x), from continuous_const.add continuous_id, simpa using h.image this, end end riesz /-- An injective linear map with finite-dimensional domain is a closed embedding. -/ lemma linear_equiv.closed_embedding_of_injective {f : E →ₗ[𝕜] F} (hf : f.ker = ⊥) [finite_dimensional 𝕜 E] : closed_embedding ⇑f := let g := linear_equiv.of_injective f (linear_map.ker_eq_bot.mp hf) in { closed_range := begin haveI := f.finite_dimensional_range, simpa [f.range_coe] using f.range.closed_of_finite_dimensional end, .. embedding_subtype_coe.comp g.to_continuous_linear_equiv.to_homeomorph.embedding } lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F] (f : E →L[𝕜] F) (hf : f.range = ⊤) : ∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F := let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in ⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩ lemma closed_embedding_smul_left {c : E} (hc : c ≠ 0) : closed_embedding (λ x : 𝕜, x • c) := linear_equiv.closed_embedding_of_injective (linear_map.ker_to_span_singleton 𝕜 E hc) /- `smul` is a closed map in the first argument. -/ lemma is_closed_map_smul_left (c : E) : is_closed_map (λ x : 𝕜, x • c) := begin by_cases hc : c = 0, { simp_rw [hc, smul_zero], exact is_closed_map_const }, { exact (closed_embedding_smul_left hc).is_closed_map } end open continuous_linear_map /-- Continuous linear equivalence between continuous linear functions `𝕜ⁿ → E` and `Eⁿ`. The spaces `𝕜ⁿ` and `Eⁿ` are represented as `ι → 𝕜` and `ι → E`, respectively, where `ι` is a finite type. -/ def continuous_linear_equiv.pi_ring (ι : Type*) [fintype ι] [decidable_eq ι] : ((ι → 𝕜) →L[𝕜] E) ≃L[𝕜] (ι → E) := { continuous_to_fun := begin refine continuous_pi (λ i, _), exact (continuous_linear_map.apply 𝕜 E (pi.single i 1)).continuous, end, continuous_inv_fun := begin simp_rw [linear_equiv.inv_fun_eq_symm, linear_equiv.trans_symm, linear_equiv.symm_symm], apply linear_map.continuous_of_bound _ (fintype.card ι : ℝ) (λ g, _), rw ← nsmul_eq_mul, apply op_norm_le_bound _ (nsmul_nonneg (norm_nonneg g) (fintype.card ι)) (λ t, _), simp_rw [linear_map.coe_comp, linear_equiv.coe_to_linear_map, function.comp_app, linear_map.coe_to_continuous_linear_map', linear_equiv.pi_ring_symm_apply], apply le_trans (norm_sum_le _ _), rw smul_mul_assoc, refine finset.sum_le_card_nsmul _ _ _ (λ i hi, _), rw [norm_smul, mul_comm], exact mul_le_mul (norm_le_pi_norm g i) (norm_le_pi_norm t i) (norm_nonneg _) (norm_nonneg g), end, .. linear_map.to_continuous_linear_map.symm.trans (linear_equiv.pi_ring 𝕜 E ι 𝕜) } /-- A family of continuous linear maps is continuous on `s` if all its applications are. -/ lemma continuous_on_clm_apply {X : Type*} [topological_space X] [finite_dimensional 𝕜 E] {f : X → E →L[𝕜] F} {s : set X} : continuous_on f s ↔ ∀ y, continuous_on (λ x, f x y) s := begin refine ⟨λ h y, (continuous_linear_map.apply 𝕜 F y).continuous.comp_continuous_on h, λ h, _⟩, let d := finrank 𝕜 E, have hd : d = finrank 𝕜 (fin d → 𝕜) := (finrank_fin_fun 𝕜).symm, let e₁ : E ≃L[𝕜] fin d → 𝕜 := continuous_linear_equiv.of_finrank_eq hd, let e₂ : (E →L[𝕜] F) ≃L[𝕜] fin d → F := (e₁.arrow_congr (1 : F ≃L[𝕜] F)).trans (continuous_linear_equiv.pi_ring (fin d)), rw [← function.comp.left_id f, ← e₂.symm_comp_self], exact e₂.symm.continuous.comp_continuous_on (continuous_on_pi.mpr (λ i, h _)) end lemma continuous_clm_apply {X : Type*} [topological_space X] [finite_dimensional 𝕜 E] {f : X → E →L[𝕜] F} : continuous f ↔ ∀ y, continuous (λ x, f x y) := by simp_rw [continuous_iff_continuous_on_univ, continuous_on_clm_apply] end complete_field section proper_field variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜] (E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜] /-- Any finite-dimensional vector space over a proper field is proper. We do not register this as an instance to avoid an instance loop when trying to prove the properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E := begin set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm, exact e.symm.antilipschitz.proper_space e.symm.continuous e.symm.surjective end end proper_field /- Over the real numbers, we can register the previous statement as an instance as it will not cause problems in instance resolution since the properness of `ℝ` is already known. -/ @[priority 900] instance finite_dimensional.proper_real (E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E := finite_dimensional.proper ℝ E /-- If `E` is a finite dimensional normed real vector space, `x : E`, and `s` is a neighborhood of `x` that is not equal to the whole space, then there exists a point `y ∈ frontier s` at distance `metric.inf_dist x sᶜ` from `x`. See also `is_compact.exists_mem_frontier_inf_dist_compl_eq_dist`. -/ lemma exists_mem_frontier_inf_dist_compl_eq_dist {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {x : E} {s : set E} (hx : x ∈ s) (hs : s ≠ univ) : ∃ y ∈ frontier s, metric.inf_dist x sᶜ = dist x y := begin rcases metric.exists_mem_closure_inf_dist_eq_dist (nonempty_compl.2 hs) x with ⟨y, hys, hyd⟩, rw closure_compl at hys, refine ⟨y, ⟨metric.closed_ball_inf_dist_compl_subset_closure hx $ metric.mem_closed_ball.2 $ ge_of_eq _, hys⟩, hyd⟩, rwa dist_comm end /-- If `K` is a compact set in a nontrivial real normed space and `x ∈ K`, then there exists a point `y` of the boundary of `K` at distance `metric.inf_dist x Kᶜ` from `x`. See also `exists_mem_frontier_inf_dist_compl_eq_dist`. -/ lemma is_compact.exists_mem_frontier_inf_dist_compl_eq_dist {E : Type*} [normed_group E] [normed_space ℝ E] [nontrivial E] {x : E} {K : set E} (hK : is_compact K) (hx : x ∈ K) : ∃ y ∈ frontier K, metric.inf_dist x Kᶜ = dist x y := begin obtain (hx'|hx') : x ∈ interior K ∪ frontier K, { rw ← closure_eq_interior_union_frontier, exact subset_closure hx }, { rw [mem_interior_iff_mem_nhds, metric.nhds_basis_closed_ball.mem_iff] at hx', rcases hx' with ⟨r, hr₀, hrK⟩, haveI : finite_dimensional ℝ E, from finite_dimensional_of_is_compact_closed_ball ℝ hr₀ (compact_of_is_closed_subset hK metric.is_closed_ball hrK), exact exists_mem_frontier_inf_dist_compl_eq_dist hx hK.ne_univ }, { refine ⟨x, hx', _⟩, rw frontier_eq_closure_inter_closure at hx', rw [metric.inf_dist_zero_of_mem_closure hx'.2, dist_self] }, end /-- In a finite dimensional vector space over `ℝ`, the series `∑ x, ∥f x∥` is unconditionally summable if and only if the series `∑ x, f x` is unconditionally summable. One implication holds in any complete normed space, while the other holds only in finite dimensional spaces. -/ lemma summable_norm_iff {α E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : α → E} : summable (λ x, ∥f x∥) ↔ summable f := begin refine ⟨summable_of_summable_norm, λ hf, _⟩, -- First we use a finite basis to reduce the problem to the case `E = fin N → ℝ` suffices : ∀ {N : ℕ} {g : α → fin N → ℝ}, summable g → summable (λ x, ∥g x∥), { obtain v := fin_basis ℝ E, set e := v.equiv_funL, have : summable (λ x, ∥e (f x)∥) := this (e.summable.2 hf), refine summable_of_norm_bounded _ (this.mul_left ↑(∥(e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E)∥₊)) (λ i, _), simpa using (e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E).le_op_norm (e $ f i) }, unfreezingI { clear_dependent E }, -- Now we deal with `g : α → fin N → ℝ` intros N g hg, have : ∀ i, summable (λ x, ∥g x i∥) := λ i, (pi.summable.1 hg i).abs, refine summable_of_norm_bounded _ (summable_sum (λ i (hi : i ∈ finset.univ), this i)) (λ x, _), rw [norm_norm, pi_norm_le_iff], { refine λ i, finset.single_le_sum (λ i hi, _) (finset.mem_univ i), exact norm_nonneg (g x i) }, { exact finset.sum_nonneg (λ _ _, norm_nonneg _) } end lemma summable_of_is_O' {ι E F : Type*} [normed_group E] [complete_space E] [normed_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {f : ι → E} {g : ι → F} (hg : summable g) (h : is_O f g cofinite) : summable f := summable_of_is_O (summable_norm_iff.mpr hg) h.norm_right lemma summable_of_is_O_nat' {E F : Type*} [normed_group E] [complete_space E] [normed_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {f : ℕ → E} {g : ℕ → F} (hg : summable g) (h : is_O f g at_top) : summable f := summable_of_is_O_nat (summable_norm_iff.mpr hg) h.norm_right lemma summable_of_is_equivalent {ι E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ι → E} {g : ι → E} (hg : summable g) (h : f ~[cofinite] g) : summable f := hg.trans_sub (summable_of_is_O' hg h.is_o.is_O) lemma summable_of_is_equivalent_nat {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ℕ → E} {g : ℕ → E} (hg : summable g) (h : f ~[at_top] g) : summable f := hg.trans_sub (summable_of_is_O_nat' hg h.is_o.is_O) lemma is_equivalent.summable_iff {ι E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ι → E} {g : ι → E} (h : f ~[cofinite] g) : summable f ↔ summable g := ⟨λ hf, summable_of_is_equivalent hf h.symm, λ hg, summable_of_is_equivalent hg h⟩ lemma is_equivalent.summable_iff_nat {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ℕ → E} {g : ℕ → E} (h : f ~[at_top] g) : summable f ↔ summable g := ⟨λ hf, summable_of_is_equivalent_nat hf h.symm, λ hg, summable_of_is_equivalent_nat hg h⟩
bb5288e13e096beb8c31cf8be8f8c3b4cc1994d1
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/polynomial/field_division.lean
e35336bad2f994d82ca8a55a4d9d998b4fa4247b
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
19,777
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.ring_division import data.polynomial.derivative import algebra.gcd_monoid /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section integral_domain variables [integral_domain R] [normalization_monoid R] instance : normalization_monoid (polynomial R) := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : polynomial R} : (norm_unit p : polynomial R) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : polynomial R) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp end integral_domain section field variables [field R] {p q : polynomial R} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp; exact (hp $ is_unit.map' C $ is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial R) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] theorem irreducible_of_monic {p : polynomial R} (hp1 : p.monic) (hp2 : p ≠ 1) : irreducible p ↔ (∀ f g : polynomial R, f.monic → g.monic → f * g = p → f = 1 ∨ g = 1) := ⟨λ hp3 f g hf hg hfg, or.cases_on (hp3.is_unit_or_is_unit hfg.symm) (assume huf : is_unit f, or.inl $ eq_one_of_is_unit_of_monic hf huf) (assume hug : is_unit g, or.inr $ eq_one_of_is_unit_of_monic hg hug), λ hp3, ⟨mt (eq_one_of_is_unit_of_monic hp1) hp2, λ f g hp, have hf : f ≠ 0, from λ hf, by { rw [hp, hf, zero_mul] at hp1, exact not_monic_zero hp1 }, have hg : g ≠ 0, from λ hg, by { rw [hp, hg, mul_zero] at hp1, exact not_monic_zero hp1 }, or.imp (λ hf, is_unit_of_mul_eq_one _ _ hf) (λ hg, is_unit_of_mul_eq_one _ _ hg) $ hp3 (f * C f.leading_coeff⁻¹) (g * C g.leading_coeff⁻¹) (monic_mul_leading_coeff_inv hf) (monic_mul_leading_coeff_inv hg) $ by rw [mul_assoc, mul_left_comm _ g, ← mul_assoc, ← C_mul, ← mul_inv', ← leading_coeff_mul, ← hp, monic.def.1 hp1, inv_one, C_1, mul_one]⟩⟩ /-- Division of polynomials. See polynomial.div_by_monic for more details.-/ def div (p q : polynomial R) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division, see the lemma `quotient_mul_add_remainder_eq_aux`. See polynomial.mod_by_monic for more details. -/ def mod (p q : polynomial R) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial R) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial R) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial R) := ⟨div⟩ instance : has_mod (polynomial R) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial R) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv_rhs { rw [← euclidean_domain.div_add_mod p q, degree_add_eq_left_of_degree_lt this, degree_mul] } lemma degree_div_le (p q : polynomial R) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field k] (p : polynomial R) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [field k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [field k] {f : R →+* k} {p : polynomial R} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [f.map_inv, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← f.map_inv, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : polynomial R} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : polynomial R} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← gcd_is_unit_iff, ← gcd_is_unit_iff, gcd_map, is_unit_map] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, f.map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp lemma mem_roots_map [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := begin rw mem_roots (show p.map f ≠ 0, by exact map_ne_zero hp), dsimp only [is_root], rw polynomial.eval_map, end lemma mem_root_set [field k] [algebra R k] {x : k} (hp : p ≠ 0) : x ∈ p.root_set k ↔ aeval x p = 0 := iff.trans multiset.mem_to_finset (mem_roots_map hp) lemma root_set_C_mul_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (C a * X ^ n).root_set S = {0} := begin ext x, rw [set.mem_singleton_iff, mem_root_set, aeval_mul, aeval_C, aeval_X_pow, mul_eq_zero], { simp_rw [ring_hom.map_eq_zero, pow_eq_zero_iff (nat.pos_of_ne_zero hn), or_iff_right_iff_imp], exact λ ha', (ha ha').elim }, { exact mul_ne_zero (mt C_eq_zero.mp ha) (pow_ne_zero n X_ne_zero) }, end lemma root_set_monomial {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (monomial n a).root_set S = {0} := by rw [←C_mul_X_pow_eq_monomial, root_set_C_mul_X_pow hn ha] lemma root_set_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) : (X ^ n : polynomial R).root_set S = {0} := by { rw [←one_mul (X ^ n : polynomial R), ←C_1, root_set_C_mul_X_pow hn], exact one_ne_zero } lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial R)) (n : ℕ) : ((↑u : polynomial R).coeff n)⁻¹ = ((↑u⁻¹ : polynomial R).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : polynomial R) = C p.leading_coeff⁻¹ := by simp [hp] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : polynomial R} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff (polynomial R), normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← f.map_inv, ← map_C, ← map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from prime_of_degree_eq_one_of_monic (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), prime_of_associated normalize_associated this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one hp1) theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on (λ i : I, polynomial.X - polynomial.C (s i))) := λ i j hij, have h : s j - s i ≠ 0, from sub_ne_zero_of_ne $ function.injective.ne H hij.symm, ⟨polynomial.C (s j - s i)⁻¹, -polynomial.C (s j - s i)⁻¹, by rw [neg_mul_eq_neg_mul_symm, ← sub_eq_add_neg, ← mul_sub, sub_sub_sub_cancel_left, ← polynomial.C_sub, ← polynomial.C_mul, inv_mul_cancel h, polynomial.C_1]⟩ /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end lemma prod_multiset_root_eq_finset_root {p : polynomial R} (hzero : p ≠ 0) : (multiset.map (λ (a : R), X - C a) p.roots).prod = ∏ a in (multiset.to_finset p.roots), (λ (a : R), (X - C a) ^ (root_multiplicity a p)) a := by simp only [count_roots hzero, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : polynomial R) : (multiset.map (λ (a : R), X - C a) p.roots).prod ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, is_unit_one, multiset.prod_zero, multiset.map_zero, is_unit.dvd] }, rw prod_multiset_root_eq_finset_root hp0, have hcoprime : pairwise (is_coprime on λ (a : R), polynomial.X - C (id a)) := pairwise_coprime_X_sub function.injective_id, have H : pairwise (is_coprime on λ (a : R), (polynomial.X - C (id a)) ^ (root_multiplicity a p)), { intros a b hdiff, exact (hcoprime a b hdiff).pow }, apply finset.prod_dvd_of_coprime (pairwise.pairwise_on H (↑(multiset.to_finset p.roots) : set R)), intros a h, rw multiset.mem_to_finset at h, exact pow_root_multiplicity_dvd p a end lemma roots_C_mul (p : polynomial R) {a : R} (hzero : a ≠ 0) : (C a * p).roots = p.roots := begin by_cases hpzero : p = 0, { simp only [hpzero, mul_zero] }, rw multiset.ext, intro b, have prodzero : C a * p ≠ 0, { simp only [hpzero, or_false, ne.def, mul_eq_zero, C_eq_zero, hzero, not_false_iff] }, rw [count_roots hpzero, count_roots prodzero, root_multiplicity_mul prodzero], have mulzero : root_multiplicity b (C a) = 0, { simp only [hzero, root_multiplicity_eq_zero, eval_C, is_root.def, not_false_iff] }, simp only [mulzero, zero_add] end lemma roots_normalize : (normalize p).roots = p.roots := begin by_cases hzero : p = 0, { rw [hzero, normalize_zero], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, rw [normalize_apply, mul_comm, coe_norm_unit_of_ne_zero hzero, roots_C_mul _ (inv_ne_zero hcoeff)], }, end end field end polynomial
c43a4fc0cc6f01914186418c5234fbb2df97712e
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/measure_theory/bochner_integration.lean
bda4ddb7488fe18054a055150afee72f33e7f84e
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
55,209
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.simple_func_dense import analysis.normed_space.bounded_linear_maps /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here by extending the integral on simple functions. ## Main definitions The Bochner integral is defined following these steps: 1. Define the integral on simple functions of the type `simple_func α β` (notation : `α →ₛ β`) where `β` is a real normed space. (See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral` for the integral on simple functions of the type `simple_func α ennreal`.) 2. Use `simple_func α β` to cut out the simple functions from L1 functions, and define integral on these. The type of simple functions in L1 space is written as `α →₁ₛ β`. 3. Show that the embedding of `α →₁ₛ β` into L1 is a dense and uniform one. 4. Show that the integral defined on `α →₁ₛ β` is a continuous linear map. 5. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ β` using `continuous_linear_map.extend`. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space. ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → β`, where `α` is a measure space and `β` is a real normed space. * `integral_zero` : `∫ 0 = 0` * `integral_add` : `∫ f + g = ∫ f + ∫ g` * `integral_neg` : `∫ -f = - ∫ f` * `integral_sub` : `∫ f - g = ∫ f - ∫ g` * `integral_smul` : `∫ r • f = r • ∫ f` * `integral_congr_ae` : `∀ₘ a, f a = g a → ∫ f = ∫ g` * `norm_integral_le_integral_norm` : `∥∫ f∥ ≤ ∫ ∥f∥` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `∀ₘ a, 0 ≤ f a → 0 ≤ ∫ f` * `integral_nonpos_of_nonpos_ae` : `∀ₘ a, f a ≤ 0 → ∫ f ≤ 0` * `integral_le_integral_of_le_ae` : `∀ₘ a, f a ≤ g a → ∫ f ≤ ∫ g` 3. Propositions connecting the Bochner integral with the integral on `ennreal`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_max_sub_lintegral_min` : `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `∀ₘ a, 0 ≤ f a → ∫ f = ∫⁻ f` 4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function f : α → ℝ, and second and third integral sign being the integral on ennreal-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is scattered in sections with the name `pos_part`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in `L¹` space. Rewrite using `l1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like `l1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `is_closed_property` or `dense_range.induction_on` for this argument. ## Notations * `α →ₛ β` : simple functions (defined in `measure_theory/integration`) * `α →₁ β` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/l1_space`) * `α →₁ₛ β` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space -- Typeclass inference has difficulty finding `has_scalar ℝ β` where `β` is a `normed_space` on `ℝ` local attribute [instance, priority 10000] mul_action.to_has_scalar distrib_mul_action.to_mul_action add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_module module.to_semimodule namespace measure_theory universes u v w variables {α : Type u} [measurable_space α] {β : Type v} [decidable_linear_order β] [has_zero β] local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ β) : α →ₛ β := f.map (λb, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg β] (f : α →ₛ β) : α →ₛ β := pos_part (-f) lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f := begin ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], rw [pos_part, map_apply], exact le_max_right _ _ end lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f := by { rw neg_part, exact pos_part_map_norm _ } lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f := begin simp only [pos_part, neg_part], ext, exact max_zero_sub_eq_self (f a) end end pos_part end simple_func end measure_theory namespace measure_theory open set filter topological_space ennreal emetric universes u v w variables {α : Type u} [measure_space α] {β : Type v} {γ : Type w} local infixr ` →ₛ `:25 := simple_func namespace simple_func section bintegral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open finset variables [normed_group β] [normed_group γ] lemma integrable_iff_integral_lt_top {f : α →ₛ β} : integrable f ↔ integral (f.map (coe ∘ nnnorm)) < ⊤ := by { rw [integrable, ← lintegral_eq_integral, lintegral_map] } lemma fin_vol_supp_of_integrable {f : α →ₛ β} (hf : integrable f) : f.fin_vol_supp := begin rw [integrable_iff_integral_lt_top] at hf, have hf := fin_vol_supp_of_integral_lt_top hf, refine fin_vol_supp_of_fin_vol_supp_map f hf _, assume b, simp [nnnorm_eq_zero] end lemma integrable_of_fin_vol_supp {f : α →ₛ β} (h : f.fin_vol_supp) : integrable f := by { rw [integrable_iff_integral_lt_top], exact integral_map_coe_lt_top h nnnorm_zero } /-- For simple functions with a `normed_group` as codomain, being integrable is the same as having finite volume support. -/ lemma integrable_iff_fin_vol_supp (f : α →ₛ β) : integrable f ↔ f.fin_vol_supp := iff.intro fin_vol_supp_of_integrable integrable_of_fin_vol_supp lemma integrable_pair {f : α →ₛ β} {g : α →ₛ γ} (hf : integrable f) (hg : integrable g) : integrable (pair f g) := by { rw integrable_iff_fin_vol_supp at *, apply fin_vol_supp_pair; assumption } variables [normed_space ℝ γ] /-- Bochner integral of simple functions whose codomain is a real `normed_space`. The name `simple_func.integral` has been taken in the file `integration.lean`, which calculates the integral of a simple function with type `α → ennreal`. The name `bintegral` stands for Bochner integral. -/ def bintegral [normed_space ℝ β] (f : α →ₛ β) : β := f.range.sum (λ x, (ennreal.to_real (volume (f ⁻¹' {x}))) • x) /-- Calculate the integral of `g ∘ f : α →ₛ γ`, where `f` is an integrable function from `α` to `β` and `g` is a function from `β` to `γ`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_bintegral (f : α →ₛ β) (g : β → γ) (hf : integrable f) (hg : g 0 = 0) : (f.map g).bintegral = f.range.sum (λ x, (ennreal.to_real (volume (f ⁻¹' {x}))) • (g x)) := begin /- Just a complicated calculation with `finset.sum`. Real work is done by `map_preimage_singleton`, `simple_func.volume_bUnion_preimage` and `ennreal.to_real_sum` -/ rw integrable_iff_fin_vol_supp at hf, simp only [bintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, let s' := f.range.filter (λb, g b = g (f a)), calc (ennreal.to_real (volume ((f.map g) ⁻¹' {g (f a)}))) • (g (f a)) = (ennreal.to_real (volume (⋃b∈s', f ⁻¹' {b}))) • (g (f a)) : by rw map_preimage_singleton ... = (ennreal.to_real (s'.sum (λb, volume (f ⁻¹' {b})))) • (g (f a)) : by rw volume_bUnion_preimage ... = (s'.sum (λb, ennreal.to_real (volume (f ⁻¹' {b})))) • (g (f a)) : begin by_cases h : g (f a) = 0, { rw [h, smul_zero, smul_zero] }, { rw ennreal.to_real_sum, simp only [mem_filter], rintros b ⟨_, hb⟩, have : b ≠ 0, { assume hb', rw [← hb, hb'] at h, contradiction }, apply hf, assumption } end ... = s'.sum (λb, (ennreal.to_real (volume (f ⁻¹' {b}))) • (g (f a))) : finset.sum_smul ... = s'.sum (λb, (ennreal.to_real (volume (f ⁻¹' {b}))) • (g b)) : finset.sum_congr rfl $ by { assume x, simp only [mem_filter], rintro ⟨_, h⟩, rw h } end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `bintegral_eq_integral'` for a simpler version. -/ lemma bintegral_eq_integral {f : α →ₛ β} {g : β → ennreal} (hf : integrable f) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).bintegral = ennreal.to_real (f.map g).integral := begin have hf' : f.fin_vol_supp, { rwa integrable_iff_fin_vol_supp at hf }, rw [map_bintegral f _ hf, map_integral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul], rw [to_real_mul_to_real, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_lt_top }, apply mul_lt_top (hgt a) (hf' _ a0) }, { simp [hg0] } end /-- `simple_func.bintegral` and `lintegral : (α → ennreal) → ennreal` are the same when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `bintegral_eq_lintegral'` for a simpler version. -/ lemma bintegral_eq_lintegral (f : α →ₛ β) (g : β → ennreal) (hf : integrable f) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).bintegral = ennreal.to_real (∫⁻ a, g (f a)) := by { rw [bintegral_eq_integral hf hg0 hgt, ← lintegral_eq_integral], refl } variables [normed_space ℝ β] lemma bintegral_congr {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) (h : ∀ₘ a, f a = g a): bintegral f = bintegral g := show ((pair f g).map prod.fst).bintegral = ((pair f g).map prod.snd).bintegral, from begin have inte := integrable_pair hf hg, rw [map_bintegral (pair f g) _ inte prod.fst_zero, map_bintegral (pair f g) _ inte prod.snd_zero], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine volume_mono_null (assume a' ha', _) h, simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] }, end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/ lemma bintegral_eq_integral' {f : α →ₛ ℝ} (hf : integrable f) (h_pos : ∀ₘ a, 0 ≤ f a) : f.bintegral = ennreal.to_real (f.map ennreal.of_real).integral := begin have : ∀ₘ a, f a = (f.map (ennreal.to_real ∘ ennreal.of_real)) a, { filter_upwards [h_pos], assume a, simp only [mem_set_of_eq, map_apply, function.comp_apply], assume h, exact (ennreal.to_real_of_real h).symm }, rw ← bintegral_eq_integral hf, { refine bintegral_congr hf _ this, exact integrable_of_ae_eq hf this }, { exact ennreal.of_real_zero }, { assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top } end /-- `simple_func.bintegral` and `lintegral : (α → ennreal) → ennreal` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/ lemma bintegral_eq_lintegral' {f : α →ₛ ℝ} (hf : integrable f) (h_pos : ∀ₘ a, 0 ≤ f a) : f.bintegral = ennreal.to_real (∫⁻ a, (f.map ennreal.of_real a)) := by rw [bintegral_eq_integral' hf h_pos, ← lintegral_eq_integral] lemma bintegral_add {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) : bintegral (f + g) = bintegral f + bintegral g := calc bintegral (f + g) = (pair f g).range.sum (λx, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • (x.fst + x.snd)) : begin rw [add_eq_map₂, map_bintegral (pair f g)], { exact integrable_pair hf hg }, { simp only [add_zero, prod.fst_zero, prod.snd_zero] } end ... = (pair f g).range.sum (λx, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.fst + ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.snd) : finset.sum_congr rfl $ assume a ha, smul_add _ _ _ ... = (simple_func.range (pair f g)).sum (λ (x : β × β), ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.fst) + (simple_func.range (pair f g)).sum (λ (x : β × β), ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.snd) : by rw finset.sum_add_distrib ... = ((pair f g).map prod.fst).bintegral + ((pair f g).map prod.snd).bintegral : begin rw [map_bintegral (pair f g), map_bintegral (pair f g)], { exact integrable_pair hf hg }, { refl }, { exact integrable_pair hf hg }, { refl } end ... = bintegral f + bintegral g : rfl lemma bintegral_neg {f : α →ₛ β} (hf : integrable f) : bintegral (-f) = - bintegral f := calc bintegral (-f) = bintegral (f.map (has_neg.neg)) : rfl ... = - bintegral f : begin rw [map_bintegral f _ hf neg_zero, bintegral, ← sum_neg_distrib], refine finset.sum_congr rfl (λx h, smul_neg _ _), end lemma bintegral_sub {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) : bintegral (f - g) = bintegral f - bintegral g := begin have : f - g = f + (-g) := rfl, rw [this, bintegral_add hf _, bintegral_neg hg], { refl }, exact hg.neg end lemma bintegral_smul (r : ℝ) {f : α →ₛ β} (hf : integrable f) : bintegral (r • f) = r • bintegral f := calc bintegral (r • f) = f.range.sum (λx, ennreal.to_real (volume (f ⁻¹' {x})) • r • x) : by rw [smul_eq_map r f, map_bintegral f _ hf (smul_zero _)] ... = f.range.sum (λ (x : β), ((ennreal.to_real (volume (f ⁻¹' {x}))) * r) • x) : finset.sum_congr rfl $ λb hb, by apply smul_smul ... = r • bintegral f : begin rw [bintegral, smul_sum], refine finset.sum_congr rfl (λb hb, _), rw [smul_smul, mul_comm] end lemma norm_bintegral_le_bintegral_norm (f : α →ₛ β) (hf : integrable f) : ∥f.bintegral∥ ≤ (f.map norm).bintegral := begin rw map_bintegral f norm hf norm_zero, rw bintegral, calc ∥f.range.sum (λx, ennreal.to_real (volume (f ⁻¹' {x})) • x)∥ ≤ f.range.sum (λx, ∥ennreal.to_real (volume (f ⁻¹' {x})) • x∥) : norm_sum_le _ _ ... = f.range.sum (λx, ennreal.to_real (volume (f ⁻¹' {x})) • ∥x∥) : begin refine finset.sum_congr rfl (λb hb, _), rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg] end end end bintegral end simple_func namespace l1 open ae_eq_fun variables [normed_group β] [second_countable_topology β] [measurable_space β] [borel_space β] [normed_group γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] variables (α β) /-- `l1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple function. -/ def simple_func : Type (max u v) := { f : α →₁ β // ∃ (s : α →ₛ β), integrable s ∧ ae_eq_fun.mk s s.measurable = f} -- TODO: it seems that `ae_eq_fun.mk s s.measurable = f` implies `integrable s` variables {α β} infixr ` →₁ₛ `:25 := measure_theory.l1.simple_func namespace simple_func section instances /-! Simple functions in L1 space form a `normed_space`. -/ instance : has_coe (α →₁ₛ β) (α →₁ β) := ⟨subtype.val⟩ protected lemma eq {f g : α →₁ₛ β} : (f : α →₁ β) = (g : α →₁ β) → f = g := subtype.eq protected lemma eq' {f g : α →₁ₛ β} : (f : α →ₘ β) = (g : α →ₘ β) → f = g := subtype.eq ∘ subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ₛ β} : (f : α →₁ β) = (g : α →₁ β) ↔ f = g := iff.intro (subtype.eq) (congr_arg coe) @[norm_cast] protected lemma eq_iff' {f g : α →₁ₛ β} : (f : α →ₘ β) = (g : α →ₘ β) ↔ f = g := iff.intro (simple_func.eq') (congr_arg _) /-- L1 simple functions forms a `emetric_space`, with the emetric being inherited from L1 space, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def emetric_space : emetric_space (α →₁ₛ β) := subtype.emetric_space /-- L1 simple functions forms a `metric_space`, with the metric being inherited from L1 space, i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`). Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def metric_space : metric_space (α →₁ₛ β) := subtype.metric_space local attribute [instance] protected lemma is_add_subgroup : is_add_subgroup (λf:α →₁ β, ∃ (s : α →ₛ β), integrable s ∧ ae_eq_fun.mk s s.measurable = f) := { zero_mem := ⟨0, integrable_zero _ _, rfl⟩, add_mem := begin rintros f g ⟨s, hsi, hs⟩ ⟨t, hti, ht⟩, use s + t, split, { exact hsi.add s.measurable t.measurable hti }, { rw [coe_add, ← hs, ← ht], refl } end, neg_mem := begin rintros f ⟨s, hsi, hs⟩, use -s, split, { exact hsi.neg }, { rw [coe_neg, ← hs], refl } end } /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def add_comm_group : add_comm_group (α →₁ₛ β) := subtype.add_comm_group local attribute [instance] simple_func.add_comm_group simple_func.metric_space simple_func.emetric_space instance : inhabited (α →₁ₛ β) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ₛ β) : α →₁ β) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ₛ β) : ((f + g : α →₁ₛ β) : α →₁ β) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ₛ β) : ((-f : α →₁ₛ β) : α →₁ β) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ₛ β) : ((f - g : α →₁ₛ β) : α →₁ β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ₛ β) : edist f g = edist (f : α →₁ β) (g : α →₁ β) := rfl @[simp] lemma dist_eq (f g : α →₁ₛ β) : dist f g = dist (f : α →₁ β) (g : α →₁ β) := rfl /-- The norm on `α →₁ₛ β` is inherited from L1 space. That is, `∥f∥ = ∫⁻ a, edist (f a) 0`. Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def has_norm : has_norm (α →₁ₛ β) := ⟨λf, ∥(f : α →₁ β)∥⟩ local attribute [instance] simple_func.has_norm lemma norm_eq (f : α →₁ₛ β) : ∥f∥ = ∥(f : α →₁ β)∥ := rfl lemma norm_eq' (f : α →₁ₛ β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ β) 0) := rfl /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def normed_group : normed_group (α →₁ₛ β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add, l1.dist_eq, l1.coe_add], rw edist_eq_add_add } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def has_scalar : has_scalar 𝕜 (α →₁ₛ β) := ⟨λk f, ⟨k • f, begin rcases f with ⟨f, ⟨s, hsi, hs⟩⟩, use k • s, split, { exact integrable.smul _ hsi }, { rw [coe_smul, subtype.coe_mk, ← hs], refl } end ⟩⟩ local attribute [instance, priority 10000] simple_func.has_scalar @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ β) : ((c • f : α →₁ₛ β) : α →₁ β) = c • (f : α →₁ β) := rfl /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def semimodule : semimodule 𝕜 (α →₁ₛ β) := { one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, simple_func.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, simple_func.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def module : module 𝕜 (α →₁ₛ β) := { .. simple_func.semimodule } /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def vector_space : vector_space 𝕜 (α →₁ₛ β) := { .. simple_func.semimodule } local attribute [instance] simple_func.vector_space simple_func.normed_group /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def normed_space : normed_space 𝕜 (α →₁ₛ β) := ⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩ end instances local attribute [instance] simple_func.normed_group simple_func.normed_space section of_simple_func /-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/ @[reducible] def of_simple_func (f : α →ₛ β) (hf : integrable f) : (α →₁ₛ β) := ⟨l1.of_fun f f.measurable hf, ⟨f, ⟨hf, rfl⟩⟩⟩ lemma of_simple_func_eq_of_fun (f : α →ₛ β) (hf : integrable f) : (of_simple_func f hf : α →₁ β) = l1.of_fun f f.measurable hf := rfl lemma of_simple_func_eq_mk (f : α →ₛ β) (hf : integrable f) : (of_simple_func f hf : α →ₘ β) = ae_eq_fun.mk f f.measurable := rfl lemma of_simple_func_zero : of_simple_func (0 : α →ₛ β) (integrable_zero α β) = 0 := rfl lemma of_simple_func_add (f g : α →ₛ β) (hf hg) : of_simple_func (f + g) (integrable.add f.measurable hf g.measurable hg) = of_simple_func f hf + of_simple_func g hg := rfl lemma of_simple_func_neg (f : α →ₛ β) (hf) : of_simple_func (-f) (integrable.neg hf) = -of_simple_func f hf := rfl lemma of_simple_func_sub (f g : α →ₛ β) (hf hg) : of_simple_func (f - g) (integrable.sub f.measurable hf g.measurable hg) = of_simple_func f hf - of_simple_func g hg := rfl variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_simple_func_smul (f : α →ₛ β) (hf) (c : 𝕜) : of_simple_func (c • f) (integrable.smul _ hf) = c • of_simple_func f hf := rfl lemma norm_of_simple_func (f : α →ₛ β) (hf) : ∥of_simple_func f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0) := rfl end of_simple_func section to_simple_func /-- Find a representative of a `l1.simple_func`. -/ def to_simple_func (f : α →₁ₛ β) : α →ₛ β := classical.some f.2 /-- `f.to_simple_func` is measurable. -/ protected lemma measurable (f : α →₁ₛ β) : measurable f.to_simple_func := f.to_simple_func.measurable /-- `f.to_simple_func` is integrable. -/ protected lemma integrable (f : α →₁ₛ β) : integrable f.to_simple_func := let ⟨h, _⟩ := classical.some_spec f.2 in h lemma of_simple_func_to_simple_func (f : α →₁ₛ β) : of_simple_func (f.to_simple_func) f.integrable = f := by { rw ← simple_func.eq_iff', exact (classical.some_spec f.2).2 } lemma to_simple_func_of_simple_func (f : α →ₛ β) (hfi) : ∀ₘ a, (of_simple_func f hfi).to_simple_func a = f a := by { rw ← mk_eq_mk, exact (classical.some_spec (of_simple_func f hfi).2).2 } lemma to_simple_func_eq_to_fun (f : α →₁ₛ β) : ∀ₘ a, (f.to_simple_func) a = (f : α →₁ β).to_fun a := begin rw [← of_fun_eq_of_fun (f.to_simple_func) (f : α →₁ β).to_fun f.measurable f.integrable (f:α→₁β).measurable (f:α→₁β).integrable, ← l1.eq_iff], simp only [of_fun_eq_mk], rcases classical.some_spec f.2 with ⟨_, h⟩, convert h, rw mk_to_fun, refl end variables (α β) lemma zero_to_simple_func : ∀ₘ a, (0 : α →₁ₛ β).to_simple_func a = 0 := begin filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ β), l1.zero_to_fun α β], assume a, simp only [mem_set_of_eq], assume h, rw h, assume h, exact h end variables {α β} lemma add_to_simple_func (f g : α →₁ₛ β) : ∀ₘ a, (f + g).to_simple_func a = f.to_simple_func a + g.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.add_to_fun (f:α→₁β) g], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma neg_to_simple_func (f : α →₁ₛ β) : ∀ₘ a, (-f).to_simple_func a = - f.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, l1.neg_to_fun (f:α→₁β)], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma sub_to_simple_func (f g : α →₁ₛ β) : ∀ₘ a, (f - g).to_simple_func a = f.to_simple_func a - g.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.sub_to_fun (f:α→₁β) g], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ β) : ∀ₘ a, (k • f).to_simple_func a = k • f.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f, l1.smul_to_fun k (f:α→₁β)], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ β) : (∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func g) x)) < ⊤ := begin rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g), exact lintegral_edist_to_fun_lt_top _ _ end lemma dist_to_simple_func (f g : α →₁ₛ β) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_simple_func x) (g.to_simple_func x)) := begin rw [dist_eq, l1.dist_to_fun, ennreal.to_real_eq_to_real], { rw lintegral_rw₂, repeat { exact all_ae_eq_symm (to_simple_func_eq_to_fun _) } }, { exact l1.lintegral_edist_to_fun_lt_top _ _ }, { exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_to_simple_func (f : α →₁ₛ β) : ∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a)) := calc ∥f∥ = ennreal.to_real (∫⁻x, edist (f.to_simple_func x) ((0 : α →₁ₛ β).to_simple_func x)) : begin rw [← dist_zero_right, dist_to_simple_func] end ... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x)) : begin rw lintegral_nnnorm_eq_lintegral_edist, have : (∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func (0:α→₁ₛβ)) x)) = ∫⁻ (x : α), edist ((to_simple_func f) x) 0, { apply lintegral_congr_ae, filter_upwards [zero_to_simple_func α β], assume a, simp only [mem_set_of_eq], assume h, rw h }, rw [ennreal.to_real_eq_to_real], { exact this }, { exact lintegral_edist_to_simple_func_lt_top _ _ }, { rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_eq_bintegral (f : α →₁ₛ β) : ∥f∥ = (f.to_simple_func.map norm).bintegral := calc ∥f∥ = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x)) : by { rw norm_to_simple_func } ... = (f.to_simple_func.map norm).bintegral : begin rw ← f.to_simple_func.bintegral_eq_lintegral (coe ∘ nnnorm) f.integrable, { congr }, { simp only [nnnorm_zero, function.comp_app, ennreal.coe_zero] }, { assume b, exact coe_lt_top } end end to_simple_func section coe_to_l1 /-! The embedding of integrable simple functions `α →₁ₛ β` into L1 is a uniform and dense embedding. -/ lemma exists_simple_func_near (f : α →₁ β) {ε : ℝ} (ε0 : 0 < ε) : ∃ s : α →₁ₛ β, dist f s < ε := begin rcases f with ⟨⟨f, hfm⟩, hfi⟩, simp only [integrable_mk, quot_mk_eq_mk] at hfi, rcases simple_func_sequence_tendsto' hfm hfi with ⟨F, ⟨h₁, h₂⟩⟩, rw ennreal.tendsto_at_top at h₂, rcases h₂ (ennreal.of_real (ε/2)) (of_real_pos.2 $ half_pos ε0) with ⟨N, hN⟩, have : (∫⁻ (x : α), nndist (F N x) (f x)) < ennreal.of_real ε := calc (∫⁻ (x : α), nndist (F N x) (f x)) ≤ 0 + ennreal.of_real (ε/2) : (hN N (le_refl _)).2 ... < ennreal.of_real ε : by { simp only [zero_add, of_real_lt_of_real_iff ε0], exact half_lt_self ε0 }, { refine ⟨of_simple_func (F N) (h₁ N), _⟩, rw dist_comm, rw lt_of_real_iff_to_real_lt _ at this, { simpa [edist_mk_mk', of_simple_func, l1.of_fun, l1.dist_eq] }, rw ← lt_top_iff_ne_top, exact lt_trans this (by simp [lt_top_iff_ne_top, of_real_ne_top]) }, { exact zero_ne_top } end protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ β) → (α →₁ β)) := uniform_continuous_comap protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ β) → (α →₁ β)) := uniform_embedding_comap subtype.val_injective protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.uniform_embedding.to_uniform_inducing protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.uniform_embedding.dense_embedding $ λ f, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨s, h⟩ := exists_simple_func_near f ε0 in ⟨_, hε (metric.mem_ball'.2 h), s, rfl⟩ protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.dense_embedding.to_dense_inducing protected lemma dense_range : dense_range (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.dense_inducing.dense variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 β] variables (α β) /-- The uniform and dense embedding of L1 simple functions into L1 functions. -/ def coe_to_l1 : (α →₁ₛ β) →L[𝕜] (α →₁ β) := { to_fun := (coe : (α →₁ₛ β) → (α →₁ β)), add := λf g, rfl, smul := λk f, rfl, cont := l1.simple_func.uniform_continuous.continuous, } variables {α β 𝕜} end coe_to_l1 section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ ℝ) : α →₁ₛ ℝ := ⟨l1.pos_part (f : α →₁ ℝ), begin rcases f with ⟨f, s, hsi, hsf⟩, use s.pos_part, split, { exact integrable.max_zero hsi }, { simp only [subtype.coe_mk], rw [l1.coe_pos_part, ← hsf, ae_eq_fun.pos_part, ae_eq_fun.zero_def, comp₂_mk_mk, mk_eq_mk], filter_upwards [], simp only [mem_set_of_eq], assume a, refl } end ⟩ /-- Negative part of a simple function in L1 space. -/ def neg_part (f : α →₁ₛ ℝ) : α →₁ₛ ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ₛ ℝ) : (f.pos_part : α →₁ ℝ) = (f : α →₁ ℝ).pos_part := rfl @[norm_cast] lemma coe_neg_part (f : α →₁ₛ ℝ) : (f.neg_part : α →₁ ℝ) = (f : α →₁ ℝ).neg_part := rfl end pos_part section simple_func_integral /-! Define the Bochner integral on `α →₁ₛ β` and prove basic properties of this integral. -/ variables [normed_space ℝ β] /-- The Bochner integral over simple functions in l1 space. -/ def integral (f : α →₁ₛ β) : β := (f.to_simple_func).bintegral lemma integral_eq_bintegral (f : α →₁ₛ β) : integral f = (f.to_simple_func).bintegral := rfl lemma integral_eq_lintegral {f : α →₁ₛ ℝ} (h_pos : ∀ₘ a, 0 ≤ f.to_simple_func a) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real (f.to_simple_func a)) := by { rw [integral, simple_func.bintegral_eq_lintegral' f.integrable h_pos], refl } lemma integral_congr (f g : α →₁ₛ β) (h : ∀ₘ a, f.to_simple_func a = g.to_simple_func a) : integral f = integral g := by { simp only [integral], apply simple_func.bintegral_congr f.integrable g.integrable, exact h } lemma integral_add (f g : α →₁ₛ β) : integral (f + g) = integral f + integral g := begin simp only [integral], rw ← simple_func.bintegral_add f.integrable g.integrable, apply simple_func.bintegral_congr (f + g).integrable, { exact f.integrable.add f.measurable g.measurable g.integrable }, { apply add_to_simple_func }, end lemma integral_smul (r : ℝ) (f : α →₁ₛ β) : integral (r • f) = r • integral f := begin simp only [integral], rw ← simple_func.bintegral_smul _ f.integrable, apply simple_func.bintegral_congr (r • f).integrable, { exact integrable.smul _ f.integrable }, { apply smul_to_simple_func } end lemma norm_integral_le_norm (f : α →₁ₛ β) : ∥ integral f ∥ ≤ ∥f∥ := begin rw [integral, norm_eq_bintegral], exact f.to_simple_func.norm_bintegral_le_bintegral_norm f.integrable end /-- The Bochner integral over simple functions in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ₛ β) →L[ℝ] β := linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩ 1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul) local notation `Integral` := @integral_clm α _ β _ _ _ _ _ open continuous_linear_map lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (zero_le_one) _ section pos_part lemma pos_part_to_simple_func (f : α →₁ₛ ℝ) : ∀ₘ a, f.pos_part.to_simple_func a = f.to_simple_func.pos_part a := begin have eq : ∀ a, f.to_simple_func.pos_part a = max (f.to_simple_func a) 0 := λa, rfl, have ae_eq : ∀ₘ a, f.pos_part.to_simple_func a = max (f.to_simple_func a) 0, { filter_upwards [to_simple_func_eq_to_fun f.pos_part, pos_part_to_fun (f : α →₁ ℝ), to_simple_func_eq_to_fun f], simp only [mem_set_of_eq], assume a h₁ h₂ h₃, rw [h₁, coe_pos_part, h₂, ← h₃] }, filter_upwards [ae_eq], simp only [mem_set_of_eq], assume a h, rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ ℝ) : ∀ₘ a, f.neg_part.to_simple_func a = f.to_simple_func.neg_part a := begin rw [simple_func.neg_part, measure_theory.simple_func.neg_part], filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f], simp only [mem_set_of_eq], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ ℝ) : f.integral = ∥f.pos_part∥ - ∥f.neg_part∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : ∀ₘ a, f.to_simple_func.pos_part a = (f.pos_part).to_simple_func.map norm a, { filter_upwards [pos_part_to_simple_func f], simp only [mem_set_of_eq], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₂ : ∀ₘ a, f.to_simple_func.neg_part a = (f.neg_part).to_simple_func.map norm a, { filter_upwards [neg_part_to_simple_func f], simp only [mem_set_of_eq], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq : ∀ₘ a, f.to_simple_func.pos_part a - f.to_simple_func.neg_part a = (f.pos_part).to_simple_func.map norm a - (f.neg_part).to_simple_func.map norm a, { filter_upwards [ae_eq₁, ae_eq₂], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_bintegral, norm_eq_bintegral, ← simple_func.bintegral_sub], { show f.to_simple_func.bintegral = ((f.pos_part.to_simple_func).map norm - f.neg_part.to_simple_func.map norm).bintegral, apply simple_func.bintegral_congr f.integrable, { show integrable (f.pos_part.to_simple_func.map norm - f.neg_part.to_simple_func.map norm), refine integrable_of_ae_eq _ _, { exact (f.to_simple_func.pos_part - f.to_simple_func.neg_part) }, { exact (integrable.max_zero f.integrable).sub f.to_simple_func.pos_part.measurable f.to_simple_func.neg_part.measurable (integrable.max_zero f.integrable.neg) }, exact ae_eq }, filter_upwards [ae_eq₁, ae_eq₂], simp only [mem_set_of_eq], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := f.to_simple_func.pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { refine integrable_of_ae_eq (integrable.max_zero f.integrable) ae_eq₁ }, { refine integrable_of_ae_eq (integrable.max_zero f.integrable.neg) ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func variables [normed_space ℝ β] [normed_space ℝ γ] [complete_space β] section integration_in_l1 local notation `to_l1` := coe_to_l1 α β ℝ local attribute [instance] simple_func.normed_group simple_func.normed_space open continuous_linear_map /-- The Bochner integral in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ β) →L[ℝ] β := integral_clm.extend to_l1 simple_func.dense_range simple_func.uniform_inducing /-- The Bochner integral in l1 space -/ def integral (f : α →₁ β) : β := (integral_clm).to_fun f lemma integral_eq (f : α →₁ β) : integral f = (integral_clm).to_fun f := rfl @[norm_cast] lemma simple_func.integral_eq_integral (f : α →₁ₛ β) : integral (f : α →₁ β) = f.integral := uniformly_extend_of_ind simple_func.uniform_inducing simple_func.dense_range simple_func.integral_clm.uniform_continuous _ variables (α β) @[simp] lemma integral_zero : integral (0 : α →₁ β) = 0 := map_zero integral_clm variables {α β} lemma integral_add (f g : α →₁ β) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁ β) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁ β) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (r : ℝ) (f : α →₁ β) : integral (r • f) = r • integral f := map_smul r integral_clm f local notation `Integral` := @integral_clm α _ β _ _ _ _ _ _ local notation `sIntegral` := @simple_func.integral_clm α _ β _ _ _ _ _ lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := calc ∥Integral∥ ≤ (1 : nnreal) * ∥sIntegral∥ : op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl} ... = ∥sIntegral∥ : one_mul _ ... ≤ 1 : norm_Integral_le_one lemma norm_integral_le (f : α →₁ β) : ∥integral f∥ ≤ ∥f∥ := calc ∥integral f∥ = ∥Integral f∥ : rfl ... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _ ... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _ ... = ∥f∥ : one_mul _ section pos_part lemma integral_eq_norm_pos_part_sub (f : α →₁ ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ ℝ) → (α →₁ ℝ)) (λ f : α →₁ ℝ, integral f = ∥pos_part f∥ - ∥neg_part f∥) l1.simple_func.dense_range (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp l1.continuous_pos_part) (continuous_norm.comp l1.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, rw [← simple_func.norm_eq, ← simple_func.norm_eq], exact simple_func.integral_eq_norm_pos_part_sub _} end end pos_part end integration_in_l1 end l1 variables [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] [measurable_space β] [borel_space β] [normed_group γ] [second_countable_topology γ] [normed_space ℝ γ] [complete_space γ] [measurable_space γ] [borel_space γ] /-- The Bochner integral -/ def integral (f : α → β) : β := if hf : measurable f ∧ integrable f then (l1.of_fun f hf.1 hf.2).integral else 0 notation `∫` binders `, ` r:(scoped f, integral f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → β} lemma integral_eq (f : α → β) (h₁ : measurable f) (h₂ : integrable f) : (∫ a, f a) = (l1.of_fun f h₁ h₂).integral := dif_pos ⟨h₁, h₂⟩ lemma integral_undef (h : ¬ (measurable f ∧ integrable f)) : (∫ a, f a) = 0 := dif_neg h lemma integral_non_integrable (h : ¬ integrable f) : (∫ a, f a) = 0 := integral_undef $ not_and_of_not_right _ h lemma integral_non_measurable (h : ¬ measurable f) : (∫ a, f a) = 0 := integral_undef $ not_and_of_not_left _ h variables (α β) @[simp] lemma integral_zero : (∫ a : α, (0:β)) = 0 := by rw [integral_eq, l1.of_fun_zero, l1.integral_zero] variables {α β} lemma integral_add (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫ a, f a + g a) = (∫ a, f a) + (∫ a, g a) := by rw [integral_eq, integral_eq f hfm hfi, integral_eq g hgm hgi, l1.of_fun_add, l1.integral_add] lemma integral_neg (f : α → β) : (∫ a, -f a) = - (∫ a, f a) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, integral_eq (λa, - f a) hf.1.neg hf.2.neg, l1.of_fun_neg, l1.integral_neg] }, { have hf' : ¬(measurable (λa, -f a) ∧ integrable (λa, -f a)), { rwa [measurable_neg_iff, integrable_neg_iff] }, rw [integral_undef hf, integral_undef hf', neg_zero] } end lemma integral_sub (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫ a, f a - g a) = (∫ a, f a) - (∫ a, g a) := by { rw [sub_eq_add_neg, ← integral_neg], exact integral_add hfm hfi hgm.neg hgi.neg } lemma integral_smul (r : ℝ) (f : α → β) : (∫ a, r • (f a)) = r • (∫ a, f a) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, integral_eq (λa, r • (f a)), l1.of_fun_smul, l1.integral_smul] }, { by_cases hr : r = 0, { simp only [hr, measure_theory.integral_zero, zero_smul] }, have hf' : ¬(measurable (λa, r • f a) ∧ integrable (λa, r • f a)), { rwa [measurable_const_smul_iff hr, integrable_smul_iff hr f]; apply_instance }, rw [integral_undef hf, integral_undef hf', smul_zero] } end lemma integral_mul_left (r : ℝ) (f : α → ℝ) : (∫ a, r * (f a)) = r * (∫ a, f a) := integral_smul r f lemma integral_mul_right (r : ℝ) (f : α → ℝ) : (∫ a, (f a) * r) = (∫ a, f a) * r := by { simp only [mul_comm], exact integral_mul_left r f } lemma integral_div (r : ℝ) (f : α → ℝ) : (∫ a, (f a) / r) = (∫ a, f a) / r := integral_mul_right r⁻¹ f lemma integral_congr_ae (hfm : measurable f) (hgm : measurable g) (h : ∀ₘ a, f a = g a) : (∫ a, f a) = (∫ a, g a) := begin by_cases hfi : integrable f, { have hgi : integrable g := integrable_of_ae_eq hfi h, rw [integral_eq f hfm hfi, integral_eq g hgm hgi, (l1.of_fun_eq_of_fun f g hfm hfi hgm hgi).2 h] }, { have hgi : ¬ integrable g, { rw integrable_congr_ae h at hfi, exact hfi }, rw [integral_non_integrable hfi, integral_non_integrable hgi] }, end lemma norm_integral_le_lintegral_norm (f : α → β) : ∥(∫ a, f a)∥ ≤ ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, ← l1.norm_of_fun_eq_lintegral_norm f hf.1 hf.2], exact l1.norm_integral_le _ }, { rw [integral_undef hf, _root_.norm_zero], exact to_real_nonneg } end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} (bound : α → ℝ) (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫ a, F n a) at_top (𝓝 $ (∫ a, f a)) := begin /- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/ rw tendsto_iff_norm_tendsto_zero, /- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/ have lintegral_norm_tendsto_zero : tendsto (λn, ennreal.to_real $ ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0) := (tendsto_to_real (zero_ne_top)).comp (tendsto_lintegral_norm_of_dominated_convergence F_measurable f_measurable bound_integrable h_bound h_lim), -- Use the sandwich theorem refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero, -- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n` { assume n, have h₁ : integrable (F n) := integrable_of_integrable_bound bound_integrable (h_bound _), have h₂ : integrable f := integrable_of_dominated_convergence bound_integrable h_bound h_lim, rw ← integral_sub (F_measurable _) h₁ f_measurable h₂, exact norm_integral_le_lintegral_norm _ } end /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → β} {f : α → β} (bound : α → ℝ) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (f_measurable : measurable f) (h_bound : ∀ᶠ n in l, ∀ₘ a, ∥F n a∥ ≤ bound a) (bound_integrable : integrable bound) (h_lim : ∀ₘ a, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫ a, F n a) l (𝓝 $ (∫ a, f a)) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { assumption }, { assumption }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { filter_upwards [h_lim], simp only [mem_set_of_eq], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ lemma integral_eq_lintegral_max_sub_lintegral_min {f : α → ℝ} (hfm : measurable f) (hfi : integrable f) : (∫ a, f a) = ennreal.to_real (∫⁻ a, ennreal.of_real $ max (f a) 0) - ennreal.to_real (∫⁻ a, ennreal.of_real $ - min (f a) 0) := let f₁ : α →₁ ℝ := l1.of_fun f hfm hfi in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, ennreal.of_real $ max (f a) 0) = ∥l1.pos_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.pos_part_to_fun f₁, l1.to_fun_of_fun f hfm hfi], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], exact le_max_right _ _ end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, ennreal.of_real $ -min (f a) 0) = ∥l1.neg_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.neg_part_to_fun_eq_min f₁, l1.to_fun_of_fun f hfm hfi], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], rw [min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero], exact le_max_right _ _ end, begin rw [eq₁, eq₂, integral, dif_pos], exact l1.integral_eq_norm_pos_part_sub _, { exact ⟨hfm, hfi⟩ } end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : ∀ₘ a, 0 ≤ f a) (hfm : measurable f) : (∫ a, f a) = ennreal.to_real (∫⁻ a, ennreal.of_real $ f a) := begin by_cases hfi : integrable f, { rw integral_eq_lintegral_max_sub_lintegral_min hfm hfi, have h_min : (∫⁻ a, ennreal.of_real (-min (f a) 0)) = 0, { rw lintegral_eq_zero_iff, { filter_upwards [hf], simp only [mem_set_of_eq], assume a h, simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] }, { refine measurable_of_real.comp ((measurable.neg measurable_id).comp $ measurable.min hfm measurable_const) } }, have h_max : (∫⁻ a, ennreal.of_real (max (f a) 0)) = (∫⁻ a, ennreal.of_real $ f a), { apply lintegral_congr_ae, filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rw max_eq_left h }, rw [h_min, h_max, zero_to_real, _root_.sub_zero] }, { rw integral_non_integrable hfi, rw [integrable_iff_norm, lt_top_iff_ne_top, ne.def, not_not] at hfi, have : (∫⁻ (a : α), ennreal.of_real (f a)) = (∫⁻ a, ennreal.of_real ∥f a∥), { apply lintegral_congr_ae, filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : ∀ₘ a, 0 ≤ f a) : 0 ≤ (∫ a, f a) := begin by_cases hfm : measurable f, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_measurable hfm } end lemma integral_nonpos_of_nonpos_ae {f : α → ℝ} (hf : ∀ₘ a, f a ≤ 0) : (∫ a, f a) ≤ 0 := begin have hf : ∀ₘ a, 0 ≤ (-f) a, { filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rwa [pi.neg_apply, neg_nonneg] }, have : 0 ≤ (∫ a, -f a) := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_le_integral_ae {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) (h : ∀ₘ a, f a ≤ g a) : (∫ a, f a) ≤ (∫ a, g a) := le_of_sub_nonneg begin rw ← integral_sub hgm hgi hfm hfi, apply integral_nonneg_of_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a, exact sub_nonneg_of_le end lemma integral_le_integral {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) (h : ∀ a, f a ≤ g a) : (∫ a, f a) ≤ (∫ a, g a) := integral_le_integral_ae hfm hfi hgm hgi $ univ_mem_sets' h lemma norm_integral_le_integral_norm (f : α → β) : ∥(∫ a, f a)∥ ≤ ∫ a, ∥f a∥ := have le_ae : ∀ₘ (a : α), 0 ≤ ∥f a∥ := by filter_upwards [] λa, norm_nonneg _, classical.by_cases ( λh : measurable f, calc ∥(∫ a, f a)∥ ≤ ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) : norm_integral_le_lintegral_norm _ ... = ∫ a, ∥f a∥ : (integral_eq_lintegral_of_nonneg_ae le_ae $ measurable.norm h).symm ) ( λh : ¬measurable f, begin rw [integral_non_measurable h, _root_.norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → β} (hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i)) : (∫ a, s.sum (λ i, f i a)) = s.sum (λ i, ∫ a, f i a) := begin refine finset.induction_on s _ _, { simp only [integral_zero, finset.sum_empty] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], rw [integral_add (hfm _) (hfi _) (s.measurable_sum hfm) (integrable_finset_sum s hfm hfi), ih] } end end properties mk_simp_attribute integral_simps "Simp set for integral rules." attribute [integral_simps] integral_neg integral_smul l1.integral_add l1.integral_sub l1.integral_smul l1.integral_neg attribute [irreducible] integral l1.integral end measure_theory
9fbb699235faf038923dfd10e5f13abda9efcb8a
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/ring_theory/perfection.lean
b88a70e41466f3164553d58fbf7fa6aada6309f3
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,479
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 algebra.char_p import algebra.ring.pi import analysis.special_functions.pow import field_theory.perfect_closure import ring_theory.localization import ring_theory.subring import ring_theory.valuation.integers /-! # Ring Perfection and Tilt In this file we define the perfection of a ring of characteristic p, and the tilt of a field given a valuation to `ℝ≥0`. ## TODO Define the valuation on the tilt, and define a characteristic predicate for the tilt. -/ universes u₁ u₂ u₃ open_locale nnreal /-- The perfection of a monoid `M`, defined to be the projective limit of `M` using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as `{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/ def monoid.perfection (M : Type u₁) [comm_monoid M] (p : ℕ) : submonoid (ℕ → M) := { carrier := { f | ∀ n, f (n + 1) ^ p = f n }, one_mem' := λ n, one_pow _, mul_mem' := λ f g hf hg n, (mul_pow _ _ _).trans $ congr_arg2 _ (hf n) (hg n) } /-- The perfection of a semiring `R` with characteristic `p`, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def semiring.perfection (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] : subsemiring (ℕ → R) := { zero_mem' := λ n, zero_pow $ hp.pos, add_mem' := λ f g hf hg n, (frobenius_add R p _ _).trans $ congr_arg2 _ (hf n) (hg n), .. monoid.perfection R p } /-- The perfection of a ring `R` with characteristic `p`, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def ring.perfection (R : Type u₁) [comm_ring R] (p : ℕ) [hp : fact p.prime] [char_p R p] : subring (ℕ → R) := { neg_mem' := λ f hf n, (frobenius_neg R p _).trans $ congr_arg _ (hf n), .. semiring.perfection R p } namespace ring.perfection variables (R : Type u₁) [comm_ring R] (p : ℕ) [hp : fact p.prime] [char_p R p] include hp /-- The `n`-th coefficient of an element of the perfection. -/ def coeff (n : ℕ) : ring.perfection R p →+* R := { to_fun := λ f, f.1 n, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[ext] lemma ext {f g : ring.perfection R p} (h : ∀ n, coeff R p n f = coeff R p n g) : f = g := subtype.eq $ funext h variables (R p) /-- The `p`-th root of an element of the perfection. -/ def pth_root : ring.perfection R p →+* ring.perfection R p := { to_fun := λ f, ⟨λ n, coeff R p (n + 1) f, λ n, f.2 _⟩, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} lemma coeff_pth_root (f : ring.perfection R p) (n : ℕ) : coeff R p n (pth_root R p f) = coeff R p (n + 1) f := rfl lemma coeff_pow_p (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (f ^ p) = coeff R p n f := by { rw ring_hom.map_pow, exact f.2 n } lemma coeff_frobenius (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (frobenius _ p f) = coeff R p n f := by convert coeff_pow_p f n lemma pth_root_frobenius : (pth_root R p).comp (frobenius _ p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, coeff_pth_root, coeff_frobenius] lemma frobenius_pth_root : (frobenius _ p).comp (pth_root R p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, ring_hom.map_frobenius, coeff_pth_root, ← ring_hom.map_frobenius, coeff_frobenius] lemma coeff_add_ne_zero {f : ring.perfection R p} {n : ℕ} (hfn : coeff R p n f ≠ 0) (k : ℕ) : coeff R p (n + k) f ≠ 0 := nat.rec_on k hfn $ λ k ih h, ih $ by erw [← coeff_pow_p, ring_hom.map_pow, h, zero_pow hp.pos] lemma coeff_ne_zero_of_le {f : ring.perfection R p} {m n : ℕ} (hfm : coeff R p m f ≠ 0) (hmn : m ≤ n) : coeff R p n f ≠ 0 := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in hk.symm ▸ coeff_add_ne_zero hfm k end ring.perfection section perfectoid variables (K : Type u₁) [field K] (v : valuation K ℝ≥0) variables (O : Type u₂) [comm_ring O] [algebra O K] (hv : v.integers O) variables (p : ℕ) include hv /-- `O/(p)` for `O`, ring of integers of `K`. -/ @[nolint unused_arguments has_inhabited_instance] def mod_p := (ideal.span {p} : ideal O).quotient variables [hp : fact p.prime] [hvp : fact (v p ≠ 1)] namespace mod_p instance : comm_ring (mod_p K v O hv p) := ideal.quotient.comm_ring _ include hp hvp instance : char_p (mod_p K v O hv p) p := char_p.quotient O p $ mt hv.one_of_is_unit $ ((algebra_map O K).map_nat_cast p).symm ▸ hvp instance : nontrivial (mod_p K v O hv p) := char_p.nontrivial_of_char_ne_one hp.ne_one section classical local attribute [instance] classical.dec omit hp hvp /-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`, a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/ noncomputable def pre_val (x : mod_p K v O hv p) : ℝ≥0 := if x = 0 then 0 else v (algebra_map O K x.out') variables {K v O hv p} lemma pre_val_mk {x : O} (hx : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0) : pre_val K v O hv p (ideal.quotient.mk _ x) = v (algebra_map O K x) := begin obtain ⟨r, hr⟩ := ideal.mem_span_singleton'.1 (ideal.quotient.eq.1 $ quotient.sound' $ @quotient.mk_out' O (ideal.span {p} : ideal O).quotient_rel x), refine (if_neg hx).trans (v.map_eq_of_sub_lt $ lt_of_not_ge' _), erw [← ring_hom.map_sub, ← hr, hv.le_iff_dvd], exact λ hprx, hx (ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ dvd_of_mul_left_dvd hprx), end lemma pre_val_zero : pre_val K v O hv p 0 = 0 := if_pos rfl lemma pre_val_mul {x y : mod_p K v O hv p} (hxy0 : x * y ≠ 0) : pre_val K v O hv p (x * y) = pre_val K v O hv p x * pre_val K v O hv p y := begin have hx0 : x ≠ 0 := mt (by { rintro rfl, rw zero_mul }) hxy0, have hy0 : y ≠ 0 := mt (by { rintro rfl, rw mul_zero }) hxy0, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_mul at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_mul, v.map_mul] end lemma pre_val_add (x y : mod_p K v O hv p) : pre_val K v O hv p (x + y) ≤ max (pre_val K v O hv p x) (pre_val K v O hv p y) := begin by_cases hx0 : x = 0, { rw [hx0, zero_add], exact le_max_right _ _ }, by_cases hy0 : y = 0, { rw [hy0, add_zero], exact le_max_left _ _ }, by_cases hxy0 : x + y = 0, { rw [hxy0, pre_val_zero], exact zero_le _ }, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_add at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_add], exact v.map_add _ _ end lemma v_p_lt_pre_val {x : mod_p K v O hv p} : v p < pre_val K v O hv p x ↔ x ≠ 0 := begin refine ⟨λ h hx, by { rw [hx, pre_val_zero] at h, exact not_lt_zero' h }, λ h, lt_of_not_ge' $ λ hp, h _⟩, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, rw [pre_val_mk h, ← (algebra_map O K).map_nat_cast p, hv.le_iff_dvd] at hp, rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton], exact hp end lemma pre_val_eq_zero {x : mod_p K v O hv p} : pre_val K v O hv p x = 0 ↔ x = 0 := ⟨λ hvx, classical.by_contradiction $ λ hx0 : x ≠ 0, by { rw [← v_p_lt_pre_val, hvx] at hx0, exact not_lt_zero' hx0 }, λ hx, hx.symm ▸ pre_val_zero⟩ variables (hv hvp) lemma v_p_lt_val {x : O} : v p < v (algebra_map O K x) ↔ (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := by rw [lt_iff_not_ge', not_iff_not, ← (algebra_map O K).map_nat_cast p, hv.le_iff_dvd, ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton] open nnreal variables {hv} [hvp] include hp lemma mul_ne_zero_of_pow_p_ne_zero {x y : mod_p K v O hv p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) : x * y ≠ 0 := begin obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, have h1p : (0 : ℝ) < 1 / p := one_div_pos.2 (nat.cast_pos.2 hp.pos), rw ← ring_hom.map_mul, rw ← ring_hom.map_pow at hx hy, rw ← v_p_lt_val hv at hx hy ⊢, rw [ring_hom.map_pow, v.map_pow, ← rpow_lt_rpow_iff h1p, ← rpow_nat_cast, ← rpow_mul, mul_one_div_cancel (nat.cast_ne_zero.2 hp.ne_zero : (p : ℝ) ≠ 0), rpow_one] at hx hy, rw [ring_hom.map_mul, v.map_mul], refine lt_of_le_of_lt _ (mul_lt_mul'''' hx hy), by_cases hvp : v p = 0, { rw hvp, exact zero_le _ }, replace hvp := zero_lt_iff.2 hvp, conv_lhs { rw ← rpow_one (v p) }, rw ← rpow_add (ne_of_gt hvp), refine rpow_le_rpow_of_exponent_ge hvp ((algebra_map O K).map_nat_cast p ▸ hv.2 _) _, rw [← add_div, div_le_one (nat.cast_pos.2 hp.pos : 0 < (p : ℝ))], exact_mod_cast hp.two_le end end classical end mod_p include hp hvp /-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/ @[nolint has_inhabited_instance] def pre_tilt := ring.perfection (mod_p K v O hv p) p namespace pre_tilt section classical local attribute [instance] classical.dec open ring.perfection /-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val_aux (f : pre_tilt K v O hv p) : ℝ≥0 := if h : ∃ n, coeff _ _ n f ≠ 0 then mod_p.pre_val K v O hv p (coeff _ _ (nat.find h) f) ^ (p ^ nat.find h) else 0 variables {K v O hv p} lemma coeff_nat_find_add_ne_zero {f : pre_tilt K v O hv p} {h : ∃ n, coeff _ _ n f ≠ 0} (k : ℕ) : coeff _ _ (nat.find h + k) f ≠ 0 := coeff_add_ne_zero (nat.find_spec h) k lemma val_aux_eq {f : pre_tilt K v O hv p} {n : ℕ} (hfn : coeff _ _ n f ≠ 0) : val_aux K v O hv p f = mod_p.pre_val K v O hv p (coeff _ _ n f) ^ (p ^ n) := begin have h : ∃ n, coeff _ _ n f ≠ 0 := ⟨n, hfn⟩, rw [val_aux, dif_pos h], obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le (nat.find_min' h hfn), induction k with k ih, { refl }, obtain ⟨x, hx⟩ := ideal.quotient.mk_surjective (coeff _ _ (nat.find h + k + 1) f), have h1 : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := hx.symm ▸ hfn, have h2 : (ideal.quotient.mk _ (x ^ p) : mod_p K v O hv p) ≠ 0, by { erw [ring_hom.map_pow, hx, ← ring_hom.map_pow, coeff_pow_p], exact coeff_nat_find_add_ne_zero k }, erw [ih (coeff_nat_find_add_ne_zero k), ← hx, ← coeff_pow_p, ring_hom.map_pow, ← hx, ← ring_hom.map_pow, mod_p.pre_val_mk h1, mod_p.pre_val_mk h2, ring_hom.map_pow, v.map_pow, ← pow_mul, pow_succ], refl end lemma val_aux_zero : val_aux K v O hv p 0 = 0 := dif_neg $ λ ⟨n, hn⟩, hn rfl lemma val_aux_one : val_aux K v O hv p 1 = 1 := (val_aux_eq $ by exact one_ne_zero).trans $ by { rw [pow_zero, pow_one, ring_hom.map_one, ← (ideal.quotient.mk _).map_one, mod_p.pre_val_mk, ring_hom.map_one, v.map_one], exact @one_ne_zero (mod_p K v O hv p) _ _ } lemma val_aux_mul (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f * g) = val_aux K v O hv p f * val_aux K v O hv p g := begin by_cases hf : f = 0, { rw [hf, zero_mul, val_aux_zero, zero_mul] }, by_cases hg : g = 0, { rw [hg, mul_zero, val_aux_zero, mul_zero] }, replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ ring.perfection.ext h), replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ ring.perfection.ext h), obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, replace hm := coeff_ne_zero_of_le hm (le_max_left m n), replace hn := coeff_ne_zero_of_le hn (le_max_right m n), have hfg : coeff _ _ (max m n + 1) (f * g) ≠ 0, { rw ring_hom.map_mul, refine mod_p.mul_ne_zero_of_pow_p_ne_zero _ _; rw [← ring_hom.map_pow, coeff_pow_p]; assumption }, rw [val_aux_eq (coeff_add_ne_zero hm 1), val_aux_eq (coeff_add_ne_zero hn 1), val_aux_eq hfg], rw ring_hom.map_mul at hfg ⊢, rw [mod_p.pre_val_mul hfg, mul_pow] end lemma val_aux_add (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f + g) ≤ max (val_aux K v O hv p f) (val_aux K v O hv p g) := begin by_cases hf : f = 0, { rw [hf, zero_add, val_aux_zero, max_eq_right], exact zero_le _ }, by_cases hg : g = 0, { rw [hg, add_zero, val_aux_zero, max_eq_left], exact zero_le _ }, by_cases hfg : f + g = 0, { rw [hfg, val_aux_zero], exact zero_le _ }, replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ ring.perfection.ext h), replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ ring.perfection.ext h), replace hfg : ∃ n, coeff _ _ n (f + g) ≠ 0 := not_forall.1 (λ h, hfg $ ring.perfection.ext h), obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, obtain ⟨k, hk⟩ := hfg, replace hm := coeff_ne_zero_of_le hm (le_trans (le_max_left m n) (le_max_left _ k)), replace hn := coeff_ne_zero_of_le hn (le_trans (le_max_right m n) (le_max_left _ k)), replace hk := coeff_ne_zero_of_le hk (le_max_right (max m n) k), rw [val_aux_eq hm, val_aux_eq hn, val_aux_eq hk, ring_hom.map_add], cases le_max_iff.1 (mod_p.pre_val_add (coeff _ _ (max (max m n) k) f) (coeff _ _ (max (max m n) k) g)) with h h, { exact le_max_left_of_le (canonically_ordered_semiring.pow_le_pow_of_le_left h _) }, { exact le_max_right_of_le (canonically_ordered_semiring.pow_le_pow_of_le_left h _) } end variables (K v O hv p) /-- The valuation `Perfection(O/(p)) → ℝ≥0`. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val : valuation (pre_tilt K v O hv p) ℝ≥0 := { to_fun := val_aux K v O hv p, map_one' := val_aux_one, map_mul' := val_aux_mul, map_zero' := val_aux_zero, map_add' := val_aux_add } variables {K v O hv p} lemma map_eq_zero {f : pre_tilt K v O hv p} : val K v O hv p f = 0 ↔ f = 0 := begin by_cases hf0 : f = 0, { rw hf0, exact iff_of_true (valuation.map_zero _) rfl }, obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf0 $ ring.perfection.ext h), show val_aux K v O hv p f = 0 ↔ f = 0, refine iff_of_false (λ hvf, hn _) hf0, rw val_aux_eq hn at hvf, replace hvf := nnreal.pow_eq_zero hvf, rwa mod_p.pre_val_eq_zero at hvf end end classical instance : integral_domain (pre_tilt K v O hv p) := { exists_pair_ne := (char_p.nontrivial_of_char_ne_one hp.ne_one).1, eq_zero_or_eq_zero_of_mul_eq_zero := λ f g hfg, by { simp_rw ← map_eq_zero at hfg ⊢, contrapose! hfg, rw valuation.map_mul, exact nnreal.mul_ne_zero' hfg.1 hfg.2 }, .. (infer_instance : comm_ring (pre_tilt K v O hv p)) } end pre_tilt /-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in [scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`, this is implemented as the fraction field of the perfection of `O/(p)`. -/ @[nolint has_inhabited_instance] def tilt := fraction_ring (pre_tilt K v O hv p) namespace tilt noncomputable instance : field (tilt K v O hv p) := fraction_ring.field end tilt end perfectoid
bda2a429acdcfffbb6b7d9a9c1ca3696fd5c2719
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/linear_algebra/determinant.lean
a7f2305f3b726b16ddb6011e9d62051d41412a30
[ "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
15,477
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Tim Baanen -/ import data.matrix.pequiv import data.fintype.card import group_theory.perm.sign import algebra.algebra.basic import tactic.ring import linear_algebra.alternating import linear_algebra.pi /-! # Determinant of a matrix This file defines the determinant of a matrix, `matrix.det`, and its essential properties. ## Main definitions - `matrix.det`: the determinant of a square matrix, as a sum over permutations - `matrix.det_row_multilinear`: the determinant, as an `alternating_map` in the rows of the matrix ## Main results - `det_mul`: the determinant of `A ⬝ B` is the product of determinants - `det_zero_of_row_eq`: the determinant is zero if there is a repeated row - `det_block_diagonal`: the determinant of a block diagonal matrix is a product of the blocks' determinants ## Implementation notes It is possible to configure `simp` to compute determinants. See the file `test/matrix.lean` for some examples. -/ universes u v w z open equiv equiv.perm finset function namespace matrix open_locale matrix big_operators variables {m n : Type u} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m] variables {R : Type v} [comm_ring R] local notation `ε` σ:max := ((sign σ : ℤ ) : R) /-- `det` is an `alternating_map` in the rows of the matrix. -/ def det_row_multilinear : alternating_map R (n → R) R n := ((multilinear_map.mk_pi_algebra R n R).comp_linear_map (linear_map.proj)).alternatization /-- The determinant of a matrix given by the Leibniz formula. -/ abbreviation det (M : matrix n n R) : R := det_row_multilinear M lemma det_apply (M : matrix n n R) : M.det = ∑ σ : perm n, (σ.sign : ℤ) • ∏ i, M (σ i) i := multilinear_map.alternatization_apply _ M -- This is what the old definition was. We use it to avoid having to change the old proofs below lemma det_apply' (M : matrix n n R) : M.det = ∑ σ : perm n, ε σ * ∏ i, M (σ i) i := begin rw det_apply, have : ∀ (r : R) (z : ℤ), z • r = (z : R) * r := λ r z, by rw [←gsmul_eq_smul, ←smul_eq_mul, ←gsmul_eq_smul_cast], simp only [this], end @[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i := begin rw det_apply', refine (finset.sum_eq_single 1 _ _).trans _, { intros σ h1 h2, cases not_forall.1 (mt equiv.ext h2) with x h3, convert mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := (det_row_multilinear : alternating_map R (n → R) R n).map_zero @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 := begin have perm_eq : (univ : finset (perm n)) = {1} := univ_eq_singleton_of_card_one (1 : perm n) (by simp [card_univ, fintype.card_perm, h]), simp [det_apply, card_eq_zero.mp h, perm_eq], end /-- If `n` has only one element, the determinant of an `n` by `n` matrix is just that element. Although `unique` implies `decidable_eq` and `fintype`, the instances might not be syntactically equal. Thus, we need to fill in the args explicitly. -/ @[simp] lemma det_unique {n : Type*} [unique n] [decidable_eq n] [fintype n] (A : matrix n n R) : det A = A (default n) (default n) := by simp [det_apply, univ_unique] lemma det_eq_elem_of_card_eq_one {A : matrix n n R} (h : fintype.card n = 1) (k : n) : det A = A k k := begin have h1 : (univ : finset (perm n)) = {1}, { apply univ_eq_singleton_of_card_one (1 : perm n), simp [card_univ, fintype.card_perm, h] }, have h2 := univ_eq_singleton_of_card_one k h, simp [det_apply, h1, h2], end lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) : ∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 := begin obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j, { rw [← fintype.injective_iff_bijective, injective] at H, push_neg at H, exact H }, exact sum_involution (λ σ _, σ * swap i j) (λ σ _, have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x), from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _) (by simp [apply_swap_eq_self hpij]) (λ _ _ _ _ h, (swap i j).injective h) (λ b _, ⟨swap i j b, mem_univ _, by simp⟩), by simp [this, sign_swap hij, prod_mul_distrib]) (λ σ _ _, (not_congr mul_swap_eq_iff).mpr hij) (λ _ _, mem_univ _) (λ σ _, mul_swap_involutive i j σ) end @[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N := calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) : by simp only [det_apply', mul_apply, prod_univ_sum, mul_sum, fintype.pi_finset_univ]; rw [finset.sum_comm] ... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) : eq.symm $ sum_subset (filter_subset _ _) (λ f _ hbij, det_mul_aux $ by simpa using hbij) ... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) : sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ h, by injection h) (λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩) ... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) : by simp [mul_sum, det_apply', mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) : sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _) (λ τ _, have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j, by rw ← σ⁻¹.prod_comp; simp [mul_apply], have h : ε σ * ε (τ * σ⁻¹) = ε τ := calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) : by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp ... = ε τ : by simp, by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm]) (λ _ _ _ _, mul_right_cancel) (λ τ _, ⟨τ * σ, by simp⟩)) ... = det M * det N : by simp [det_apply', mul_assoc, mul_sum, mul_comm, mul_left_comm] instance : is_monoid_hom (det : matrix n n R → R) := { map_one := det_one, map_mul := det_mul } /-- Transposing a matrix preserves the determinant. -/ @[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det := begin rw [det_apply', det_apply'], apply sum_bij (λ σ _, σ⁻¹), { intros σ _, apply mem_univ }, { intros σ _, rw [sign_inv], congr' 1, apply prod_bij (λ i _, σ i), { intros i _, apply mem_univ }, { intros i _, simp }, { intros i j _ _ h, simp at h, assumption }, { intros i _, use σ⁻¹ i, finish } }, { intros σ σ' _ _ h, simp at h, assumption }, { intros σ _, use σ⁻¹, finish } end /-- Permuting the columns changes the sign of the determinant. -/ lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det := begin have : (σ.sign : ℤ) • M.det = (σ.sign * M.det : R), { rw [coe_coe, ←gsmul_eq_smul, ←smul_eq_mul, ←gsmul_eq_smul_cast] }, exact ((det_row_multilinear : alternating_map R (n → R) R n).map_perm M σ).trans this, end /-- The determinant of a permutation matrix equals its sign. -/ @[simp] lemma det_permutation (σ : perm n) : matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign := by rw [←matrix.mul_one (σ.to_pequiv.to_matrix : matrix n n R), pequiv.to_pequiv_mul_matrix, det_permute, det_one, mul_one] @[simp] lemma det_smul {A : matrix n n R} {c : R} : det (c • A) = c ^ fintype.card n * det A := calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul] ... = det (diagonal (λ _, c)) * det A : det_mul _ _ ... = c ^ fintype.card n * det A : by simp [card_univ] section hom_map variables {S : Type w} [comm_ring S] lemma ring_hom.map_det {M : matrix n n R} {f : R →+* S} : f M.det = matrix.det (f.map_matrix M) := by simp [matrix.det_apply', f.map_sum, f.map_prod] lemma alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] {M : matrix n n S} {f : S →ₐ[R] T} : f M.det = matrix.det ((f : S →+* T).map_matrix M) := by rw [← alg_hom.coe_to_ring_hom, ring_hom.map_det] end hom_map section det_zero /-! ### `det_zero` section Prove that a matrix with a repeated column has determinant equal to zero. -/ lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 := (det_row_multilinear : alternating_map R (n → R) R n).map_coord_zero i (funext h) lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : ∀ i, A i j = 0) : det A = 0 := by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, } variables {M : matrix n n R} {i j : n} /-- If a matrix has a repeated row, the determinant will be zero. -/ theorem det_zero_of_row_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 := (det_row_multilinear : alternating_map R (n → R) R n).map_eq_zero_of_eq M hij i_ne_j end det_zero lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) : det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) := (det_row_multilinear : alternating_map R (n → R) R n).map_add M j u v lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) : det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_add], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_row M j $ s • u) = s * det (update_row M j u) := (det_row_multilinear : alternating_map R (n → R) R n).map_smul M j s u lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_column M j $ s • u) = s * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_smul], simp [update_row_transpose, det_transpose] end @[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) : (block_diagonal M).det = ∏ k, (M k).det := begin -- Rewrite the determinants as a sum over permutations. simp_rw [det_apply'], -- The right hand side is a product of sums, rewrite it as a sum of products. rw finset.prod_sum, simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ], -- We claim that the only permutations contributing to the sum are those that -- preserve their second component. let preserving_snd : finset (equiv.perm (n × o)) := finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd), have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)}, σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd := λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩, rw ← finset.sum_subset (finset.subset_univ preserving_snd) _, -- And that these are in bijection with `o → equiv.perm m`. rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _, prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm, { intros σ _, rw mem_preserving_snd, rintros ⟨k, x⟩, simp }, { intros σ _, rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product, finset.prod_comm], simp [sign_prod_congr_left] }, { intros σ σ' _ _ eq, ext x hx k, simp only at eq, have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) = prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) := λ k x, by rw eq, simp only [prod_congr_left_apply, prod.mk.inj_iff] at this, exact (this k x).1 }, { intros σ hσ, rw mem_preserving_snd at hσ, have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd, { intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } }, have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k), { intros k x, ext; simp [hσ] }, have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k), { intros k x, conv_lhs { rw ← perm.apply_inv_self σ (x, k) }, ext; simp [hσ'] }, refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩, { intro x, simp [mk_apply_eq, mk_inv_apply_eq] }, { intro x, simp [mk_apply_eq, mk_inv_apply_eq] }, { apply finset.mem_univ }, { ext ⟨k, x⟩; simp [hσ] } }, { intros σ _ hσ, rw mem_preserving_snd at hσ, obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ, rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero], rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne], exact hkx } end /-- The determinant of a 2x2 block matrix with the lower-left block equal to zero is the product of the determinants of the diagonal blocks. For the generalization to any number of blocks, see `matrix.upper_block_triangular_det`. -/ lemma upper_two_block_triangular_det (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : (matrix.from_blocks A B 0 D).det = A.det * D.det := begin classical, simp_rw det_apply', convert (sum_subset (subset_univ ((sum_congr_hom m n).range : set (perm (m ⊕ n))).to_finset) _).symm, rw sum_mul_sum, simp_rw univ_product_univ, rw (sum_bij (λ (σ : perm m × perm n) _, equiv.sum_congr σ.fst σ.snd) _ _ _ _).symm, { intros σ₁₂ h, simp only [], erw [set.mem_to_finset, monoid_hom.mem_range], use σ₁₂, simp }, { simp only [forall_prop_of_true, prod.forall, mem_univ], intros σ₁ σ₂, rw fintype.prod_sum_type, simp_rw [equiv.sum_congr_apply, sum.map_inr, sum.map_inl, from_blocks_apply₁₁, from_blocks_apply₂₂], have hr : ∀ (a b c d : R), (a * b) * (c * d) = a * c * (b * d), { intros, ac_refl }, rw hr, congr, norm_cast, rw sign_sum_congr }, { intros σ₁ σ₂ h₁ h₂, dsimp only [], intro h, have h2 : ∀ x, perm.sum_congr σ₁.fst σ₁.snd x = perm.sum_congr σ₂.fst σ₂.snd x, { intro x, exact congr_fun (congr_arg to_fun h) x }, simp only [sum.map_inr, sum.map_inl, perm.sum_congr_apply, sum.forall] at h2, ext, { exact h2.left x }, { exact h2.right x }}, { intros σ hσ, erw [set.mem_to_finset, monoid_hom.mem_range] at hσ, obtain ⟨σ₁₂, hσ₁₂⟩ := hσ, use σ₁₂, rw ←hσ₁₂, simp }, { intros σ hσ hσn, have h1 : ¬ (∀ x, ∃ y, sum.inl y = σ (sum.inl x)), { by_contradiction, rw set.mem_to_finset at hσn, apply absurd (mem_sum_congr_hom_range_of_perm_maps_to_inl _) hσn, rintros x ⟨a, ha⟩, rw [←ha], exact h a }, obtain ⟨a, ha⟩ := not_forall.mp h1, cases hx : σ (sum.inl a) with a2 b, { have hn := (not_exists.mp ha) a2, exact absurd hx.symm hn }, { rw [finset.prod_eq_zero (finset.mem_univ (sum.inl a)), mul_zero], rw [hx, from_blocks_apply₂₁], refl }} end end matrix
768c3837d9e1f909c2e5aea35223fd5fa7a0ed51
d642a6b1261b2cbe691e53561ac777b924751b63
/src/order/filter/partial.lean
4d52f752a24156f3d3f8634c87bcd74049365778
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
8,470
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Extends `tendsto` to relations and partial functions. -/ import order.filter.basic import data.pfun universes u v w namespace filter variables {α : Type u} {β : Type v} {γ : Type w} /- Relations. -/ def rmap (r : rel α β) (f : filter α) : filter β := { sets := r.core ⁻¹' f.sets, univ_sets := by { simp [rel.core], apply univ_mem_sets }, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ rel.core_mono _ st, inter_sets := by { simp [set.preimage, rel.core_inter], exact λ s t, inter_mem_sets } } theorem rmap_sets (r : rel α β) (f : filter α) : (rmap r f).sets = r.core ⁻¹' f.sets := rfl @[simp] theorem mem_rmap (r : rel α β) (l : filter α) (s : set β) : s ∈ l.rmap r ↔ r.core s ∈ l := iff.refl _ @[simp] theorem rmap_rmap (r : rel α β) (s : rel β γ) (l : filter α) : rmap s (rmap r l) = rmap (r.comp s) l := filter_eq $ by simp [rmap_sets, set.preimage, rel.core_comp] @[simp] lemma rmap_compose (r : rel α β) (s : rel β γ) : rmap s ∘ rmap r = rmap (r.comp s) := funext $ rmap_rmap _ _ def rtendsto (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁.rmap r ≤ l₂ theorem rtendsto_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ ∀ s ∈ l₂, r.core s ∈ l₁ := iff.refl _ def rcomap (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.core s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (by rw rel.core_inter) (set.inter_subset_inter ha₂ hb₂)⟩ } theorem rcomap_sets (r : rel α β) (f : filter β) : (rcomap r f).sets = rel.image (λ s t, r.core s ⊆ t) f.sets := rfl @[simp] theorem rcomap_rcomap (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap r (rcomap s l) = rcomap (r.comp s) l := filter_eq $ begin ext t, simp [rcomap_sets, rel.image, rel.core_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.core_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.core s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap_compose (r : rel α β) (s : rel β γ) : rcomap r ∘ rcomap s = rcomap (r.comp s) := funext $ rcomap_rcomap _ _ theorem rtendsto_iff_le_comap (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ l₁ ≤ l₂.rcomap r := begin rw rtendsto_def, change (∀ (s : set β), s ∈ l₂.sets → rel.core r s ∈ l₁) ↔ l₁ ≤ rcomap r l₂, simp [filter.le_def, rcomap, rel.mem_image], split, intros h s t tl₂ h', { exact mem_sets_of_superset (h t tl₂) h' }, intros h t tl₂, apply h _ t tl₂ (set.subset.refl _), end -- Interestingly, there does not seem to be a way to express this relation using a forward map. -- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f` if -- and only if `s ∈ f'`. But the intersection of two sets satsifying the lhs may be empty. def rcomap' (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.preimage s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (@rel.preimage_inter _ _ r _ _) (set.inter_subset_inter ha₂ hb₂)⟩ } @[simp] lemma mem_rcomap' (r : rel α β) (l : filter β) (s : set α) : s ∈ l.rcomap' r ↔ ∃ t ∈ l, rel.preimage r t ⊆ s := iff.refl _ theorem rcomap'_sets (r : rel α β) (f : filter β) : (rcomap' r f).sets = rel.image (λ s t, r.preimage s ⊆ t) f.sets := rfl @[simp] theorem rcomap'_rcomap' (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap' r (rcomap' s l) = rcomap' (r.comp s) l := filter_eq $ begin ext t, simp [rcomap'_sets, rel.image, rel.preimage_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.preimage_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.preimage s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap'_compose (r : rel α β) (s : rel β γ) : rcomap' r ∘ rcomap' s = rcomap' (r.comp s) := funext $ rcomap'_rcomap' _ _ def rtendsto' (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' r theorem rtendsto'_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto' r l₁ l₂ ↔ ∀ s ∈ l₂, r.preimage s ∈ l₁ := begin unfold rtendsto', unfold rcomap', simp [le_def, rel.mem_image], split, { intros h s hs, apply (h _ _ hs (set.subset.refl _)) }, intros h s t ht h', apply mem_sets_of_superset (h t ht) h' end theorem tendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto_def, rel.core, set.preimage] } theorem tendsto_iff_rtendsto' (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto'_def, rel.preimage_def, set.preimage] } /- Partial functions. -/ def pmap (f : α →. β) (l : filter α) : filter β := filter.rmap f.graph' l @[simp] lemma mem_pmap (f : α →. β) (l : filter α) (s : set β) : s ∈ l.pmap f ↔ f.core s ∈ l := iff.refl _ def ptendsto (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁.pmap f ≤ l₂ theorem ptendsto_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f.core s ∈ l₁ := iff.refl _ theorem ptendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α →. β) : ptendsto f l₁ l₂ ↔ rtendsto f.graph' l₁ l₂ := iff.refl _ theorem pmap_res (l : filter α) (s : set α) (f : α → β) : pmap (pfun.res f s) l = map f (l ⊓ principal s) := filter_eq $ begin apply set.ext, intro t, simp [pfun.core_res], split, { intro h, constructor, split, { exact h }, constructor, split, { reflexivity }, simp [set.inter_distrib_right], apply set.inter_subset_left }, rintro ⟨t₁, h₁, t₂, h₂, h₃⟩, apply mem_sets_of_superset h₁, rw ← set.inter_subset, exact set.subset.trans (set.inter_subset_inter_right _ h₂) h₃ end theorem tendsto_iff_ptendsto (l₁ : filter α) (l₂ : filter β) (s : set α) (f : α → β) : tendsto f (l₁ ⊓ principal s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ := by simp only [tendsto, ptendsto, pmap_res] theorem tendsto_iff_ptendsto_univ (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ := by { rw ← tendsto_iff_ptendsto, simp [principal_univ] } def pcomap' (f : α →. β) (l : filter β) : filter α := filter.rcomap' f.graph' l def ptendsto' (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' f.graph' theorem ptendsto'_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto' f l₁ l₂ ↔ ∀ s ∈ l₂, f.preimage s ∈ l₁ := rtendsto'_def _ _ _ theorem ptendsto_of_ptendsto' {f : α →. β} {l₁ : filter α} {l₂ : filter β} : ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h s sl₂, exacts mem_sets_of_superset (h s sl₂) (pfun.preimage_subset_core _ _), end theorem ptendsto'_of_ptendsto {f : α →. β} {l₁ : filter α} {l₂ : filter β} (h : f.dom ∈ l₁) : ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h' s sl₂, rw pfun.preimage_eq, show pfun.core f s ∩ pfun.dom f ∈ l₁, exact inter_mem_sets (h' s sl₂) h end end filter
8c1de5e675a5f68a9b30349691d7e858c11ba541
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/sigma/default_auto.lean
05ff95251e892bf24093ab827068730294df92c8
[]
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
308
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.data.sigma.basic import Mathlib.Lean3Lib.init.data.sigma.lex namespace Mathlib end Mathlib
4db7b56eefd8540addf61dd407d6810f803bf1ad
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Match/MatchPatternAttr.lean
fb6044fb41a20cf6a8de2fe7fb34c89ffeddf0c6
[ "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
580
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.Attributes namespace Lean builtin_initialize matchPatternAttr : TagAttribute ← registerTagAttribute `match_pattern "mark that a definition can be used in a pattern (remark: the dependent pattern matching compiler will unfold the definition)" @[export lean_has_match_pattern_attribute] def hasMatchPatternAttribute (env : Environment) (n : Name) : Bool := matchPatternAttr.hasTag env n end Lean
68becea9735bafc8a3d7d313c2e418476db251c2
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/ResolveName.lean
874493db79093c4194835f3c25d52803c4c4f0e8
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,976
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.Data.OpenDecl import Lean.Hygiene import Lean.Modifiers import Lean.Exception namespace Lean /-! We use aliases to implement the `export <id> (<id>+)` command. An `export A (x)` in the namespace `B` produces an alias `B.x ~> A.x`. -/ abbrev AliasState := SMap Name (List Name) abbrev AliasEntry := Name × Name def addAliasEntry (s : AliasState) (e : AliasEntry) : AliasState := match s.find? e.1 with | none => s.insert e.1 [e.2] | some es => if es.elem e.2 then s else s.insert e.1 (e.2 :: es) builtin_initialize aliasExtension : SimplePersistentEnvExtension AliasEntry AliasState ← registerSimplePersistentEnvExtension { name := `aliasesExt, addEntryFn := addAliasEntry, addImportedFn := fun es => mkStateFromImportedEntries addAliasEntry {} es |>.switch } /- Add alias `a` for `e` -/ @[export lean_add_alias] def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) def getAliases (env : Environment) (a : Name) : List Name := match aliasExtension.getState env |>.find? a with | none => [] | some es => es -- slower, but only used in the pretty printer def getRevAliases (env : Environment) (e : Name) : List Name := (aliasExtension.getState env).fold (fun as a es => if List.contains es e then a :: as else as) [] /- Global name resolution -/ namespace ResolveName /- Check whether `ns ++ id` is a valid namepace name and/or there are aliases names `ns ++ id`. -/ private def resolveQualifiedName (env : Environment) (ns : Name) (id : Name) : List Name := let resolvedId := ns ++ id let resolvedIds := getAliases env resolvedId if env.contains resolvedId && (!id.isAtomic || !isProtected env resolvedId) then resolvedId :: resolvedIds else -- Check whether environment contains the private version. That is, `_private.<module_name>.ns.id`. let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then resolvedIdPrv :: resolvedIds else resolvedIds /- Check surrounding namespaces -/ private def resolveUsingNamespace (env : Environment) (id : Name) : Name → List Name | ns@(Name.str p _ _) => match resolveQualifiedName env ns id with | [] => resolveUsingNamespace env id p | resolvedIds => resolvedIds | _ => [] /- Check exact name -/ private def resolveExact (env : Environment) (id : Name) : Option Name := if id.isAtomic then none else let resolvedId := id.replacePrefix rootNamespace Name.anonymous if env.contains resolvedId then some resolvedId else -- We also allow `_root` when accessing private declarations. -- If we change our minds, we should just replace `resolvedId` with `id` let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then some resolvedIdPrv else none /- Check open namespaces -/ private def resolveOpenDecls (env : Environment) (id : Name) : List OpenDecl → List Name → List Name | [], resolvedIds => resolvedIds | OpenDecl.simple ns exs :: openDecls, resolvedIds => if exs.elem id then resolveOpenDecls env id openDecls resolvedIds else let newResolvedIds := resolveQualifiedName env ns id resolveOpenDecls env id openDecls (newResolvedIds ++ resolvedIds) | OpenDecl.explicit openedId resolvedId :: openDecls, resolvedIds => let resolvedIds := if id == openedId then resolvedId :: resolvedIds else resolvedIds resolveOpenDecls env id openDecls resolvedIds def resolveGlobalName (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop : Name → List String → List (Name × List String) | id@(Name.str p s _), projs => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { extractionResult with name := id }.review match resolveUsingNamespace env id ns with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map fun id => (id, projs) | [] => match resolveExact env id with | some newId => [(newId, projs)] | none => let resolvedIds := if env.contains id then [id] else [] let idPrv := mkPrivateName env id let resolvedIds := if env.contains idPrv then [idPrv] ++ resolvedIds else resolvedIds let resolvedIds := resolveOpenDecls env id openDecls resolvedIds let resolvedIds := getAliases env id ++ resolvedIds match resolvedIds with | _ :: _ => resolvedIds.eraseDups.map fun id => (id, projs) | [] => loop p (s::projs) | _, _ => [] loop extractionResult.name [] /- Namespace resolution -/ def resolveNamespaceUsingScope (env : Environment) (n : Name) : Name → Option Name | Name.anonymous => none | ns@(Name.str p _ _) => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingScope env n p | _ => unreachable! def resolveNamespaceUsingOpenDecls (env : Environment) (n : Name) : List OpenDecl → Option Name | [] => none | OpenDecl.simple ns [] :: ds => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingOpenDecls env n ds | _ :: ds => resolveNamespaceUsingOpenDecls env n ds /- Given a name `id` try to find namespace it refers to. The resolution procedure works as follows 1- If `id` is the extact name of an existing namespace, then return `id` 2- If `id` is in the scope of `namespace` commands the namespace `s_1. ... . s_n`, then return `s_1 . ... . s_i ++ n` if it is the name of an existing namespace. We search "backwards". 3- Finally, for each command `open N`, return `N ++ n` if it is the name of an existing namespace. We search "backwards" again. That is, we try the most recent `open` command first. We only consider simple `open` commands. -/ def resolveNamespace? (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : Option Name := if env.isNamespace id then some id else match resolveNamespaceUsingScope env id ns with | some n => some n | none => match resolveNamespaceUsingOpenDecls env id openDecls with | some n => some n | none => none end ResolveName class MonadResolveName (m : Type → Type) := (getCurrNamespace : m Name) (getOpenDecls : m (List OpenDecl)) export MonadResolveName (getCurrNamespace getOpenDecls) instance (m n) [MonadResolveName m] [MonadLift m n] : MonadResolveName n := { getCurrNamespace := liftM (getCurrNamespace : m _), getOpenDecls := liftM (getOpenDecls : m _) } section Methods variables {m : Type → Type} [Monad m] [MonadResolveName m] [MonadEnv m] /- Given a name `n`, return a list of possible interpretations. Each interpretation is a pair `(declName, fieldList)`, where `declName` is the name of a declaration in the current environment, and `fieldList` are (potential) field names. The pair is needed because in Lean `.` may be part of a qualified name or a field (aka dot-notation). As an example, consider the following definitions ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalName x` => `[(Foo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w])]` After `open Foo open Boo`, we have - `resolveGlobalName x` => `[(Foo.x, []), (Boo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w]), (Boo.x, [z, w])]` -/ def resolveGlobalName (id : Name) : m (List (Name × List String)) := do return ResolveName.resolveGlobalName (← getEnv) (← getCurrNamespace) (← getOpenDecls) id variables [MonadExceptOf Exception m] [MonadRef m] [AddErrorMessageContext m] def resolveNamespace (id : Name) : m Name := do match ResolveName.resolveNamespace? (← getEnv) (← getCurrNamespace) (← getOpenDecls) id with | some ns => return ns | none => throwError s!"unknown namespace '{id}'" /- Similar to `resolveGlobalName`, but discard any candidate whose `fieldList` is not empty. -/ def resolveGlobalConst (n : Name) : m (List Name) := do let cs ← resolveGlobalName n let cs := cs.filter fun (_, fieldList) => fieldList.isEmpty if cs.isEmpty then throwUnknownConstant n return cs.map (·.1) def resolveGlobalConstNoOverload (n : Name) : m Name := do let cs ← resolveGlobalConst n match cs with | [c] => pure c | _ => throwError s!"ambiguous identifier '{mkConst n}', possible interpretations: {cs.map mkConst}" end Methods end Lean
0a016af84f67c829c0cd40fea35873e71030f5c0
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/t7.lean
7e25aae2ab3f86bdaf342b65e62b65512dedba7c
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
629
lean
prelude definition Prop : Type.{1} := Type.{0} constant and : Prop → Prop → Prop context parameter {A : Type} -- Mark A as implicit parameter parameter R : A → A → Prop parameter B : Type definition id (a : A) : A := a private definition refl : Prop := ∀ (a : A), R a a definition symm : Prop := ∀ (a b : A), R a b → R b a definition trans : Prop := ∀ (a b c : A), R a b → R b c → R a c definition equivalence : Prop := and (and refl symm) trans end check id.{2} check trans.{1} check symm.{1} check equivalence.{1} (* local env = get_env() print(env:find("equivalence"):value()) *)
f89adadb7518b44b9df684dec120401c44fe5062
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/match_convoy.lean
6996bf3a826482573385701eddb3fc359a472973
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
2,694
lean
definition foo (a b : bool) : bool := match a, b with | tt, ff := tt | tt, tt := tt | ff, tt := tt | ff, ff := ff end example : foo tt tt = tt := rfl example : foo tt ff = tt := rfl example : foo ff tt = tt := rfl example : foo ff ff = ff := rfl inductive vec (A : Type) : nat → Type | nil {} : vec nat.zero | cons : ∀ {n}, A → vec n → vec (nat.succ n) open vec definition boo (n : nat) (v : vec bool n) : vec bool n := match n, v : ∀ (n : _), vec bool n → _ with | 0, nil := nil | n+1, cons a v := cons (bnot a) v end constant bag_setoid : ∀ A, setoid (list A) attribute [instance] bag_setoid noncomputable definition bag (A : Type) : Type := quot (bag_setoid A) constant subcount : ∀ {A}, list A → list A → bool constant list.count : ∀ {A}, A → list A → nat constant all_of_subcount_eq_tt : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ constant ex_of_subcount_eq_ff : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ noncomputable definition count {A} (a : A) (b : bag A) : nat := quot.lift_on b (λ l, list.count a l) (λ l₁ l₂ h, sorry) noncomputable definition subbag {A} (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix ⊆ := subbag attribute [instance] noncomputable definition decidable_subbag {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, absurd (h w) hw)) end) attribute [instance] noncomputable definition decidable_subbag2 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match sigma.mk (subcount l₁ l₂) rfl : (Σ (b : _), subcount l₁ l₂ = b) → _ with | sigma.mk tt H := is_true (all_of_subcount_eq_tt H) | sigma.mk ff H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, absurd (h w) hw)) end) local notation ⟦ a , b ⟧ := sigma.mk a b attribute [instance] noncomputable definition decidable_subbag3 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match ⟦subcount l₁ l₂, rfl⟧ : (Σ (b : _), subcount l₁ l₂ = b) → _ with | ⟦tt, H⟧ := is_true (all_of_subcount_eq_tt H) | ⟦ff, H⟧ := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, absurd (h w) hw)) end)
d1efcefb512e9a4fe3c68f435d6be70a4bd63fe7
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/vm_eval1.lean
2bf479fd82d674fdf5461214ac1231c991962a4e
[ "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
769
lean
open bool nat -- set_option trace.compiler.code_gen true attribute [reducible] definition foo (b : bool) : Type := cond b nat (nat → nat) definition bla (b : bool) : foo b → nat := bool.cases_on b (λ f, f 100) (λ n, n) definition of_dec (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h, ff) (λ h, tt) definition boo (n : nat) := bla (of_dec (n > 10)) definition x : nat := 20 definition tst (b : bool) (a : nat) : foo b := bool.cases_on b (λ n : nat, n * a) a eval bla ff (λ n : nat, n+10) eval bla tt x eval boo 11 x eval boo 9 (λ n : nat, n+20) eval tst ff 4 10 eval tst tt 3 print "---------" vm_eval bla ff (λ n : nat, n+10) vm_eval bla tt x vm_eval boo 11 x vm_eval boo 9 (λ n : nat, n+20) vm_eval tst ff 4 10 vm_eval tst tt 3
bd0e7416ea857654d8c353cbe33ffc38726f5d89
46ee5dc7248ccc9ee615639c0c003c05f58975cd
/src/soundness.lean
dbac4787b76e561c550d681eb68141b1dc4296e8
[ "Apache-2.0" ]
permissive
m4lvin/tablean
e61d593b4dde6512245192c577edeb36c48f63c0
836202612fc2bfacb5545696412e7d27f7704141
refs/heads/main
1,685,613,112,076
1,676,755,678,000
1,676,755,678,000
454,064,275
8
1
null
null
null
null
UTF-8
Lean
false
false
16,430
lean
-- SOUNDNESS import syntax import tableau open classical local attribute [instance, priority 10] prop_decidable open has_sat -- Combine a collection of pointed models with one new world using the given valuation. -- TODO: rewrite to term mode? def combinedModel { β : Type } (collection : β → Σ (W : Type), kripkeModel W × W) (newVal : char → Prop) : kripkeModel (sum unit Σ k : β, (collection k).fst) × (sum unit Σ k : β, (collection k).fst) := begin split, split, { -- making the valuation function: intro world, cases world, { -- the one new world: cases world, exact newVal, -- use new given valuation here!! }, { -- world in one of the given models: cases world with R w, exact (collection R).snd.fst.val w, } }, { -- defining relations: intros worldOne worldTwo, cases worldOne; cases worldTwo, -- four cases about two new or old worlds: { exact false, }, -- no reflexive loop at the new world. { exact (worldTwo.snd == (collection worldTwo.fst).snd.snd), }, -- conect new world to given points. { exact false }, -- no connection from models to new world { -- connect two old worlds iff they are from the same model and were connected there already: cases worldOne with kOne wOne, cases worldTwo with kTwo wTwo, have help : kOne = kTwo → Prop, { intro same, have sameCol : (collection kOne = collection kTwo), { rw ← same, }, rw ← sameCol at wTwo, exact (collection kOne).snd.fst.rel wOne wTwo, }, exact dite (kOne = kTwo) (λ same, help same) (λ _, false) }, }, { -- point at the new world: left, exact (), } end -- The combined model preserves all truths at the old worlds. lemma combMo_preserves_truth_at_oldWOrld { β : Type } (collection : β → Σ (W : Type), kripkeModel W × W) (newVal : char → Prop) : (∀ (f : formula) (R : β) (oldWorld : (collection R).fst), evaluate ((combinedModel collection newVal).fst, (sum.inr ⟨R, oldWorld⟩)) f ↔ evaluate ((collection R).snd.fst, oldWorld) f) := begin intro f, induction f ; intros R oldWorld, case bottom : { finish, }, case atom_prop : c { unfold combinedModel, unfold evaluate, }, case neg : f f_IH { unfold evaluate, rw f_IH R oldWorld, }, case and : f g f_IH g_IH { unfold evaluate, rw f_IH R oldWorld, rw g_IH R oldWorld, }, case box : f f_IH { unfold evaluate, split, { intro true_in_combo, intros otherWorld rel_in_old_model, specialize f_IH R otherWorld, rw ← f_IH, specialize true_in_combo (sum.inr ⟨R, otherWorld⟩), apply true_in_combo, unfold combinedModel, simp, exact rel_in_old_model, }, { intro true_in_old, simp, split, { intro newWorld, unfold combinedModel, tauto, -- the new world is never reachable, trivial case }, { intros otherR otherWorld, intro rel_in_new_model, specialize f_IH otherR otherWorld, unfold combinedModel at rel_in_new_model, have sameR : R = otherR, { by_contradiction, classical, finish, }, subst sameR, rw f_IH, apply true_in_old, -- remains to show that related in old model simp at *, exact rel_in_new_model, }, }, }, end -- The combined model for X satisfies X. lemma combMo_sat_X { X : finset formula } { β : set formula } { beta_def : β = { R : formula | ~R.box ∈ X } } (simple_X : simple X) (not_closed_X : ¬ closed X) (collection : β → Σ (W : Type), kripkeModel W × W) (all_pro_sat : ∀ R : β, ∀ f ∈ projection X ∪ {~R}, evaluate ((collection R).snd.fst, (collection R).snd.snd) f) : (∀ f ∈ X, evaluate ((combinedModel collection (λ c, (formula.atom_prop c ∈ X))).fst, (combinedModel collection (λ c, (formula.atom_prop c ∈ X))).snd) f) := begin intros f f_in_X, cases f, -- no induction because X is simple case formula.bottom: { unfold closed at not_closed_X, tauto, }, case atom_prop: { unfold combinedModel, unfold evaluate, simp, exact f_in_X, }, case neg: { -- subcases :-/ cases f, case atom_prop: { unfold combinedModel, unfold evaluate, unfold closed at not_closed_X, rw not_or_distrib at not_closed_X, simp at *, tauto, }, case box: newf { -- set coMo := , --unfold combinedModel, change (evaluate ((combinedModel collection (λ c, (·c) ∈ X)).fst, (combinedModel collection (λ (c : char), (·c) ∈ X)).snd) (~□newf)), unfold evaluate, rw not_forall, -- need a reachable world where newf holds, choose the witness let h : newf ∈ β, { rw beta_def, use f_in_X, }, let oldWorld : unit ⊕ Σ (k : β), (collection k).fst := sum.inr ⟨⟨newf, h⟩, (collection ⟨newf, h⟩).snd.snd⟩, use oldWorld, simp, split, { -- show that worlds are related in combined model (def above, case 2) unfold combinedModel, simp, }, { -- show that f is false at old world have coMoLemma := combMo_preserves_truth_at_oldWOrld collection (λ (c : char), (·c) ∈ X) newf ⟨newf, h⟩ (collection ⟨newf, h⟩).snd.snd, rw coMoLemma, specialize all_pro_sat ⟨newf, h⟩ (~newf), unfold evaluate at all_pro_sat, simp at *, exact all_pro_sat, }, }, case bottom: { tauto, }, all_goals { unfold simple at simple_X, by_contradiction, exact simple_X _ f_in_X, }, }, case and: fa fb { unfold simple at simple_X, by_contradiction, exact simple_X (fa ⋏ fb) f_in_X, }, case box: f { unfold evaluate, intros otherWorld is_rel, cases otherWorld, { cases is_rel, }, -- otherWorld cannot be the (unreachable) new world have coMoLemma := combMo_preserves_truth_at_oldWOrld collection (λ c, (·c) ∈ X) f otherWorld.fst otherWorld.snd, simp at coMoLemma, rw coMoLemma, specialize all_pro_sat otherWorld.fst f, simp at all_pro_sat, rw or_imp_distrib at all_pro_sat, cases all_pro_sat with _ all_pro_sat_right, rw ← proj at f_in_X, specialize all_pro_sat_right f_in_X, have sameWorld : otherWorld.snd = (collection otherWorld.fst).snd.snd, { rw (heq_iff_eq.mp (heq.symm is_rel)), }, rw sameWorld, simp, exact all_pro_sat_right, }, end -- Lemma 1 (page 16) -- A simple set of formulas X is satisfiable if and only if -- it is not closed and for all ¬[A]R ∈ X also XA; ¬R is satisfiable. lemma Lemma1_simple_sat_iff_all_projections_sat { X : finset formula } : simple X → (satisfiable X ↔ (¬ closed X ∧ ∀ R, (~□R) ∈ X → satisfiable (projection X ∪ {~R}))) := begin intro X_is_simple, split, { -- left to right intro sat_X, unfold satisfiable at *, rcases sat_X with ⟨ W, M, w, w_sat_X ⟩, split, { -- show that X is not closed: by_contradiction hyp, unfold closed at hyp, cases hyp with bot_in_X f_and_notf_in_X, { exact w_sat_X ⊥ bot_in_X, }, { rcases f_and_notf_in_X with ⟨ f, f_in_X, notf_in_X ⟩, let w_sat_f := w_sat_X f f_in_X, let w_sat_notf := w_sat_X (~f) notf_in_X, unfold evaluate at *, exact absurd w_sat_f w_sat_notf, } }, { -- show that for each ~[]R ∈ X the projection with ~R is satisfiable: intros R notboxr_in_X, let w_sat_notboxr := w_sat_X (~□R) notboxr_in_X, unfold evaluate at w_sat_notboxr, simp at w_sat_notboxr, rcases w_sat_notboxr with ⟨ v, w_rel_v, v_sat_notr ⟩, use [W, M, v], intro g, simp at *, rw or_imp_distrib, split, { intro g_is_notR, rw g_is_notR, exact v_sat_notr, }, { intro boxg_in_X, rw proj at boxg_in_X, specialize w_sat_X (□g) boxg_in_X, unfold evaluate at w_sat_X, exact w_sat_X v w_rel_v, }, }, }, { -- right to left intro rhs, cases rhs with not_closed_X all_pro_sat, unfold satisfiable at *, -- Let's build a new Kripke model! let β := { R : formula | ~□R ∈ X }, -- beware, using Axioms of Choice here! choose typeFor this_pro_sat using all_pro_sat, choose modelFor this_pro_sat using this_pro_sat, choose worldFor this_pro_sat using this_pro_sat, -- define the collection: let collection : β → (Σ (W : Type), (kripkeModel W × W)) := begin intro k, cases k with R notboxr_in_X, simp at notboxr_in_X, use [typeFor R notboxr_in_X, modelFor R notboxr_in_X, worldFor R notboxr_in_X], end, let newVal := λ c, formula.atom_prop c ∈ X, let BigM := combinedModel collection newVal, use unit ⊕ Σ k : β, (collection k).fst, use [BigM.fst, BigM.snd], -- apply Lemma, missing last argument "all_pro_sat" -- we need to use that X_is_simple (to restrict cases what phi can be) -- and that X is not closed (to ensure that it is locally consistent) apply combMo_sat_X X_is_simple not_closed_X collection, -- it remains to show that the new big model satisfies X intros R f f_inpro_or_notr, cases R with R notrbox_in_X, simp only [finset.mem_union, finset.mem_insert, finset.mem_singleton, subtype.coe_mk] at *, specialize this_pro_sat R notrbox_in_X, cases f_inpro_or_notr with f_inpro f_is_notboxR, { -- if f is in the projection specialize this_pro_sat f, rw or_imp_distrib at this_pro_sat, cases this_pro_sat with this_pro_sat_l this_pro_sat_r, exact this_pro_sat_l f_inpro, }, { -- case where f is ~[]R cases f_is_notboxR, specialize this_pro_sat (~R), rw or_imp_distrib at this_pro_sat, cases this_pro_sat with this_pro_sat_l this_pro_sat_r, exact this_pro_sat_r f_is_notboxR, }, simp, -- to check β }, end -- Each rule is sound and preserves satisfiability "downwards" lemma localRuleSoundness {α : finset formula} { B : finset (finset formula) } : localRule α B → (satisfiable α → ∃ β ∈ B, satisfiable β) := begin intro r, intro a_sat, unfold satisfiable at a_sat, rcases a_sat with ⟨ W, M, w, w_sat_a ⟩, cases r, case localRule.bot : a bot_in_a { by_contradiction, let w_sat_bot := w_sat_a ⊥ bot_in_a , unfold evaluate at w_sat_bot, exact w_sat_bot, }, case localRule.not : a f hyp { by_contradiction, have w_sat_f : evaluate (M, w) f , { apply w_sat_a, exact hyp.left, }, have w_sat_not_f : evaluate (M, w) (~f) , { apply w_sat_a (~f), exact hyp.right, }, unfold evaluate at *, exact absurd w_sat_f w_sat_not_f, }, case localRule.neg : a f hyp { have w_sat_f : evaluate (M, w) f, { specialize w_sat_a (~~f) hyp, unfold evaluate at *, finish, }, use (a \ {~~f} ∪ {f}), simp only [true_and, eq_self_iff_true, sdiff_singleton_is_erase, multiset.mem_singleton, finset.mem_mk], unfold satisfiable, use [W, M, w], intro g, simp only [ne.def, union_singleton_is_insert, finset.mem_insert, finset.mem_erase], rw or_imp_distrib, split, { intro g_is_f, rw g_is_f, apply w_sat_f, }, { rw and_imp, intros g_neq_notnotf g_in_a, apply w_sat_a, exact g_in_a, }, }, case localRule.con : a f g hyp { use ( (a \ {f ⋏ g}) ∪ { f, g } ), split, simp, unfold satisfiable, use [W, M, w], simp only [and_imp, forall_eq_or_imp, sdiff_singleton_is_erase, ne.def, finset.union_insert, finset.mem_insert, finset.mem_erase], split, { -- f specialize w_sat_a (f⋏g) hyp, unfold evaluate at *, exact w_sat_a.left, }, { intros h hhyp, simp at hhyp, cases hhyp, { -- h = g specialize w_sat_a (f⋏g) hyp, unfold evaluate at *, rw hhyp, exact w_sat_a.right, }, { -- h in a exact w_sat_a h hhyp.right, }, }, }, case localRule.nCo : a f g notfandg_in_a { unfold satisfiable, simp, let w_sat_phi := w_sat_a (~(f⋏g)) notfandg_in_a, unfold evaluate at w_sat_phi, rw not_and_distrib at w_sat_phi, cases w_sat_phi with not_w_f not_w_g, { use (a \ { ~ (f ⋏ g) } ∪ {~f}), split, { simp at *, }, { use [W, M, w], intro psi, simp, intro psi_def, cases psi_def, { rw psi_def, unfold evaluate, exact not_w_f, }, { cases psi_def with psi_in_a, exact w_sat_a psi psi_def_right, }, }, }, { use (a \ { ~ (f ⋏ g) } ∪ {~g}), split, { simp at *, }, { use [W, M, w], intro psi, simp, intro psi_def, cases psi_def, { rw psi_def, unfold evaluate, exact not_w_g, }, { cases psi_def with psi_in_a, exact w_sat_a psi psi_def_right, }, }, }, }, end -- The critical roule is sound and preserves satisfiability "downwards". -- TODO: is this the same as (one of the directions of) Lemma 1 ?? lemma atmSoundness {α : finset formula} {f} (not_box_f_in_a : ~□f ∈ α) : simple α → satisfiable α → satisfiable (projection α ∪ {~f}) := begin intro s, intro aSat, unfold satisfiable at aSat, rcases aSat with ⟨W, M, w, w_sat_a⟩, split, simp, -- get the other reachable world: let w_sat_not_box_f := w_sat_a (~f.box) not_box_f_in_a, unfold evaluate at w_sat_not_box_f, simp at w_sat_not_box_f, rcases w_sat_not_box_f with ⟨ v, w_rel_v, v_not_sat_f ⟩, -- show that the projection is satisfiable: use [M, v], split, { unfold evaluate, exact v_not_sat_f, }, intros phi phi_in_proj, rw proj at phi_in_proj, { specialize w_sat_a phi.box _, exact phi_in_proj, unfold evaluate at w_sat_a, exact w_sat_a v w_rel_v, }, end lemma localTableauAndEndNodesUnsatThenNotSat {Z} (ltZ : localTableau Z) : (Π (Y), Y ∈ endNodesOf ⟨Z, ltZ⟩ → ¬ satisfiable Y) → ¬satisfiable Z := begin intro endsOfXnotSat, induction ltZ, case byLocalRule : X YS lr next IH { by_contradiction satX, rcases localRuleSoundness lr satX with ⟨Y,Y_in_YS,satY⟩, specialize IH Y Y_in_YS, set ltY := next Y Y_in_YS, have endNodesInclusion : ∀ W, W ∈ endNodesOf ⟨Y, ltY⟩ → W ∈ endNodesOf ⟨X, localTableau.byLocalRule lr next⟩ , { rw endNodesOf, intros W W_endOF_Y, simp only [endNodesOf, finset.mem_bUnion, finset.mem_attach, exists_true_left, subtype.exists], use [Y, Y_in_YS], assumption, }, have endsOfYnotSat : (∀ (Y_1 : finset formula), Y_1 ∈ endNodesOf ⟨Y, ltY⟩ → ¬ satisfiable Y_1), { intros W W_is_endOf_Y, apply endsOfXnotSat W (endNodesInclusion W W_is_endOf_Y), }, finish, }, case sim : X X_is_simple { apply endsOfXnotSat, unfold endNodesOf, simp, }, end lemma tableauThenNotSat : ∀ X, closedTableau X → ¬ satisfiable X := begin intros X t, induction t, case loc: Y ltY next IH { apply localTableauAndEndNodesUnsatThenNotSat ltY, intros Z ZisEndOfY, exact IH Z ZisEndOfY, }, case atm: Y ϕ notBoxPhiInY Y_is_simple ltProYnPhi { rw Lemma1_simple_sat_iff_all_projections_sat Y_is_simple, simp, intro Ynotclosed, use ϕ, use notBoxPhiInY, finish, }, end -- Theorem 2, page 30 theorem correctness : ∀ X, satisfiable X → consistent X := begin intro X, contrapose, unfold consistent, simp, unfold inconsistent, intro hyp, cases hyp with t, exact tableauThenNotSat X t, end lemma soundTableau : ∀ φ, provable φ → ¬ satisfiable ({~φ} : finset formula) := begin intro phi, intro prov, cases prov with _ tabl, apply tableauThenNotSat, exact tabl, end theorem soundness : ∀ φ, provable φ → tautology φ := begin intros φ prov, apply notsatisfnotThenTaut, rw ← singletonSat_iff_sat, apply soundTableau, exact prov, end
4b2ffebcc7141d470d7eab5bfd04fbbe27ae46ac
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/int/basic.lean
250bc5a993d62bdec342cc92f948bec39c3fdc4b
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,727
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic import algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ instance : nontrivial ℤ := ⟨⟨0, 1, int.zero_ne_one⟩⟩ instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm } /- Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : decidable_linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, mul_pos := @int.mul_pos, zero_lt_one := int.zero_lt_one, .. int.comm_ring, .. int.decidable_linear_order, .. int.nontrivial } instance : decidable_linear_ordered_add_comm_group int := by apply_instance theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero @[simp] lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 := le_of_lt (int.lt_add_one_iff.mpr h) theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end /-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater than `b`, and the `pred` of a number less than `b`. -/ protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b), { induction a with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction a with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end -- Will be generalized to Euclidean domains. protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos.2 H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n := begin apply (mod_add_cancel_right b).mp, rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod] end /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem eq_div_of_mul_eq_right {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) : b = c / a := eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma add_div_of_dvd {a b c : ℤ} : c ∣ a → c ∣ b → (a + b) / c = a / c + b / c := begin intros h1 h2, by_cases h3 : c = 0, { rw [h3, zero_dvd_iff] at *, rw [h1, h2, h3], refl }, { apply mul_right_cancel' h3, rw add_mul, repeat {rw [int.div_mul_cancel]}; try {apply dvd_add}; assumption } end theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt abs_eq_zero.1 az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw [int.mul_div_cancel_left _ hb], rw mul_assoc at h, apply mul_left_cancel' hb h end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl @[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).to_nat = a.to_nat + b.to_nat := begin lift a to ℕ using ha, lift b to ℕ using hb, norm_cast, end lemma to_nat_add_one {a : ℤ} (h : 0 ≤ a) : (a + 1).to_nat = a.to_nat + 1 := to_nat_add h (zero_le_one) /-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`. -/ def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h lemma to_nat_zero_of_neg : ∀ {z : ℤ}, z < 0 → z.to_nat = 0 | (-[1+n]) _ := rfl | (int.of_nat n) h := (not_le_of_gt h $ int.of_nat_nonneg n).elim /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ /-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately using `bit`. -/ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma bodd_bit0 (n : ℤ) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n : ℤ) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n := mt (congr_arg bodd) $ by simp lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n := (bit0_ne_bit1 _ _).symm lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 := by simpa only [bit0_zero] using bit1_ne_bit0 m 0 @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical end int attribute [irreducible] int.lt
5bf0b6e0ca9bf05aaf0e7989e201b8f347f3fcee
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/normed_space/normed_group_quotient.lean
889180e16ce745ee757806742bbc09d42e34f74d
[ "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
22,001
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Riccardo Brasca -/ import analysis.normed_space.normed_group_hom /-! # Quotients of seminormed groups For any `semi_normed_group M` and any `S : add_subgroup M`, we provide a `semi_normed_group` structure on `quotient_add_group.quotient S` (abreviated `quotient S` in the following). If `S` is closed, we provide `normed_group (quotient S)` (regardless of whether `M` itself is separated). The two main properties of these structures are the underlying topology is the quotient topology and the projection is a normed group homomorphism which is norm non-increasing (better, it has operator norm exactly one unless `S` is dense in `M`). The corresponding universal property is that every normed group hom defined on `M` which vanishes on `S` descends to a normed group hom defined on `quotient S`. This file also introduces a predicate `is_quotient` characterizing normed group homs that are isomorphic to the canonical projection onto a normed group quotient. ## Main definitions We use `M` and `N` to denote seminormed groups and `S : add_subgroup M`. All the following definitions are in the `add_subgroup` namespace. Hence we can access `add_subgroup.normed_mk S` as `S.normed_mk`. * `semi_normed_group_quotient` : The seminormed group structure on the quotient by an additive subgroup. This is an instance so there is no need to explictly use it. * `normed_group_quotient` : The normed group structure on the quotient by a closed additive subgroup. This is an instance so there is no need to explictly use it. * `normed_mk S` : the normed group hom from `M` to `quotient S`. * `lift S f hf`: implements the universal property of `quotient S`. Here `(f : normed_group_hom M N)`, `(hf : ∀ s ∈ S, f s = 0)` and `lift S f hf : normed_group_hom (quotient S) N`. * `is_quotient`: given `f : normed_group_hom M N`, `is_quotient f` means `N` is isomorphic to a quotient of `M` by a subgroup, with projection `f`. Technically it asserts `f` is surjective and the norm of `f x` is the infimum of the norms of `x + m` for `m` in `f.ker`. ## Main results * `norm_normed_mk` : the operator norm of the projection is `1` if the subspace is not dense. * `is_quotient.norm_lift`: Provided `f : normed_hom M N` satisfies `is_quotient f`, for every `n : N` and positive `ε`, there exists `m` such that `f m = n ∧ ∥m∥ < ∥n∥ + ε`. ## Implementation details For any `semi_normed_group M` and any `S : add_subgroup M` we define a norm on `quotient S` by `∥x∥ = Inf (norm '' {m | mk' S m = x})`. This formula is really an implementation detail, it shouldn't be needed outside of this file setting up the theory. Since `quotient S` is automatically a topological space (as any quotient of a topological space), one needs to be careful while defining the `semi_normed_group` instance to avoid having two different topologies on this quotient. This is not purely a technological issue. Mathematically there is something to prove. The main point is proved in the auxiliary lemma `quotient_nhd_basis` that has no use beyond this verification and states that zero in the quotient admits as basis of neighborhoods in the quotient topology the sets `{x | ∥x∥ < ε}` for positive `ε`. Once this mathematical point it settled, we have two topologies that are propositionaly equal. This is not good enough for the type class system. As usual we ensure *definitional* equality using forgetful inheritance, see Note [forgetful inheritance]. A (semi)-normed group structure includes a uniform space structure which includes a topological space structure, together with propositional fields asserting compatibility conditions. The usual way to define a `semi_normed_group` is to let Lean build a uniform space structure using the provided norm, and then trivially build a proof that the norm and uniform structure are compatible. Here the uniform structure is provided using `topological_add_group.to_uniform_space` which uses the topological structure and the group structure to build the uniform structure. This uniform structure induces the correct topological structure by construction, but the fact that it is compatible with the norm is not obvious; this is where the mathematical content explained in the previous paragraph kicks in. -/ noncomputable theory open quotient_add_group metric set open_locale topological_space nnreal variables {M N : Type*} [semi_normed_group M] [semi_normed_group N] /-- The definition of the norm on the quotient by an additive subgroup. -/ noncomputable instance norm_on_quotient (S : add_subgroup M) : has_norm (quotient S) := { norm := λ x, Inf (norm '' {m | mk' S m = x}) } lemma image_norm_nonempty {S : add_subgroup M} : ∀ x : quotient S, (norm '' {m | mk' S m = x}).nonempty := begin rintro ⟨m⟩, rw set.nonempty_image_iff, use m, change mk' S m = _, refl end lemma bdd_below_image_norm (s : set M) : bdd_below (norm '' s) := begin use 0, rintro _ ⟨x, hx, rfl⟩, apply norm_nonneg end /-- The norm on the quotient satisfies `∥-x∥ = ∥x∥`. -/ lemma quotient_norm_neg {S : add_subgroup M} (x : quotient S) : ∥-x∥ = ∥x∥ := begin suffices : norm '' {m | mk' S m = x} = norm '' {m | mk' S m = -x}, by simp only [this, norm], ext r, split, { rintros ⟨m, hm : mk' S m = x, rfl⟩, subst hm, rw ← norm_neg, exact ⟨-m, by simp only [(mk' S).map_neg, set.mem_set_of_eq], rfl⟩ }, { rintros ⟨m, hm : mk' S m = -x, rfl⟩, use -m, simp [hm] } end lemma quotient_norm_sub_rev {S : add_subgroup M} (x y: quotient S) : ∥x - y∥ = ∥y - x∥ := by rw [show x - y = -(y - x), by abel, quotient_norm_neg] /-- The norm of the projection is smaller or equal to the norm of the original element. -/ lemma quotient_norm_mk_le (S : add_subgroup M) (m : M) : ∥mk' S m∥ ≤ ∥m∥ := begin apply real.Inf_le, use 0, { rintros _ ⟨n, h, rfl⟩, apply norm_nonneg }, { apply set.mem_image_of_mem, rw set.mem_set_of_eq } end /-- The norm of the image under the natural morphism to the quotient. -/ lemma quotient_norm_mk_eq (S : add_subgroup M) (m : M) : ∥mk' S m∥ = Inf ((λ x, ∥m + x∥) '' S) := begin change Inf _ = _, congr' 1, ext r, simp_rw [coe_mk', eq_iff_sub_mem], split, { rintros ⟨y, h, rfl⟩, use [y - m, h], simp }, { rintros ⟨y, h, rfl⟩, use m + y, simpa using h }, end /-- The quotient norm is nonnegative. -/ lemma quotient_norm_nonneg (S : add_subgroup M) : ∀ x : quotient S, 0 ≤ ∥x∥ := begin rintros ⟨m⟩, change 0 ≤ ∥mk' S m∥, apply real.lb_le_Inf _ (image_norm_nonempty _), rintros _ ⟨n, h, rfl⟩, apply norm_nonneg end /-- The quotient norm is nonnegative. -/ lemma norm_mk_nonneg (S : add_subgroup M) (m : M) : 0 ≤ ∥mk' S m∥ := quotient_norm_nonneg S _ /-- The norm of the image of `m : M` in the quotient by `S` is zero if and only if `m` belongs to the closure of `S`. -/ lemma quotient_norm_eq_zero_iff (S : add_subgroup M) (m : M) : ∥mk' S m∥ = 0 ↔ m ∈ closure (S : set M) := begin have : 0 ≤ ∥mk' S m∥ := norm_mk_nonneg S m, rw [← this.le_iff_eq, quotient_norm_mk_eq, real.Inf_le_iff], simp_rw [zero_add], { calc (∀ ε > (0 : ℝ), ∃ r ∈ (λ x, ∥m + x∥) '' (S : set M), r < ε) ↔ (∀ ε > 0, (∃ x ∈ S, ∥m + x∥ < ε)) : by simp [set.bex_image_iff] ... ↔ ∀ ε > 0, (∃ x ∈ S, ∥m + -x∥ < ε) : _ ... ↔ ∀ ε > 0, (∃ x ∈ S, x ∈ metric.ball m ε) : by simp [dist_eq_norm, ← sub_eq_add_neg, norm_sub_rev] ... ↔ m ∈ closure ↑S : by simp [metric.mem_closure_iff, dist_comm], apply forall_congr, intro ε, apply forall_congr, intro ε_pos, rw [← S.exists_neg_mem_iff_exists_mem], simp }, { use 0, rintro _ ⟨x, x_in, rfl⟩, apply norm_nonneg }, rw set.nonempty_image_iff, use [0, S.zero_mem] end /-- For any `x : quotient S` and any `0 < ε`, there is `m : M` such that `mk' S m = x` and `∥m∥ < ∥x∥ + ε`. -/ lemma norm_mk_lt {S : add_subgroup M} (x : quotient S) {ε : ℝ} (hε : 0 < ε) : ∃ (m : M), mk' S m = x ∧ ∥m∥ < ∥x∥ + ε := begin obtain ⟨_, ⟨m : M, H : mk' S m = x, rfl⟩, hnorm : ∥m∥ < ∥x∥ + ε⟩ := real.lt_Inf_add_pos (bdd_below_image_norm _) (image_norm_nonempty x) hε, subst H, exact ⟨m, rfl, hnorm⟩, end /-- For any `m : M` and any `0 < ε`, there is `s ∈ S` such that `∥m + s∥ < ∥mk' S m∥ + ε`. -/ lemma norm_mk_lt' (S : add_subgroup M) (m : M) {ε : ℝ} (hε : 0 < ε) : ∃ s ∈ S, ∥m + s∥ < ∥mk' S m∥ + ε := begin obtain ⟨n : M, hn : mk' S n = mk' S m, hn' : ∥n∥ < ∥mk' S m∥ + ε⟩ := norm_mk_lt (quotient_add_group.mk' S m) hε, erw [eq_comm, quotient_add_group.eq] at hn, use [- m + n, hn], rwa [add_neg_cancel_left] end /-- The quotient norm satisfies the triangle inequality. -/ lemma quotient_norm_add_le (S : add_subgroup M) (x y : quotient S) : ∥x + y∥ ≤ ∥x∥ + ∥y∥ := begin refine le_of_forall_pos_le_add (λ ε hε, _), replace hε := half_pos hε, obtain ⟨m, rfl, hm : ∥m∥ < ∥mk' S m∥ + ε / 2⟩ := norm_mk_lt x hε, obtain ⟨n, rfl, hn : ∥n∥ < ∥mk' S n∥ + ε / 2⟩ := norm_mk_lt y hε, calc ∥mk' S m + mk' S n∥ = ∥mk' S (m + n)∥ : by rw (mk' S).map_add ... ≤ ∥m + n∥ : quotient_norm_mk_le S (m + n) ... ≤ ∥m∥ + ∥n∥ : norm_add_le _ _ ... ≤ ∥mk' S m∥ + ∥mk' S n∥ + ε : by linarith end /-- The quotient norm of `0` is `0`. -/ lemma norm_mk_zero (S : add_subgroup M) : ∥(0 : quotient S)∥ = 0 := begin erw quotient_norm_eq_zero_iff, exact subset_closure S.zero_mem end /-- If `(m : M)` has norm equal to `0` in `quotient S` for a closed subgroup `S` of `M`, then `m ∈ S`. -/ lemma norm_zero_eq_zero (S : add_subgroup M) (hS : is_closed (S : set M)) (m : M) (h : ∥mk' S m∥ = 0) : m ∈ S := by rwa [quotient_norm_eq_zero_iff, hS.closure_eq] at h lemma quotient_nhd_basis (S : add_subgroup M) : (𝓝 (0 : quotient S)).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {x | ∥x∥ < ε}) := ⟨begin intros U, split, { intros U_in, rw ← (mk' S).map_zero at U_in, have := preimage_nhds_coinduced U_in, rcases metric.mem_nhds_iff.mp this with ⟨ε, ε_pos, H⟩, use [ε/2, half_pos ε_pos], intros x x_in, dsimp at x_in, rcases norm_mk_lt x (half_pos ε_pos) with ⟨y, rfl, ry⟩, apply H, rw ball_0_eq, dsimp, linarith }, { rintros ⟨ε, ε_pos, h⟩, have : (mk' S) '' (ball (0 : M) ε) ⊆ {x | ∥x∥ < ε}, { rintros - ⟨x, x_in, rfl⟩, rw mem_ball_0_iff at x_in, exact lt_of_le_of_lt (quotient_norm_mk_le S x) x_in }, apply filter.mem_sets_of_superset _ (set.subset.trans this h), clear h U this, apply is_open.mem_nhds, { change is_open ((mk' S) ⁻¹' _), erw quotient_add_group.preimage_image_coe, apply is_open_Union, rintros ⟨s, s_in⟩, exact (continuous_add_right s).is_open_preimage _ is_open_ball }, { exact ⟨(0 : M), mem_ball_self ε_pos, (mk' S).map_zero⟩ } }, end⟩ /-- The seminormed group structure on the quotient by an additive subgroup. -/ noncomputable instance add_subgroup.semi_normed_group_quotient (S : add_subgroup M) : semi_normed_group (quotient S) := { dist := λ x y, ∥x - y∥, dist_self := λ x, by simp only [norm_mk_zero, sub_self], dist_comm := quotient_norm_sub_rev, dist_triangle := λ x y z, begin unfold dist, have : x - z = (x - y) + (y - z) := by abel, rw this, exact quotient_norm_add_le S (x - y) (y - z) end, dist_eq := λ x y, rfl, to_uniform_space := topological_add_group.to_uniform_space (quotient S), uniformity_dist := begin rw uniformity_eq_comap_nhds_zero', have := (quotient_nhd_basis S).comap (λ (p : quotient S × quotient S), p.2 - p.1), apply this.eq_of_same_basis, have : ∀ ε : ℝ, (λ (p : quotient S × quotient S), p.snd - p.fst) ⁻¹' {x | ∥x∥ < ε} = {p : quotient S × quotient S | ∥p.fst - p.snd∥ < ε}, { intro ε, ext x, dsimp, rw quotient_norm_sub_rev }, rw funext this, refine filter.has_basis_binfi_principal _ set.nonempty_Ioi, rintros ε (ε_pos : 0 < ε) η (η_pos : 0 < η), refine ⟨min ε η, lt_min ε_pos η_pos, _, _⟩, { suffices : ∀ (a b : quotient S), ∥a - b∥ < ε → ∥a - b∥ < η → ∥a - b∥ < ε, by simpa, exact λ a b h h', h }, { simp } end } -- This is a sanity check left here on purpose to ensure that potential refactors won't destroy -- this important property. example (S : add_subgroup M) : (quotient.topological_space : topological_space $ quotient S) = S.semi_normed_group_quotient.to_uniform_space.to_topological_space := rfl /-- The quotient in the category of normed groups. -/ noncomputable instance add_subgroup.normed_group_quotient (S : add_subgroup M) [hS : is_closed (S : set M)] : normed_group (quotient S) := { eq_of_dist_eq_zero := begin rintros ⟨m⟩ ⟨m'⟩ (h : ∥mk' S m - mk' S m'∥ = 0), erw [← (mk' S).map_sub, quotient_norm_eq_zero_iff, hS.closure_eq, ← quotient_add_group.eq_iff_sub_mem] at h, exact h end, .. add_subgroup.semi_normed_group_quotient S } -- This is a sanity check left here on purpose to ensure that potential refactors won't destroy -- this important property. example (S : add_subgroup M) [is_closed (S : set M)] : S.semi_normed_group_quotient = normed_group.to_semi_normed_group := rfl namespace add_subgroup open normed_group_hom /-- The morphism from a seminormed group to the quotient by a subgroup. -/ noncomputable def normed_mk (S : add_subgroup M) : normed_group_hom M (quotient S) := { bound' := ⟨1, λ m, by simpa [one_mul] using quotient_norm_mk_le _ m⟩, .. quotient_add_group.mk' S } /-- `S.normed_mk` agrees with `quotient_add_group.mk' S`. -/ @[simp] lemma normed_mk.apply (S : add_subgroup M) (m : M) : normed_mk S m = quotient_add_group.mk' S m := rfl /-- `S.normed_mk` is surjective. -/ lemma surjective_normed_mk (S : add_subgroup M) : function.surjective (normed_mk S) := surjective_quot_mk _ /-- The kernel of `S.normed_mk` is `S`. -/ lemma ker_normed_mk (S : add_subgroup M) : S.normed_mk.ker = S := quotient_add_group.ker_mk _ /-- The operator norm of the projection is at most `1`. -/ lemma norm_normed_mk_le (S : add_subgroup M) : ∥S.normed_mk∥ ≤ 1 := normed_group_hom.op_norm_le_bound _ zero_le_one (λ m, by simp [quotient_norm_mk_le]) /-- The operator norm of the projection is `1` if the subspace is not dense. -/ lemma norm_normed_mk (S : add_subgroup M) (h : (S.topological_closure : set M) ≠ univ) : ∥S.normed_mk∥ = 1 := begin obtain ⟨x, hx⟩ := set.nonempty_compl.2 h, let y := S.normed_mk x, have hy : ∥y∥ ≠ 0, { intro h0, exact set.not_mem_of_mem_compl hx ((quotient_norm_eq_zero_iff S x).1 h0) }, refine le_antisymm (norm_normed_mk_le S) (le_of_forall_pos_le_add (λ ε hε, _)), suffices : 1 ≤ ∥S.normed_mk∥ + min ε ((1 : ℝ)/2), { exact le_add_of_le_add_left this (min_le_left ε ((1 : ℝ)/2)) }, have hδ := sub_pos.mpr (lt_of_le_of_lt (min_le_right ε ((1 : ℝ)/2)) one_half_lt_one), have hδpos : 0 < min ε ((1 : ℝ)/2) := lt_min hε one_half_pos, have hδnorm := mul_pos (div_pos hδpos hδ) (lt_of_le_of_ne (norm_nonneg y) hy.symm), obtain ⟨m, hm, hlt⟩ := norm_mk_lt y hδnorm, have hrw : ∥y∥ + min ε (1 / 2) / (1 - min ε (1 / 2)) * ∥y∥ = ∥y∥ * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) := by ring, rw [hrw] at hlt, have hm0 : ∥m∥ ≠ 0, { intro h0, have hnorm := quotient_norm_mk_le S m, rw [h0, hm] at hnorm, replace hnorm := le_antisymm hnorm (norm_nonneg _), simpa [hnorm] using hy }, replace hlt := (div_lt_div_right (lt_of_le_of_ne (norm_nonneg m) hm0.symm)).2 hlt, simp only [hm0, div_self, ne.def, not_false_iff] at hlt, have hrw₁ : ∥y∥ * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) / ∥m∥ = (∥y∥ / ∥m∥) * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) := by ring, rw [hrw₁] at hlt, replace hlt := (inv_pos_lt_iff_one_lt_mul (lt_trans (div_pos hδpos hδ) (lt_one_add _))).2 hlt, suffices : ∥S.normed_mk∥ ≥ 1 - min ε (1 / 2), { exact sub_le_iff_le_add.mp this }, calc ∥S.normed_mk∥ ≥ ∥(S.normed_mk) m∥ / ∥m∥ : ratio_le_op_norm S.normed_mk m ... = ∥y∥ / ∥m∥ : by rw [normed_mk.apply, hm] ... ≥ (1 + min ε (1 / 2) / (1 - min ε (1 / 2)))⁻¹ : le_of_lt hlt ... = 1 - min ε (1 / 2) : by field_simp [(ne_of_lt hδ).symm] end /-- The operator norm of the projection is `0` if the subspace is dense. -/ lemma norm_trivial_quotient_mk (S : add_subgroup M) (h : (S.topological_closure : set M) = set.univ) : ∥S.normed_mk∥ = 0 := begin refine le_antisymm (op_norm_le_bound _ (le_refl _) (λ x, _)) (norm_nonneg _), have hker : x ∈ (S.normed_mk).ker.topological_closure, { rw [S.ker_normed_mk], exact set.mem_of_eq_of_mem h trivial }, rw [ker_normed_mk] at hker, simp only [(quotient_norm_eq_zero_iff S x).mpr hker, normed_mk.apply, zero_mul], end end add_subgroup namespace normed_group_hom /-- `is_quotient f`, for `f : M ⟶ N` means that `N` is isomorphic to the quotient of `M` by the kernel of `f`. -/ structure is_quotient (f : normed_group_hom M N) : Prop := (surjective : function.surjective f) (norm : ∀ x, ∥f x∥ = Inf ((λ m, ∥x + m∥) '' f.ker)) /-- Given `f : normed_group_hom M N` such that `f s = 0` for all `s ∈ S`, where, `S : add_subgroup M` is closed, the induced morphism `normed_group_hom (quotient S) N`. -/ noncomputable def lift {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) : normed_group_hom (quotient S) N := { bound' := begin obtain ⟨c : ℝ, hcpos : (0 : ℝ) < c, hc : ∀ x, ∥f x∥ ≤ c * ∥x∥⟩ := f.bound, refine ⟨c, λ mbar, le_of_forall_pos_le_add (λ ε hε, _)⟩, obtain ⟨m : M, rfl : mk' S m = mbar, hmnorm : ∥m∥ < ∥mk' S m∥ + ε/c⟩ := norm_mk_lt mbar (div_pos hε hcpos), calc ∥f m∥ ≤ c * ∥m∥ : hc m ... ≤ c*(∥mk' S m∥ + ε/c) : ((mul_lt_mul_left hcpos).mpr hmnorm).le ... = c * ∥mk' S m∥ + ε : by rw [mul_add, mul_div_cancel' _ hcpos.ne.symm] end, .. quotient_add_group.lift S f.to_add_monoid_hom hf } lemma lift_mk {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) (m : M) : lift S f hf (S.normed_mk m) = f m := rfl lemma lift_unique {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) (g : normed_group_hom (quotient S) N) : g.comp (S.normed_mk) = f → g = lift S f hf := begin intro h, ext, rcases add_subgroup.surjective_normed_mk _ x with ⟨x,rfl⟩, change (g.comp (S.normed_mk) x) = _, simpa only [h] end /-- `S.normed_mk` satisfies `is_quotient`. -/ lemma is_quotient_quotient (S : add_subgroup M) : is_quotient (S.normed_mk) := ⟨S.surjective_normed_mk, λ m, by simpa [S.ker_normed_mk] using quotient_norm_mk_eq _ m⟩ lemma is_quotient.norm_lift {f : normed_group_hom M N} (hquot : is_quotient f) {ε : ℝ} (hε : 0 < ε) (n : N) : ∃ (m : M), f m = n ∧ ∥m∥ < ∥n∥ + ε := begin obtain ⟨m, rfl⟩ := hquot.surjective n, have nonemp : ((λ m', ∥m + m'∥) '' f.ker).nonempty, { rw set.nonempty_image_iff, exact ⟨0, f.ker.zero_mem⟩ }, have bdd : bdd_below ((λ m', ∥m + m'∥) '' f.ker), { use 0, rintro _ ⟨x, hx, rfl⟩, apply norm_nonneg }, rcases real.lt_Inf_add_pos bdd nonemp hε with ⟨_, ⟨⟨x, hx, rfl⟩, H : ∥m + x∥ < Inf ((λ (m' : M), ∥m + m'∥) '' f.ker) + ε⟩⟩, exact ⟨m+x, by rw [f.map_add,(normed_group_hom.mem_ker f x).mp hx, add_zero], by rwa hquot.norm⟩, end lemma is_quotient.norm_le {f : normed_group_hom M N} (hquot : is_quotient f) (m : M) : ∥f m∥ ≤ ∥m∥ := begin rw hquot.norm, apply real.Inf_le, { use 0, rintros _ ⟨m', hm', rfl⟩, apply norm_nonneg }, { exact ⟨0, f.ker.zero_mem, by simp⟩ } end lemma lift_norm_le {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) {c : ℝ≥0} (fb : ∥f∥ ≤ c) : ∥lift S f hf∥ ≤ c := begin apply op_norm_le_bound _ c.coe_nonneg, intros x, by_cases hc : c = 0, { simp only [hc, nnreal.coe_zero, zero_mul] at fb ⊢, obtain ⟨x, rfl⟩ := surjective_quot_mk _ x, show ∥f x∥ ≤ 0, calc ∥f x∥ ≤ 0 * ∥x∥ : f.le_of_op_norm_le fb x ... = 0 : zero_mul _ }, { replace hc : 0 < c := pos_iff_ne_zero.mpr hc, apply le_of_forall_pos_le_add, intros ε hε, have aux : 0 < (ε / c) := div_pos hε hc, obtain ⟨x, rfl, Hx⟩ : ∃ x', S.normed_mk x' = x ∧ ∥x'∥ < ∥x∥ + (ε / c) := (is_quotient_quotient _).norm_lift aux _, rw lift_mk, calc ∥f x∥ ≤ c * ∥x∥ : f.le_of_op_norm_le fb x ... ≤ c * (∥S.normed_mk x∥ + ε / c) : (mul_le_mul_left _).mpr Hx.le ... = c * _ + ε : _, { exact_mod_cast hc }, { rw [mul_add, mul_div_cancel'], exact_mod_cast hc.ne' } }, end lemma lift_norm_noninc {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) (fb : f.norm_noninc) : (lift S f hf).norm_noninc := λ x, begin have fb' : ∥f∥ ≤ (1 : ℝ≥0) := norm_noninc.norm_noninc_iff_norm_le_one.mp fb, simpa using le_of_op_norm_le _ (f.lift_norm_le _ _ fb') _, end end normed_group_hom
fbdde0b16a3b70c9a618ce6fd4f16a67b18fa1ed
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/data/finset.lean
5af15aea2d4bb30e15335395568becb7926e6dd4
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
92,337
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, Jeremy Avigad, Minchao Wu, Mario Carneiro Finite sets. -/ import logic.embedding algebra.order_functions data.multiset data.sigma.basic data.set.lattice open multiset subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /- membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /- set coercion -/ /-- Convert a finset to a set in the natural way. -/ def to_set (s : finset α) : set α := {x | x ∈ s} instance : has_lift (finset α) (set α) := ⟨to_set⟩ @[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl /- extensionality -/ theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext.2 @[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ := (set.ext_iff _ _).trans ext.symm lemma to_set_injective {α} : function.injective (finset.to_set : finset α → set α) := λ s t, coe_inj.1 /- subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp] theorem coe_subset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ := show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_iff_subset_not_subset, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff /- empty -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ | e := not_mem_empty a $ e ▸ h @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem exists_mem_iff_ne_empty {s : finset α} : (∃ a : α, a ∈ s) ↔ ¬s = ∅ := ⟨λ ⟨a, ha⟩, ne_empty_of_mem ha, exists_mem_of_ne_empty⟩ @[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl lemma nonempty_iff_ne_empty (s : finset α) : nonempty (↑s : set α) ↔ s ≠ ∅ := begin rw [set.coe_nonempty_iff_ne_empty, ←coe_empty], apply not_congr, apply function.injective.eq_iff, exact to_set_injective end /-- `singleton a` is the set `{a}` containing `a` and nothing else. -/ def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩ local prefix `ι`:90 := singleton @[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _) @[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl /- insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ @[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm] @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := ne_empty_of_mem (mem_insert_self a s) theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) := iff.intro (assume ⟨h₁, h₂⟩, have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂, let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩) (assume ⟨a, hat, has⟩, let ⟨h₁, h₂⟩ := insert_subset.mp has in ⟨h₂, assume h, hat $ h h₁⟩) lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s @[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl @[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a := insert_eq_of_mem $ mem_singleton_self _ /- union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ @[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext.2 $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext.2 $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext.2 $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext.2 $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] @[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext.2 $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext.2 $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] /- inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext.2 $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and_assoc] @[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and.left_comm] @[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext.2 $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext.2 $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext.2 $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext.2 $ λ _, mem_inter.trans $ false_and _ @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /- lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.lattice.semilattice_inf_bot, ..finset.lattice.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /- erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /- sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) @[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) @[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] lemma to_set_sdiff (s t : finset α) : (s \ t).to_set = s.to_set \ t.to_set := by apply finset.coe_sdiff end decidable_eq /- attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /- filter -/ section filter variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm] @[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext.2 $ assume a, by simp only [mem_filter, and_false]; refl lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ @[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext.2 $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] theorem filter_inter {s t : finset α} : filter p s ∩ t = filter p (s ∩ t) := by {ext, simp [and_assoc], rw [and.left_comm] } theorem inter_filter {s t : finset α} : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else (filter p s) := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter] theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} [decidable_pred (∈ t₁)] (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, classical.or_not] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter(eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, insert_empty_eq_singleton, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end end filter /- range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := finset.induction_on s ⟨0, empty_subset _⟩ $ λ a s ha ⟨n, hn⟩, ⟨max (a + 1) n, insert_subset.2 ⟨by simpa only [mem_range] using le_max_left (a+1) n, subset.trans hn (by simpa only [range_subset] using le_max_right (a+1) n)⟩⟩ end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := finset.singleton a end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /- erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a :: s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext' $ by simp @[simp] lemma to_finset_smul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (add_monoid.smul n s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, add_monoid.one_smul] }, { rw [add_monoid.add_smul, to_finset_add, add_monoid.one_smul, to_finset_smul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext' $ by simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] end list namespace finset section map open function def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_inj f.2 @[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] theorem map_refl : s.map (embedding.refl _) = s := ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) := ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ_inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] @[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] @[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) theorem image_id [decidable_eq α] : s.image id = s := ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : (singleton a).image f = singleton (f a) := ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b := ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, exists_mem_of_ne_empty h, true_and, mem_singleton, eq_comm] protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subset_image_iff [decidable_eq α] {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { exact ⟨∅, set.empty_subset _, finset.image_empty _⟩ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi] end end image /- card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = finset.singleton a := by cases s; simp [multiset.card_eq_one, finset.singleton, finset.card] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _ theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : function.injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on [decidable_eq β] {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext.2 $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt}) lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from function.injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from injective_of_has_left_inverse ⟨g, left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)⟩, subtype.ext.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a := show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _ theorem bind_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bind f ∩ t = s.bind (λ x, f x ∩ t) := by { ext x, simp, exact ⟨λ ⟨xt, y, ys, xf⟩, ⟨y, ys, xt, xf⟩, λ ⟨y, ys, xt, xf⟩, ⟨xt, y, ys, xf⟩⟩ } theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bind f = s.bind (λ x, t ∩ f x) := by rw [inter_comm, bind_inter]; simp theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm] lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := begin ext b, simp, split, { rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb }, { rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ } end end bind section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ end prod section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right] end sigma section pi variables {δ : α → Type*} [decidable_eq α] def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) := ⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩ @[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) : (s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl @[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} : f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) := mem_pi _ _ _ def pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : finset α)) : β a := multiset.pi.empty β a h def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h) @[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same _ lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := multiset.pi.cons_ne _ _ lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume e₁ e₂ eq, @multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $ funext $ assume e, funext $ assume h, have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h), by rw [eq], this @[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) := rfl @[simp] lemma pi_insert [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) := begin apply eq_of_veq, rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2, refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) = erase_dup ((t a).1.bind $ λ b, erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $ λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha), subst s', rw pi_cons, congr, funext b, rw multiset.erase_dup_eq_self.2, exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2, end end pi section powerset def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) end powerset section powerset_len def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) end powerset_len section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := by haveI := classical.prop_decidable; rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq, fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold] end fold section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_val : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b := calc _ = f b ⊔ (∅:finset β).sup f : sup_insert ... = f b : sup_bot_eq lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2)) lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := by letI := classical.dec_eq β; from calc f b ≤ f b ⊔ s.sup f : le_sup_left ... = (insert b s).sup f : sup_insert.symm ... = s.sup f : by rw [insert_eq_of_mem hb] lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := by letI := classical.dec_eq β; from finset.induction_on s (λ _, bot_le) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le H.1 (ih H.2)) @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := have A : ∀x y, g (x ⊔ y) = g x ⊔ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [sup_of_le_right h, sup_of_le_right (mono_g h)] }, { simp [sup_of_le_left h, sup_of_le_left (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt}) end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_val : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b := calc _ = f b ⊓ (∅:finset β).inf f : inf_insert ... = f b : inf_top_eq lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih, by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc] theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2)) lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := by letI := classical.dec_eq β; from calc f b ≥ f b ⊓ s.inf f : inf_le_left ... = (insert b s).inf f : inf_insert.symm ... = s.inf f : by rw [insert_eq_of_mem hb] lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_top) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact le_inf H.1 (ih H.2)) lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) := iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := have A : ∀x y, g (x ⊓ y) = g x ⊓ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [inf_of_le_left h, inf_of_le_left (mono_g h)] }, { simp [inf_of_le_right h, inf_of_le_right (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt}) end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := le_antisymm (le_infi $ assume a, le_infi $ assume ha, inf_le ha) (finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha) /- max and min of finite sets -/ section max_min variables [decidable_linear_order α] protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert @[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := max_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := min_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption lemma exists_min (s : finset β) (f : β → α) (h : nonempty ↥(↑s : set β)) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := begin have : s.image f ≠ ∅, rwa [ne, image_eq_empty, ← ne.def, ← nonempty_iff_ne_empty], cases min_of_ne_empty this with y hy, rcases mem_image.mp (mem_of_min hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', min_le_of_mem (mem_image_of_mem f hx') hy⟩ end end max_min section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_bind_left {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} [decidable_eq ι] (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} end disjoint theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ a.1 ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} [decidable_eq α] : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf section decidable_linear_order variables {α} [decidable_linear_order α] def min' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.min $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] def max' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.max $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (S : finset α) (H : S ≠ ∅) theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le S H i H1, have H6 := le_max' S H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le S H j H2, have H6 := le_max' S H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end end decidable_linear_order /- Ico (a closed open interval) -/ variables {n m l : ℕ} /-- `Ico n m` is the set of natural numbers `n ≤ k < m`. -/ def Ico (n m : ℕ) : finset ℕ := ⟨_, Ico.nodup n m⟩ namespace Ico @[simp] theorem val (n m : ℕ) : (Ico n m).1 = multiset.Ico n m := rfl @[simp] theorem to_finset (n m : ℕ) : (multiset.Ico n m).to_finset = Ico n m := (multiset.to_finset_eq _).symm theorem image_add (n m k : ℕ) : (Ico n m).image ((+) k) = Ico (n + k) (m + k) := by simp [image, multiset.Ico.map_add] theorem image_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).image (λ x, x - k) = Ico (n - k) (m - k) := begin dsimp [image], rw [multiset.Ico.map_sub _ _ _ h, ←multiset.to_finset_eq], refl, end theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq_of_veq $ multiset.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := multiset.Ico.card _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := multiset.Ico.mem theorem eq_empty_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = ∅ := eq_of_veq $ multiset.Ico.eq_zero_of_le h @[simp] theorem self_eq_empty (n : ℕ) : Ico n n = ∅ := eq_empty_of_le $ le_refl n @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = ∅ ↔ m ≤ n := iff.trans val_eq_zero.symm multiset.Ico.eq_zero_iff theorem subset_iff {m₁ n₁ m₂ n₂ : ℕ} (hmn : m₁ < n₁) : Ico m₁ n₁ ⊆ Ico m₂ n₂ ↔ (m₂ ≤ m₁ ∧ n₁ ≤ n₂) := begin simp only [subset_iff, mem], refine ⟨λ h, ⟨_, _⟩, _⟩, { exact (h ⟨le_refl _, hmn⟩).1 }, { refine le_of_pred_lt (@h (pred n₁) ⟨le_pred_of_lt hmn, pred_lt _⟩).2, exact ne_of_gt (lt_of_le_of_lt (nat.zero_le m₁) hmn) }, { rintros ⟨hm, hn⟩ k ⟨hmk, hkn⟩, exact ⟨le_trans hm hmk, lt_of_lt_of_le hkn hn⟩ } end protected theorem subset {m₁ n₁ m₂ n₂ : ℕ} (hmm : m₂ ≤ m₁) (hnn : n₁ ≤ n₂) : Ico m₁ n₁ ⊆ Ico m₂ n₂ := begin simp only [finset.subset_iff, Ico.mem], assume x hx, exact ⟨le_trans hmm hx.1, lt_of_lt_of_le hx.2 hnn⟩ end lemma union_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ∪ Ico m l = Ico n l := by rw [← to_finset, ← to_finset, ← multiset.to_finset_add, multiset.Ico.add_consecutive hnm hml, to_finset] @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = ∅ := begin rw [← to_finset, ← to_finset, ← multiset.to_finset_inter, multiset.Ico.inter_consecutive], simp, end lemma disjoint_consecutive (n m l : ℕ) : disjoint (Ico n m) (Ico m l) := le_of_eq $ inter_consecutive n m l @[simp] theorem succ_singleton (n : ℕ) : Ico n (n+1) = {n} := eq_of_veq $ multiset.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = insert m (Ico n m) := by rw [← to_finset, multiset.Ico.succ_top h, multiset.to_finset_cons, to_finset] theorem succ_top' {n m : ℕ} (h : n < m) : Ico n m = insert (m - 1) (Ico n (m - 1)) := begin have w : m = m - 1 + 1 := (nat.sub_add_cancel (nat.one_le_of_lt h)).symm, conv { to_lhs, rw w }, rw succ_top, exact nat.le_pred_of_lt h end theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = insert n (Ico (n + 1) m) := by rw [← to_finset, multiset.Ico.eq_cons h, multiset.to_finset_cons, to_finset] @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} := eq_of_veq $ multiset.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := multiset.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := eq_of_veq $ multiset.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := eq_of_veq $ multiset.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := eq_of_veq $ multiset.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := eq_of_veq $ multiset.Ico.filter_lt n m l lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := eq_of_veq $ multiset.Ico.filter_le_of_le_bot hln lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ := eq_of_veq $ multiset.Ico.filter_le_of_top_le hml lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := eq_of_veq $ multiset.Ico.filter_le_of_le hnl @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := eq_of_veq $ multiset.Ico.filter_le n m l @[simp] lemma diff_left (l n m : ℕ) : (Ico n m) \ (Ico n l) = Ico (max n l) m := by ext k; by_cases n ≤ k; simp [h, and_comm] @[simp] lemma diff_right (l n m : ℕ) : (Ico n m) \ (Ico l m) = Ico n (min m l) := have ∀k, (k < m ∧ (l ≤ k → m ≤ k)) ↔ (k < m ∧ k < l) := assume k, and_congr_right $ assume hk, by rw [← not_imp_not]; simp [hk], by ext k; by_cases n ≤ k; simp [h, this] end Ico -- TODO We don't yet attempt to reproduce the entire interface for `Ico` for `Ico_ℤ`. /-- `Ico_ℤ l u` is the set of integers `l ≤ k < u`. -/ def Ico_ℤ (l u : ℤ) : finset ℤ := (finset.range (u - l).to_nat).map { to_fun := λ n, n + l, inj := λ n m h, by simpa using h } namespace Ico_ℤ @[simp] lemma mem {n m l : ℤ} : l ∈ Ico_ℤ n m ↔ n ≤ l ∧ l < m := begin dsimp [Ico_ℤ], simp only [int.lt_to_nat, exists_prop, mem_range, add_comm, function.embedding.coe_fn_mk, mem_map], split, { rintro ⟨a, ⟨h, rfl⟩⟩, exact ⟨int.le.intro rfl, lt_sub_iff_add_lt'.mp h⟩ }, { rintro ⟨h₁, h₂⟩, use (l - n).to_nat, split; simp [h₁, h₂], } end end Ico_ℤ end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace lattice variables {ι : Sort*} [complete_lattice α] [decidable_eq ι] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := le_antisymm (le_infi $ assume t, le_infi $ assume b, le_infi $ assume hb, infi_le _ _) (le_infi $ assume b, infi_le_of_le {plift.up b} $ infi_le_of_le (plift.up b) $ infi_le_of_le (by simp) $ le_refl _) end lattice namespace set variables {ι : Sort*} [decidable_eq ι] lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := lattice.supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := lattice.infi_eq_infi_finset s end set namespace finset namespace nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : finset (ℕ × ℕ) := (multiset.nat.antidiagonal n).to_finset /-- 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 := by rw [antidiagonal, multiset.mem_to_finset, multiset.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by simpa using list.to_finset_card_of_nodup (list.nat.nodup_antidiagonal n) /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := by { rw [antidiagonal, multiset.nat.antidiagonal_zero], refl } end nat end finset
21f78bd5fe83fb1b4981d886ab40184e56252e33
367134ba5a65885e863bdc4507601606690974c1
/src/order/filter/basic.lean
e87986e8eb5c1d9f4670c25a9745c57cc5cfe698
[ "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
108,873
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, Jeremy Avigad -/ import order.zorn import order.copy import data.set.finite import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 @[simp] lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets @[simp] lemma inter_mem_sets_iff {s t} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f := ⟨λ h, ⟨mem_sets_of_superset h (inter_subset_left s t), mem_sets_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem_sets⟩ lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ @[simp] lemma bInter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs]) @[simp] lemma bInter_finset_mem_sets {β : Type v} {s : β → set α} (is : finset β) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := bInter_mem_sets is.finite_to_set alias bInter_finset_mem_sets ← finset.Inter_mem_sets attribute [protected] finset.Inter_mem_sets @[simp] lemma sInter_mem_sets {s : set (set α)} (hfin : finite s) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by rw [sInter_eq_bInter, bInter_mem_sets hfin] @[simp] lemma Inter_mem_sets {β : Type v} {s : β → set α} [fintype β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f := by simpa using bInter_mem_sets finite_univ lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', `[dsimp only [set.mem_set_of_eq]], match e' with | some e := interactive.exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.refl _ end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, subset.trans hinter hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u h, generate_sets.basic h, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f, ∃t₂∈g, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ assume s hs, by simp [mem_top_sets.1 hs]) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ 𝓟) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ class ne_bot (f : filter α) : Prop := (ne' : f ≠ ⊥) lemma ne_bot_iff {f : filter α} : ne_bot f ↔ f ≠ ⊥ := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := ne_bot.ne' @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_iff_comm.1 ne_bot_iff.symm lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ⟨ne_bot_of_le_ne_bot hf.1 hg⟩ lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_sets_of_superset hs (subset_union_left s t), mem_sets_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ supr_range lemma mem_infi_iff {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : I → set α, (∀ i, V i ∈ s i) ∧ (⋂ i, V i) ⊆ U := begin rw [infi_eq_generate, mem_generate_iff], split, { rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, let V := λ i, ⋂₀ σ i, have V_in : ∀ i, V i ∈ s i, { rintro ⟨i, i_in⟩, rw sInter_mem_sets (σfin _), apply σsub }, exact ⟨I, Ifin, V, V_in, tinter⟩ }, { rintro ⟨I, Ifin, V, V_in, h⟩, refine ⟨range V, _, _, h⟩, { rintro _ ⟨i, rfl⟩, rw mem_Union, use [i, V_in i] }, { haveI : fintype I := finite.fintype Ifin, exact finite_range _ } }, end lemma mem_infi_iff' {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : ι → set α, (∀ i ∈ I, V i ∈ s i) ∧ (⋂ i ∈ I, V i) ⊆ U := begin simp only [mem_infi_iff, set_coe.forall', bInter_eq_Inter], refine ⟨_, λ ⟨I, If, V, hV⟩, ⟨I, If, λ i, V i, hV⟩⟩, rintro ⟨I, If, V, hV⟩, lift V to ι → set α using trivial, exact ⟨I, If, V, hV⟩ end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ /-! ### Lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma nonempty_of_mem_sets {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_in_sets_eq_bot.mp hf.1)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem_sets α f hf s hs @[simp] lemma empty_nmem_sets (f : filter α) [ne_bot f] : ¬(∅ ∈ f) := λ h, (nonempty_of_mem_sets h).ne_empty rfl lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem_sets (univ_mem_sets : univ ∈ f) lemma compl_not_mem_sets {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f := λ hsc, (nonempty_of_mem_sets (inter_mem_sets h hsc)).ne_empty $ inter_compl_self s lemma filter_eq_bot_of_not_nonempty (f : filter α) (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h, ⟨λ hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot_sets)⟩, @nonempty_of_mem_sets _ _⟩ lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α := ⟨λ ⟨⟨f, g, hfg⟩⟩, by_contra $ λ h, hfg $ (filter_eq_bot_of_not_nonempty f h).trans (filter_eq_bot_of_not_nonempty g h).symm, λ ⟨x⟩, ⟨⟨⊤, ⊥, ne_bot.ne $ forall_sets_nonempty_iff_ne_bot.1 $ λ s hs, by rwa [mem_top_sets.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩⟩ lemma mem_sets_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := have ∅ ∈ f ⊓ 𝓟 sᶜ, from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : sᶜ ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := ext $ λ t, by simp [mem_binfi h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset ι, (⨅i∈t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := by rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp]; refl lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset ι, s ∈ ⨅i∈t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset (plift ι), s ∈ ⨅i∈t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup_sets, mem_join_sets] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_join_sets] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup_left (infi_le _ _) _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := ⟨begin intro h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃i, ∅ ∈ f i, from (mem_infi hd ∅).1 he, exact (hb i).ne (empty_in_sets_eq_bot.1 hi) end⟩ /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else ⟨λ h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x)⟩ lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀i, ne_bot (f i) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀i, ne_bot (f i)) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup_sets, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, 𝓟 (s x)) = 𝓟 (⋃i, s i) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_principal_sets, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_in_sets_eq_bot.symm.trans $ mem_principal_sets.trans subset_empty_iff @[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := ne_bot_iff.trans $ (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma inf_principal_eq_bot {f : filter α} {s : set α} : f ⊓ 𝓟 s = ⊥ ↔ sᶜ ∈ f := by { rw [← empty_in_sets_eq_bot, mem_inf_principal], refl } lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal_sets, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, 𝓟 (f i)) = 𝓟 (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, 𝓟 (f i)) = 𝓟 (⋂i, f i) := by simpa using infi_principal_finset finset.univ f lemma infi_principal_finite {ι : Type w} {s : set ι} (hs : finite s) (f : ι → set α) : (⨅i∈s, 𝓟 (f i)) = 𝓟 (⋂i∈s, f i) := begin unfreezingI { lift s to finset ι using hs }, -- TODO: why `unfreezingI` is needed? exact_mod_cast infi_principal_finset s f end end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_sets_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot @[simp] lemma eventually_const {f : filter α} [t : ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h] using t.ne) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_sets_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := inter_mem_sets_iff lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_all {ι} [fintype ι] {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by simpa only [filter.eventually, set_of_forall] using Inter_mem_sets @[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) := by simpa only [filter.eventually, set_of_forall] using bInter_mem_sets hI alias eventually_all_finite ← set.finite.eventually_all attribute [protected] set.finite.eventually_all @[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := I.finite_to_set.eventually_all alias eventually_all_finset ← finset.eventually_all attribute [protected] finset.eventually_all @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr_sets @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := compl_not_mem_sets h lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.filter_mono {p : α → Prop} {f g : filter α} (h : ∃ᶠ x in f, p x) (hle : f ≤ g) : ∃ᶠ x in g, p x := mt (λ h', h'.filter_mono hle) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot_iff] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl lemma eventually_eq.rfl {l : filter α} {f : α → β} : f =ᶠ[l] f := eventually_eq.refl l f @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (function.uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.div' [group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal lemma eventually_eq.sub_eq [add_group β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : f - g =ᶠ[l] 0 := by simpa using (eventually_eq.sub (eventually_eq.refl l f) h).symm lemma eventually_eq_iff_sub [add_group β] {f g : α → β} {l : filter α} : f =ᶠ[l] g ↔ f - g =ᶠ[l] 0 := ⟨λ h, h.sub_eq, λ h, by simpa using h.add (eventually_eq.refl l g)⟩ section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := eventually_eq.rfl.le lemma eventually_le.rfl : f ≤ᶠ[l] f := eventually_le.refl l f @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ @[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) := h'.mp $ h.mono $ λ x, and.imp @[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) := h'.mp $ h.mono $ λ x, or.imp @[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) : (tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) := h.mono $ λ x, mt @[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : t' ≤ᶠ[l] s') : (s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma image_mem_map_iff (hf : function.injective m) : m '' s ∈ map m f ↔ s ∈ f := ⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩ lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_id' : filter.map (λ x, x) f = f := map_id @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_sets_of_superset t_in, rintros y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := begin classical, erw [← not_iff_not, not_not, not_not, filter.eventually_comap], simp only [not_exists, not_and], end end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure_sets, mem_principal_sets, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β, pure_bind, bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map, mem_join_sets, mem_set_of_eq, function.comp, mem_pure_sets] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f.sets ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintros ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem_sets] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ λ s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨mem_sets_of_superset ht₁ (subset_union_left _ _), mem_sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap (f : filter β) (m : α → β) : (f.comap m).map m = f ⊓ 𝓟 (range m) := begin refine le_antisymm (le_inf map_comap_le $ le_principal_iff.2 range_mem_map) _, rintro t' ⟨t, ht, sub⟩, refine mem_inf_principal.2 (mem_sets_of_superset ht _), rintro _ hxt ⟨x, rfl⟩, exact sub hxt end lemma map_comap_of_mem {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := by rw [map_comap, inf_eq_left.2 (le_principal_iff.2 hf)] lemma comap_le_comap_iff {f g : filter β} {m : α → β} (hf : range m ∈ f) : comap m f ≤ comap m g ↔ f ≤ g := ⟨λ h, map_comap_of_mem hf ▸ (map_mono h).trans map_comap_le, λ h, comap_mono h⟩ theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := map_comap_of_mem $ by simp only [hf.range_eq, univ_mem_sets] lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := by rw [map_comap, subtype.range_coe] lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := have (coe : s × s → α × α) = (λ x, (x.1, x.2)), by ext ⟨x, y⟩; refl, by simp [this, map_comap, ← prod_range_range_eq] lemma image_mem_sets {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap_of_mem h, exact image_mem_map W_in end lemma image_coe_mem_sets {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_sets (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : function.injective m) : comap m (map m f) = f := le_antisymm (assume s hs, mem_sets_of_superset (preimage_mem_comap $ image_mem_map hs) $ by simp only [preimage_image_eq s h]) le_comap_map lemma mem_comap_iff {f : filter β} {m : α → β} (inj : function.injective m) (large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f := by rw [← image_mem_map_iff inj, map_comap_of_mem large] lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : function.injective m) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_sets_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.refl _⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m := by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm] lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ (range m)ᶜ ∉ f := comap_ne_bot_iff_frequently lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot_iff_frequently.2 $ eventually.frequently hm lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine ⟨compl_compl s ▸ mt mem_sets_of_eq_bot _⟩, rintros ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : function.surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem_sets' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_sets_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := by simp only [ne_bot_iff, ne, map_eq_bot_iff] lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [mem_infi hf, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (assume s hs, _), simp only [mem_inf_sets, exists_prop, mem_map, mem_preimage, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀ s ∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintros U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, rw ← image_subset_iff at h, use [f '' V, image_mem_map V_in, Z, Z_in], refine subset.trans _ h, have : f '' (V ∩ f ⁻¹' Z) ⊆ f '' (V ∩ W), from image_subset _ (inter_subset_inter_right _ ‹_›), rwa image_inter_preimage at this } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : function.injective (pure : α → filter α) := assume a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := ⟨mt empty_in_sets_eq_bot.2 $ not_mem_empty a⟩ @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure_sets, λ h s hs, mem_sets_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (λ ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, λ a, hts _⟩) (λ ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, λ f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, exact singleton_mem_pure_sets }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs singleton_mem_pure_sets }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind_sets' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join_sets, mem_bind_sets', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind_sets, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse_sets : ∀(fs : list β') (us : list γ'), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃us:list (set α'), forall₂ (λb (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure_sets, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma le_map_of_right_inverse {mab : α → β} {mba : β → α} {f : filter α} {g : filter β} (h₁ : mab ∘ mba =ᶠ[g] id) (h₂ : tendsto mba g f) : g ≤ map mab f := by { rw [← @map_id _ g, ← map_congr h₁, ← map_map], exact map_mono h₂ } lemma tendsto_of_not_nonempty {f : α → β} {la : filter α} {lb : filter β} (h : ¬nonempty α) : tendsto f la lb := by simp only [filter_eq_bot_of_not_nonempty la h, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := le_trans (map_mono h) hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, tendsto_comap.comp h, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap_of_mem h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅i, x i) y := hi.mono_left $ infi_le _ _ lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map, filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map, mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λx, b) a (pure b) := tendsto_pure.2 $ univ_mem_sets' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl @[simp] lemma map_inf_principal_preimage {f : α → β} {s : set β} {l : filter α} : map f (l ⊓ 𝓟 (f ⁻¹' s)) = map f l ⊓ 𝓟 s := filter.ext $ λ t, by simp only [mem_map, mem_inf_principal, mem_set_of_eq, mem_preimage] /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot.ne hb.eq_bot lemma tendsto.if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [∀ x, decidable (p x)] (h₀ : tendsto f (l₁ ⊓ 𝓟 {x | p x}) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin simp only [tendsto_def, mem_inf_principal] at *, intros s hs, filter_upwards [h₀ s hs, h₁ s hs], simp only [mem_preimage], intros x hp₀ hp₁, split_ifs, exacts [hp₀ h, hp₁ h] end lemma tendsto.piecewise {l₁ : filter α} {l₂ : filter β} {f g : α → β} {s : set α} [∀ x, decidable (x ∈ s)] (h₀ : tendsto f (l₁ ⊓ 𝓟 s) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 sᶜ) l₂) : tendsto (piecewise s f g) l₁ l₂ := h₀.if h₁ /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end @[simp] lemma prod_mem_prod_iff {s : set α} {t : set β} {f : filter α} {g : filter β} [f.ne_bot] [g.ne_bot] : s.prod t ∈ f ×ᶠ g ↔ s ∈ f ∧ t ∈ g := ⟨λ h, let ⟨s', hs', t', ht', H⟩ := mem_prod_iff.1 h in (prod_subset_prod_iff.1 H).elim (λ ⟨hs's, ht't⟩, ⟨mem_sets_of_superset hs' hs's, mem_sets_of_superset ht' ht't⟩) (λ h, h.elim (λ hs'e, absurd hs'e (nonempty_of_mem_sets hs').ne_empty) (λ ht'e, absurd ht'e (nonempty_of_mem_sets ht').ne_empty)), λ h, prod_mem_prod h.1 h.2⟩ lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅i, f i) ×ᶠ g = (⨅i, (f i) ×ᶠ g) := by rw [filter.prod, comap_infi, infi_inf]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅i, g i) = (⨅i, f ×ᶠ (g i)) := by rw [filter.prod, comap_infi, inf_infi]; simp only [filter.prod, eq_self_iff_true] @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λp:β×α, (p.2, p.1)) (g ×ᶠ f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma prod_map_map_eq' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) (F : filter α₁) (G : filter β₁) : (map f F) ×ᶠ (map g G) = map (prod.map f g) (F ×ᶠ G) := by { rw filter.prod_map_map_eq, refl } lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma pure_prod {a : α} {f : filter β} : pure a ×ᶠ f = map (prod.mk a) f := by rw [prod_eq, map_pure, pure_seq_eq_map] @[simp] lemma prod_pure {f : filter α} {b : β} : f ×ᶠ pure b = map (λ a, (a, b)) f := by rw [prod_eq, seq_pure, map_map] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := by simp only [ne_bot_iff, ne, prod_eq_bot, not_or_distrib] lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /-! ### Coproducts of filters -/ section coprod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /-- Coproduct of filters. -/ protected def coprod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊔ g.comap prod.snd lemma mem_coprod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f.coprod g ↔ ((∃ t₁ ∈ f, prod.fst ⁻¹' t₁ ⊆ s) ∧ (∃ t₂ ∈ g, prod.snd ⁻¹' t₂ ⊆ s)) := by simp [filter.coprod] @[mono] lemma coprod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.coprod g₁ ≤ f₂.coprod g₂ := sup_le_sup (comap_mono hf) (comap_mono hg) lemma principal_coprod_principal (s : set α) (t : set β) : (𝓟 s).coprod (𝓟 t) = 𝓟 (sᶜ.prod tᶜ)ᶜ := begin rw [filter.coprod, comap_principal, comap_principal, sup_principal], congr, ext x, simp ; tauto, end -- this inequality can be strict; see `map_const_principal_coprod_map_id_principal` and -- `map_prod_map_const_id_principal_coprod_principal` below. lemma map_prod_map_coprod_le {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : map (prod.map m₁ m₂) (f₁.coprod f₂) ≤ (map m₁ f₁).coprod (map m₂ f₂) := begin intros s, simp only [mem_map, mem_coprod_iff], rintros ⟨⟨u₁, hu₁, h₁⟩, ⟨u₂, hu₂, h₂⟩⟩, refine ⟨⟨m₁ ⁻¹' u₁, hu₁, λ _ hx, h₁ _⟩, ⟨m₂ ⁻¹' u₂, hu₂, λ _ hx, h₂ _⟩⟩; convert hx end /-- Characterization of the coproduct of the `filter.map`s of two principal filters `𝓟 {a}` and `𝓟 {i}`, the first under the constant function `λ a, b` and the second under the identity function. Together with the next lemma, `map_prod_map_const_id_principal_coprod_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_const_principal_coprod_map_id_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : (map (λ _ : α, b) (𝓟 {a})).coprod (map id (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι) ∪ (univ : set β).prod {i}) := begin rw [map_principal, map_principal, principal_coprod_principal], congr, ext ⟨b', i'⟩, simp, tauto, end /-- Characterization of the `filter.map` of the coproduct of two principal filters `𝓟 {a}` and `𝓟 {i}`, under the `prod.map` of two functions, respectively the constant function `λ a, b` and the identity function. Together with the previous lemma, `map_const_principal_coprod_map_id_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_prod_map_const_id_principal_coprod_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : map (prod.map (λ _ : α, b) id) ((𝓟 {a}).coprod (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι)) := begin rw [principal_coprod_principal, map_principal], congr, ext ⟨b', i'⟩, split, { rintros ⟨⟨a'', i''⟩, h₁, ⟨h₂, h₃⟩⟩, simp }, { rintros ⟨h₁, h₂⟩, use (a, i'), simpa using h₁.symm } end lemma tendsto.prod_map_coprod {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a.coprod b) (c.coprod d) := map_prod_map_coprod_le.trans (coprod_mono hf hg) end coprod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β} (h : eq_on f g s) (hl : s ∈ l) : f =ᶠ[l] g := h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl lemma set.subset.eventually_le {α} {l : filter α} {s t : set α} (h : s ⊆ t) : s ≤ᶠ[l] t := filter.eventually_of_forall h lemma set.maps_to.tendsto {α β} {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) : filter.tendsto f (𝓟 s) (𝓟 t) := filter.tendsto_principal_principal.2 h
d9235ff5d4d81a6e96b92afb367c9f05e36a2678
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/integral/lebesgue.lean
6041f5c3b17477440b9de5fb1ebf84d1570680de
[ "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
104,216
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import dynamics.ergodic.measure_preserving import measure_theory.function.simple_func import measure_theory.measure.mutually_singular /-! # Lower Lebesgue integral for `ℝ≥0∞`-valued functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the lower Lebesgue integral of an `ℝ≥0∞`-valued function. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : α → ℝ≥0∞`. * `∫⁻ x, f x ∂μ`: integral of a function `f : α → ℝ≥0∞` with respect to a measure `μ`; * `∫⁻ x, f x`: integral of a function `f : α → ℝ≥0∞` with respect to the canonical measure `volume` on `α`; * `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ℝ≥0∞` over a set `s` with respect to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : α → ℝ≥0∞` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`. -/ noncomputable theory open set (hiding restrict restrict_apply) filter ennreal function (support) open_locale classical topology big_operators nnreal ennreal measure_theory namespace measure_theory section move_this variables {α : Type*} {mα : measurable_space α} {a : α} {s : set α} include mα -- todo after the port: move to measure_theory/measure/measure_space lemma restrict_dirac' (hs : measurable_set s) [decidable (a ∈ s)] : (measure.dirac a).restrict s = if a ∈ s then measure.dirac a else 0 := begin ext1 t ht, classical, simp only [measure.restrict_apply ht, measure.dirac_apply' _ (ht.inter hs), set.indicator_apply, set.mem_inter_iff, pi.one_apply], by_cases has : a ∈ s, { simp only [has, and_true, if_true], split_ifs with hat, { rw measure.dirac_apply_of_mem hat, }, { simp only [measure.dirac_apply' _ ht, set.indicator_apply, hat, if_false], }, }, { simp only [has, and_false, if_false, measure.coe_zero, pi.zero_apply], }, end -- todo after the port: move to measure_theory/measure/measure_space lemma restrict_dirac [measurable_singleton_class α] [decidable (a ∈ s)] : (measure.dirac a).restrict s = if a ∈ s then measure.dirac a else 0 := begin ext1 t ht, classical, simp only [measure.restrict_apply ht, measure.dirac_apply _, set.indicator_apply, set.mem_inter_iff, pi.one_apply], by_cases has : a ∈ s, { simp only [has, and_true, if_true], split_ifs with hat, { rw measure.dirac_apply_of_mem hat, }, { simp only [measure.dirac_apply' _ ht, set.indicator_apply, hat, if_false], }, }, { simp only [has, and_false, if_false, measure.coe_zero, pi.zero_apply], }, end end move_this local infixr ` →ₛ `:25 := simple_func variables {α β γ δ : Type*} section lintegral open simple_func variables {m : measurable_space α} {μ ν : measure α} {f : α → ℝ≥0∞} {s : set α} /-- The **lower Lebesgue integral** of a function `f` with respect to a measure `μ`. -/ @[irreducible] def lintegral {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : ℝ≥0∞ := ⨆ (g : α →ₛ ℝ≥0∞) (hf : ⇑g ≤ f), g.lintegral μ /-! In the notation for integrals, an expression like `∫⁻ x, g ‖x‖ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫⁻ x, f x = 0` will be parsed incorrectly. -/ notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral (measure.restrict μ s) r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r theorem simple_func.lintegral_eq_lintegral {m : measurable_space α} (f : α →ₛ ℝ≥0∞) (μ : measure α) : ∫⁻ a, f a ∂ μ = f.lintegral μ := begin rw lintegral, exact le_antisymm (supr₂_le $ λ g hg, lintegral_mono hg $ le_rfl) (le_supr₂_of_le f le_rfl le_rfl) end @[mono] lemma lintegral_mono' {m : measurable_space α} ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ℝ≥0∞⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := begin rw [lintegral, lintegral], exact supr_mono (λ φ, supr_mono' $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩) end lemma lintegral_mono ⦃f g : α → ℝ≥0∞⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono' (le_refl μ) hfg lemma lintegral_mono_nnreal {f g : α → ℝ≥0} (h : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono $ λ a, ennreal.coe_le_coe.2 (h a) lemma supr_lintegral_measurable_le_eq_lintegral (f : α → ℝ≥0∞) : (⨆ (g : α → ℝ≥0∞) (g_meas : measurable g) (hg : g ≤ f), ∫⁻ a, g a ∂μ) = ∫⁻ a, f a ∂μ := begin apply le_antisymm, { exact supr_le (λ i, supr_le (λ hi, supr_le (λ h'i, lintegral_mono h'i))) }, { rw lintegral, refine supr₂_le (λ i hi, le_supr₂_of_le i i.measurable $ le_supr_of_le hi _), exact le_of_eq (i.lintegral_eq_lintegral _).symm }, end lemma lintegral_mono_set {m : measurable_space α} ⦃μ : measure α⦄ {s t : set α} {f : α → ℝ≥0∞} (hst : s ⊆ t) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in t, f x ∂μ := lintegral_mono' (measure.restrict_mono hst (le_refl μ)) (le_refl f) lemma lintegral_mono_set' {m : measurable_space α} ⦃μ : measure α⦄ {s t : set α} {f : α → ℝ≥0∞} (hst : s ≤ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in t, f x ∂μ := lintegral_mono' (measure.restrict_mono' hst (le_refl μ)) (le_refl f) lemma monotone_lintegral {m : measurable_space α} (μ : measure α) : monotone (lintegral μ) := lintegral_mono @[simp] lemma lintegral_const (c : ℝ≥0∞) : ∫⁻ a, c ∂μ = c * μ univ := by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const] lemma lintegral_zero : ∫⁻ a:α, 0 ∂μ = 0 := by simp lemma lintegral_zero_fun : lintegral μ (0 : α → ℝ≥0∞) = 0 := lintegral_zero @[simp] lemma lintegral_one : ∫⁻ a, (1 : ℝ≥0∞) ∂μ = μ univ := by rw [lintegral_const, one_mul] lemma set_lintegral_const (s : set α) (c : ℝ≥0∞) : ∫⁻ a in s, c ∂μ = c * μ s := by rw [lintegral_const, measure.restrict_apply_univ] lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s := by rw [set_lintegral_const, one_mul] lemma set_lintegral_const_lt_top [is_finite_measure μ] (s : set α) {c : ℝ≥0∞} (hc : c ≠ ∞) : ∫⁻ a in s, c ∂μ < ∞ := begin rw lintegral_const, exact ennreal.mul_lt_top hc (measure_ne_top (μ.restrict s) univ), end lemma lintegral_const_lt_top [is_finite_measure μ] {c : ℝ≥0∞} (hc : c ≠ ∞) : ∫⁻ a, c ∂μ < ∞ := by simpa only [measure.restrict_univ] using set_lintegral_const_lt_top univ hc section variable (μ) /-- For any function `f : α → ℝ≥0∞`, there exists a measurable function `g ≤ f` with the same integral. -/ lemma exists_measurable_le_lintegral_eq (f : α → ℝ≥0∞) : ∃ g : α → ℝ≥0∞, measurable g ∧ g ≤ f ∧ ∫⁻ a, f a ∂μ = ∫⁻ a, g a ∂μ := begin cases eq_or_ne (∫⁻ a, f a ∂μ) 0 with h₀ h₀, { exact ⟨0, measurable_zero, zero_le f, h₀.trans lintegral_zero.symm⟩ }, rcases exists_seq_strict_mono_tendsto' h₀.bot_lt with ⟨L, hL_mono, hLf, hL_tendsto⟩, have : ∀ n, ∃ g : α → ℝ≥0∞, measurable g ∧ g ≤ f ∧ L n < ∫⁻ a, g a ∂μ, { intro n, simpa only [← supr_lintegral_measurable_le_eq_lintegral f, lt_supr_iff, exists_prop] using (hLf n).2 }, choose g hgm hgf hLg, refine ⟨λ x, ⨆ n, g n x, measurable_supr hgm, λ x, supr_le (λ n, hgf n x), le_antisymm _ _⟩, { refine le_of_tendsto' hL_tendsto (λ n, (hLg n).le.trans $ lintegral_mono $ λ x, _), exact le_supr (λ n, g n x) n }, { exact lintegral_mono (λ x, supr_le $ λ n, hgf n x) } end end /-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions `φ : α →ₛ ℝ≥0∞` such that `φ ≤ f`. This lemma says that it suffices to take functions `φ : α →ₛ ℝ≥0`. -/ lemma lintegral_eq_nnreal {m : measurable_space α} (f : α → ℝ≥0∞) (μ : measure α) : (∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x), (φ.map (coe : ℝ≥0 → ℝ≥0∞)).lintegral μ) := begin rw lintegral, refine le_antisymm (supr₂_le $ assume φ hφ, _) (supr_mono' $ λ φ, ⟨φ.map (coe : ℝ≥0 → ℝ≥0∞), le_rfl⟩), by_cases h : ∀ᵐ a ∂μ, φ a ≠ ∞, { let ψ := φ.map ennreal.to_nnreal, replace h : ψ.map (coe : ℝ≥0 → ℝ≥0∞) =ᵐ[μ] φ := h.mono (λ a, ennreal.coe_to_nnreal), have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x), exact le_supr_of_le (φ.map ennreal.to_nnreal) (le_supr_of_le this (ge_of_eq $ lintegral_congr h)) }, { have h_meas : μ (φ ⁻¹' {∞}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h, refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _), obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {∞}), from exists_nat_mul_gt h_meas (ne_of_lt hb), use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {∞}), simp only [lt_supr_iff, exists_prop, coe_restrict, φ.measurable_set_preimage, coe_const, ennreal.coe_indicator, map_coe_ennreal_restrict, simple_func.map_const, ennreal.coe_nat, restrict_const_lintegral], refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩, simp only [mem_preimage, mem_singleton_iff] at hx, simp only [hx, le_top] } end lemma exists_simple_func_forall_lintegral_sub_lt_of_pos {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ φ : α →ₛ ℝ≥0, (∀ x, ↑(φ x) ≤ f x) ∧ ∀ ψ : α →ₛ ℝ≥0, (∀ x, ↑(ψ x) ≤ f x) → (map coe (ψ - φ)).lintegral μ < ε := begin rw lintegral_eq_nnreal at h, have := ennreal.lt_add_right h hε, erw ennreal.bsupr_add at this; [skip, exact ⟨0, λ x, zero_le _⟩], simp_rw [lt_supr_iff, supr_lt_iff, supr_le_iff] at this, rcases this with ⟨φ, hle : ∀ x, ↑(φ x) ≤ f x, b, hbφ, hb⟩, refine ⟨φ, hle, λ ψ hψ, _⟩, have : (map coe φ).lintegral μ ≠ ∞, from ne_top_of_le_ne_top h (le_supr₂ φ hle), rw [← ennreal.add_lt_add_iff_left this, ← add_lintegral, ← map_add @ennreal.coe_add], refine (hb _ (λ x, le_trans _ (max_le (hle x) (hψ x)))).trans_lt hbφ, norm_cast, simp only [add_apply, sub_apply, add_tsub_eq_max] end theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ℝ≥0∞) : (⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) := begin simp only [← supr_apply], exact (monotone_lintegral μ).le_map_supr end lemma supr₂_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ℝ≥0∞) : (⨆ i j, ∫⁻ a, f i j a ∂μ) ≤ (∫⁻ a, ⨆ i j, f i j a ∂μ) := by { convert (monotone_lintegral μ).le_map_supr₂ f, ext1 a, simp only [supr_apply] } theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ℝ≥0∞) : (∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) := by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le } lemma le_infi₂_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ℝ≥0∞) : (∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) := by { convert (monotone_lintegral μ).map_infi₂_le f, ext1 a, simp only [infi_apply] } lemma lintegral_mono_ae {f g : α → ℝ≥0∞} (h : ∀ᵐ a ∂μ, f a ≤ g a) : (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) := begin rcases exists_measurable_superset_of_null h with ⟨t, hts, ht, ht0⟩, have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0, rw [lintegral, lintegral], refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _), by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma set_lintegral_mono_ae {s : set α} {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) (hfg : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ := lintegral_mono_ae $ (ae_restrict_iff $ measurable_set_le hf hg).2 hfg lemma set_lintegral_mono {s : set α} {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) (hfg : ∀ x ∈ s, f x ≤ g x) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ := set_lintegral_mono_ae hf hg (ae_of_all _ hfg) lemma lintegral_congr_ae {f g : α → ℝ≥0∞} (h : f =ᵐ[μ] g) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le) lemma lintegral_congr {f g : α → ℝ≥0∞} (h : ∀ a, f a = g a) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := by simp only [h] lemma set_lintegral_congr {f : α → ℝ≥0∞} {s t : set α} (h : s =ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := by rw [measure.restrict_congr_set h] lemma set_lintegral_congr_fun {f g : α → ℝ≥0∞} {s : set α} (hs : measurable_set s) (hfg : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in s, g x ∂μ := by { rw lintegral_congr_ae, rw eventually_eq, rwa ae_restrict_iff' hs, } lemma lintegral_of_real_le_lintegral_nnnorm (f : α → ℝ) : ∫⁻ x, ennreal.of_real (f x) ∂μ ≤ ∫⁻ x, ‖f x‖₊ ∂μ := begin simp_rw ← of_real_norm_eq_coe_nnnorm, refine lintegral_mono (λ x, ennreal.of_real_le_of_real _), rw real.norm_eq_abs, exact le_abs_self (f x), end lemma lintegral_nnnorm_eq_of_ae_nonneg {f : α → ℝ} (h_nonneg : 0 ≤ᵐ[μ] f) : ∫⁻ x, ‖f x‖₊ ∂μ = ∫⁻ x, ennreal.of_real (f x) ∂μ := begin apply lintegral_congr_ae, filter_upwards [h_nonneg] with x hx, rw [real.nnnorm_of_nonneg hx, ennreal.of_real_eq_coe_nnreal hx], end lemma lintegral_nnnorm_eq_of_nonneg {f : α → ℝ} (h_nonneg : 0 ≤ f) : ∫⁻ x, ‖f x‖₊ ∂μ = ∫⁻ x, ennreal.of_real (f x) ∂μ := lintegral_nnnorm_eq_of_ae_nonneg (filter.eventually_of_forall h_nonneg) /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ℝ≥0∞} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin set c : ℝ≥0 → ℝ≥0∞ := coe, set F := λ a:α, ⨆n, f n a, have hF : measurable F := measurable_supr hf, refine le_antisymm _ (supr_lintegral_le _), rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_le (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ℝ≥0∞) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (pos_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ℝ≥0∞, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, measurable_set {a : α | ⇑(map c rs) a ≤ f n a} := assume n, measurable_set_le (simple_func.measurable _) (hf n), calc (r:ℝ≥0∞) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) : by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral] ... = ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : by simp only [(eq _).symm] ... = ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : finset.sum_congr rfl $ assume x hx, begin rw [measure_Union_eq_supr (directed_of_sup $ mono x), ennreal.mul_supr], end ... = ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : begin rw [ennreal.finset_sum_supr_nat], assume p i j h, exact mul_le_mul_left' (measure_mono $ mono p h) _ end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) : begin refine supr_mono (λ n, _), rw [restrict_lintegral _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2 with a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a ∂μ) : begin refine supr_mono (λ n, _), rw [← simple_func.lintegral_eq_lintegral], refine lintegral_mono (assume a, _), simp only [map_apply] at h_meas, simp only [coe_map, restrict_apply _ (h_meas _), (∘)], exact indicator_apply_le id, end end /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. Version with ae_measurable functions. -/ theorem lintegral_supr' {f : ℕ → α → ℝ≥0∞} (hf : ∀n, ae_measurable (f n) μ) (h_mono : ∀ᵐ x ∂μ, monotone (λ n, f n x)) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin simp_rw ←supr_apply, let p : α → (ℕ → ℝ≥0∞) → Prop := λ x f', monotone f', have hp : ∀ᵐ x ∂μ, p x (λ i, f i x), from h_mono, have h_ae_seq_mono : monotone (ae_seq hf p), { intros n m hnm x, by_cases hx : x ∈ ae_seq_set hf p, { exact ae_seq.prop_of_mem_ae_seq_set hf hx hnm, }, { simp only [ae_seq, hx, if_false], exact le_rfl, }, }, rw lintegral_congr_ae (ae_seq.supr hf hp).symm, simp_rw supr_apply, rw @lintegral_supr _ _ μ _ (ae_seq.measurable hf p) h_ae_seq_mono, congr, exact funext (λ n, lintegral_congr_ae (ae_seq.ae_seq_n_eq_fun_n_ae hf hp n)), end /-- Monotone convergence theorem expressed with limits -/ theorem lintegral_tendsto_of_tendsto_of_monotone {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} (hf : ∀n, ae_measurable (f n) μ) (h_mono : ∀ᵐ x ∂μ, monotone (λ n, f n x)) (h_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 $ F x)) : tendsto (λ n, ∫⁻ x, f n x ∂μ) at_top (𝓝 $ ∫⁻ x, F x ∂μ) := begin have : monotone (λ n, ∫⁻ x, f n x ∂μ) := λ i j hij, lintegral_mono_ae (h_mono.mono $ λ x hx, hx hij), suffices key : ∫⁻ x, F x ∂μ = ⨆n, ∫⁻ x, f n x ∂μ, { rw key, exact tendsto_at_top_supr this }, rw ← lintegral_supr' hf h_mono, refine lintegral_congr_ae _, filter_upwards [h_mono, h_tendsto] with _ hx_mono hx_tendsto using tendsto_nhds_unique hx_tendsto (tendsto_at_top_supr hx_mono), end lemma lintegral_eq_supr_eapprox_lintegral {f : α → ℝ≥0∞} (hf : measurable f) : (∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) := calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ℝ≥0∞) a ∂μ) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ℝ≥0∞) a ∂μ) : begin rw [lintegral_supr], { measurability, }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. This lemma states states this fact in terms of `ε` and `δ`. -/ lemma exists_pos_set_lintegral_lt_of_measure_lt {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ δ > 0, ∀ s, μ s < δ → ∫⁻ x in s, f x ∂μ < ε := begin rcases exists_between hε.bot_lt with ⟨ε₂, hε₂0 : 0 < ε₂, hε₂ε⟩, rcases exists_between hε₂0 with ⟨ε₁, hε₁0, hε₁₂⟩, rcases exists_simple_func_forall_lintegral_sub_lt_of_pos h hε₁0.ne' with ⟨φ, hle, hφ⟩, rcases φ.exists_forall_le with ⟨C, hC⟩, use [(ε₂ - ε₁) / C, ennreal.div_pos_iff.2 ⟨(tsub_pos_iff_lt.2 hε₁₂).ne', ennreal.coe_ne_top⟩], refine λ s hs, lt_of_le_of_lt _ hε₂ε, simp only [lintegral_eq_nnreal, supr_le_iff], intros ψ hψ, calc (map coe ψ).lintegral (μ.restrict s) ≤ (map coe φ).lintegral (μ.restrict s) + (map coe (ψ - φ)).lintegral (μ.restrict s) : begin rw [← simple_func.add_lintegral, ← simple_func.map_add @ennreal.coe_add], refine simple_func.lintegral_mono (λ x, _) le_rfl, simp only [add_tsub_eq_max, le_max_right, coe_map, function.comp_app, simple_func.coe_add, simple_func.coe_sub, pi.add_apply, pi.sub_apply, with_top.coe_max] end ... ≤ (map coe φ).lintegral (μ.restrict s) + ε₁ : begin refine add_le_add le_rfl (le_trans _ (hφ _ hψ).le), exact simple_func.lintegral_mono le_rfl measure.restrict_le_self end ... ≤ (simple_func.const α (C : ℝ≥0∞)).lintegral (μ.restrict s) + ε₁ : add_le_add (simple_func.lintegral_mono (λ x, coe_le_coe.2 (hC x)) le_rfl) le_rfl ... = C * μ s + ε₁ : by simp only [←simple_func.lintegral_eq_lintegral, coe_const, lintegral_const, measure.restrict_apply, measurable_set.univ, univ_inter] ... ≤ C * ((ε₂ - ε₁) / C) + ε₁ : add_le_add_right (mul_le_mul_left' hs.le _) _ ... ≤ (ε₂ - ε₁) + ε₁ : add_le_add mul_div_le le_rfl ... = ε₂ : tsub_add_cancel_of_le hε₁₂.le, end /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma tendsto_set_lintegral_zero {ι} {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {l : filter ι} {s : ι → set α} (hl : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫⁻ x in s i, f x ∂μ) l (𝓝 0) := begin simp only [ennreal.nhds_zero, tendsto_infi, tendsto_principal, mem_Iio, ← pos_iff_ne_zero] at hl ⊢, intros ε ε0, rcases exists_pos_set_lintegral_lt_of_measure_lt h ε0.ne' with ⟨δ, δ0, hδ⟩, exact (hl δ δ0).mono (λ i, hδ _) end /-- The sum of the lower Lebesgue integrals of two functions is less than or equal to the integral of their sum. The other inequality needs one of these functions to be (a.e.-)measurable. -/ lemma le_lintegral_add (f g : α → ℝ≥0∞) : ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ ≤ ∫⁻ a, f a + g a ∂μ := begin dunfold lintegral, refine ennreal.bsupr_add_bsupr_le' ⟨0, zero_le f⟩ ⟨0, zero_le g⟩ (λ f' hf' g' hg', _), exact le_supr₂_of_le (f' + g') (add_le_add hf' hg') (add_lintegral _ _).ge end -- Use stronger lemmas `lintegral_add_left`/`lintegral_add_right` instead lemma lintegral_add_aux {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, (⨆n, (eapprox f n : α → ℝ≥0∞) a) + (⨆n, (eapprox g n : α → ℝ≥0∞) a) ∂μ) : by simp only [supr_eapprox_apply, hf, hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ℝ≥0∞) a) ∂μ) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral], refl }, { measurability, }, { assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) } ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg] /-- If `f g : α → ℝ≥0∞` are two functions and one of them is (a.e.) measurable, then the Lebesgue integral of `f + g` equals the sum of integrals. This lemma assumes that `f` is integrable, see also `measure_theory.lintegral_add_right` and primed versions of these lemmas. -/ @[simp] lemma lintegral_add_left {f : α → ℝ≥0∞} (hf : measurable f) (g : α → ℝ≥0∞) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := begin refine le_antisymm _ (le_lintegral_add _ _), rcases exists_measurable_le_lintegral_eq μ (λ a, f a + g a) with ⟨φ, hφm, hφ_le, hφ_eq⟩, calc ∫⁻ a, f a + g a ∂μ = ∫⁻ a, φ a ∂μ : hφ_eq ... ≤ ∫⁻ a, f a + (φ a - f a) ∂μ : lintegral_mono (λ a, le_add_tsub) ... = ∫⁻ a, f a ∂μ + ∫⁻ a, φ a - f a ∂μ : lintegral_add_aux hf (hφm.sub hf) ... ≤ ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ : add_le_add_left (lintegral_mono $ λ a, tsub_le_iff_left.2 $ hφ_le a) _ end lemma lintegral_add_left' {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (g : α → ℝ≥0∞) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := by rw [lintegral_congr_ae hf.ae_eq_mk, ← lintegral_add_left hf.measurable_mk, lintegral_congr_ae (hf.ae_eq_mk.add (ae_eq_refl g))] lemma lintegral_add_right' (f : α → ℝ≥0∞) {g : α → ℝ≥0∞} (hg : ae_measurable g μ) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := by simpa only [add_comm] using lintegral_add_left' hg f /-- If `f g : α → ℝ≥0∞` are two functions and one of them is (a.e.) measurable, then the Lebesgue integral of `f + g` equals the sum of integrals. This lemma assumes that `g` is integrable, see also `measure_theory.lintegral_add_left` and primed versions of these lemmas. -/ @[simp] lemma lintegral_add_right (f : α → ℝ≥0∞) {g : α → ℝ≥0∞} (hg : measurable g) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := lintegral_add_right' f hg.ae_measurable @[simp] lemma lintegral_smul_measure (c : ℝ≥0∞) (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ := by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul] @[simp] lemma lintegral_sum_measure {m : measurable_space α} {ι} (f : α → ℝ≥0∞) (μ : ι → measure α) : ∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) := begin simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum], rw [supr_comm], congr, funext s, induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp }, simp only [finset.sum_insert hi, ← hs], refine (ennreal.supr_add_supr _).symm, intros φ ψ, exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩, add_le_add (simple_func.lintegral_mono le_sup_left le_rfl) (finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right le_rfl)⟩ end theorem has_sum_lintegral_measure {ι} {m : measurable_space α} (f : α → ℝ≥0∞) (μ : ι → measure α) : has_sum (λ i, ∫⁻ a, f a ∂(μ i)) (∫⁻ a, f a ∂(measure.sum μ)) := (lintegral_sum_measure f μ).symm ▸ ennreal.summable.has_sum @[simp] lemma lintegral_add_measure {m : measurable_space α} (f : α → ℝ≥0∞) (μ ν : measure α) : ∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν := by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν) @[simp] lemma lintegral_finset_sum_measure {ι} {m : measurable_space α} (s : finset ι) (f : α → ℝ≥0∞) (μ : ι → measure α) : ∫⁻ a, f a ∂(∑ i in s, μ i) = ∑ i in s, ∫⁻ a, f a ∂μ i := by { rw [← measure.sum_coe_finset, lintegral_sum_measure, ← finset.tsum_subtype'], refl } @[simp] lemma lintegral_zero_measure {m : measurable_space α} (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂(0 : measure α) = 0 := bot_unique $ by simp [lintegral] lemma set_lintegral_empty (f : α → ℝ≥0∞) : ∫⁻ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, lintegral_zero_measure] lemma set_lintegral_univ (f : α → ℝ≥0∞) : ∫⁻ x in univ, f x ∂μ = ∫⁻ x, f x ∂μ := by rw measure.restrict_univ lemma set_lintegral_measure_zero (s : set α) (f : α → ℝ≥0∞) (hs' : μ s = 0) : ∫⁻ x in s, f x ∂μ = 0 := begin convert lintegral_zero_measure _, exact measure.restrict_eq_zero.2 hs', end lemma lintegral_finset_sum' (s : finset β) {f : β → α → ℝ≥0∞} (hf : ∀ b ∈ s, ae_measurable (f b) μ) : (∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ := begin induction s using finset.induction_on with a s has ih, { simp }, { simp only [finset.sum_insert has], rw [finset.forall_mem_insert] at hf, rw [lintegral_add_left' hf.1, ih hf.2] } end lemma lintegral_finset_sum (s : finset β) {f : β → α → ℝ≥0∞} (hf : ∀ b ∈ s, measurable (f b)) : (∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ := lintegral_finset_sum' s (λ b hb, (hf b hb).ae_measurable) @[simp] lemma lintegral_const_mul (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) : by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl } ... = (⨆n, r * (eapprox f n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact mul_le_mul_left' (monotone_eapprox _ h _) _ } end ... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf] lemma lintegral_const_mul'' (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin have A : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ a, r * f a ∂μ = ∫⁻ a, r * hf.mk f a ∂μ := lintegral_congr_ae (eventually_eq.fun_comp hf.ae_eq_mk _), rw [A, B, lintegral_const_mul _ hf.measurable_mk], end lemma lintegral_const_mul_le (r : ℝ≥0∞) (f : α → ℝ≥0∞) : r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff], assume hs, rw [← simple_func.const_mul_lintegral, lintegral], refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) le_rfl), exact mul_le_mul_left' (hs x) _ end lemma lintegral_const_mul' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using mul_le_mul_left' this r end lemma lintegral_mul_const (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul r hf] lemma lintegral_mul_const'' (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul'' r hf] lemma lintegral_mul_const_le (r : ℝ≥0∞) (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ := by simp_rw [mul_comm, lintegral_const_mul_le r f] lemma lintegral_mul_const' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞): ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul' r f hr] /- A double integral of a product where each factor contains only one variable is a product of integrals -/ lemma lintegral_lintegral_mul {β} [measurable_space β] {ν : measure β} {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g ν) : ∫⁻ x, ∫⁻ y, f x * g y ∂ν ∂μ = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_const_mul'' _ hg, lintegral_mul_const'' _ hf] -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ℝ≥0∞) : (∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) := lintegral_congr_ae $ h.mono $ λ a h, by rw h -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁') (h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ℝ≥0∞) : (∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) := lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂] @[simp] lemma lintegral_indicator (f : α → ℝ≥0∞) {s : set α} (hs : measurable_set s) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := begin simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'], apply le_antisymm; refine supr_mono' (subtype.forall.2 $ λ φ hφ, _), { refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩, refine simple_func.lintegral_mono (λ x, _) le_rfl, by_cases hx : x ∈ s, { simp [hx, hs, le_refl] }, { apply le_trans (hφ x), simp [hx, hs, le_refl] } }, { refine ⟨⟨φ.restrict s, λ x, _⟩, le_rfl⟩, simp [hφ x, hs, indicator_le_indicator] } end lemma lintegral_indicator₀ (f : α → ℝ≥0∞) {s : set α} (hs : null_measurable_set s μ) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := by rw [← lintegral_congr_ae (indicator_ae_eq_of_ae_eq_set hs.to_measurable_ae_eq), lintegral_indicator _ (measurable_set_to_measurable _ _), measure.restrict_congr_set hs.to_measurable_ae_eq] lemma lintegral_indicator_const {s : set α} (hs : measurable_set s) (c : ℝ≥0∞) : ∫⁻ a, s.indicator (λ _, c) a ∂μ = c * μ s := by rw [lintegral_indicator _ hs, set_lintegral_const] lemma set_lintegral_eq_const {f : α → ℝ≥0∞} (hf : measurable f) (r : ℝ≥0∞) : ∫⁻ x in {x | f x = r}, f x ∂μ = r * μ {x | f x = r} := begin have : ∀ᵐ x ∂μ, x ∈ {x | f x = r} → f x = r := ae_of_all μ (λ _ hx, hx), rw [set_lintegral_congr_fun _ this], dsimp, rw [lintegral_const, measure.restrict_apply measurable_set.univ, set.univ_inter], exact hf (measurable_set_singleton r) end @[simp] lemma lintegral_indicator_one (hs : measurable_set s) : ∫⁻ a, s.indicator 1 a ∂μ = μ s := (lintegral_indicator_const hs _).trans $ one_mul _ /-- A version of **Markov's inequality** for two functions. It doesn't follow from the standard Markov's inequality because we only assume measurability of `g`, not `f`. -/ lemma lintegral_add_mul_meas_add_le_le_lintegral {f g : α → ℝ≥0∞} (hle : f ≤ᵐ[μ] g) (hg : ae_measurable g μ) (ε : ℝ≥0∞) : ∫⁻ a, f a ∂μ + ε * μ {x | f x + ε ≤ g x} ≤ ∫⁻ a, g a ∂μ := begin rcases exists_measurable_le_lintegral_eq μ f with ⟨φ, hφm, hφ_le, hφ_eq⟩, calc ∫⁻ x, f x ∂μ + ε * μ {x | f x + ε ≤ g x} = ∫⁻ x, φ x ∂μ + ε * μ {x | f x + ε ≤ g x} : by rw [hφ_eq] ... ≤ ∫⁻ x, φ x ∂μ + ε * μ {x | φ x + ε ≤ g x} : add_le_add_left (mul_le_mul_left' (measure_mono $ λ x, (add_le_add_right (hφ_le _) _).trans) _) _ ... = ∫⁻ x, φ x + indicator {x | φ x + ε ≤ g x} (λ _, ε) x ∂μ : begin rw [lintegral_add_left hφm, lintegral_indicator₀, set_lintegral_const], exact measurable_set_le (hφm.null_measurable.measurable'.add_const _) hg.null_measurable end ... ≤ ∫⁻ x, g x ∂μ : lintegral_mono_ae (hle.mono $ λ x hx₁, _), simp only [indicator_apply], split_ifs with hx₂, exacts [hx₂, (add_zero _).trans_le $ (hφ_le x).trans hx₁] end /-- **Markov's inequality** also known as **Chebyshev's first inequality**. -/ lemma mul_meas_ge_le_lintegral₀ {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (ε : ℝ≥0∞) : ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ := by simpa only [lintegral_zero, zero_add] using lintegral_add_mul_meas_add_le_le_lintegral (ae_of_all _ $ λ x, zero_le (f x)) hf ε /-- **Markov's inequality** also known as **Chebyshev's first inequality**. For a version assuming `ae_measurable`, see `mul_meas_ge_le_lintegral₀`. -/ lemma mul_meas_ge_le_lintegral {f : α → ℝ≥0∞} (hf : measurable f) (ε : ℝ≥0∞) : ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ := mul_meas_ge_le_lintegral₀ hf.ae_measurable ε lemma lintegral_eq_top_of_measure_eq_top_ne_zero {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (hμf : μ {x | f x = ∞} ≠ 0) : ∫⁻ x, f x ∂μ = ∞ := eq_top_iff.mpr $ calc ∞ = ∞ * μ {x | ∞ ≤ f x} : by simp [mul_eq_top, hμf] ... ≤ ∫⁻ x, f x ∂μ : mul_meas_ge_le_lintegral₀ hf ∞ lemma set_lintegral_eq_top_of_measure_eq_top_ne_zero (hf : ae_measurable f (μ.restrict s)) (hμf : μ {x ∈ s | f x = ∞} ≠ 0) : ∫⁻ x in s, f x ∂μ = ∞ := lintegral_eq_top_of_measure_eq_top_ne_zero hf $ mt (eq_bot_mono $ by { rw ←set_of_inter_eq_sep, exact measure.le_restrict_apply _ _ }) hμf lemma measure_eq_top_of_lintegral_ne_top (hf : ae_measurable f μ) (hμf : ∫⁻ x, f x ∂μ ≠ ∞) : μ {x | f x = ∞} = 0 := of_not_not $ λ h, hμf $ lintegral_eq_top_of_measure_eq_top_ne_zero hf h lemma measure_eq_top_of_set_lintegral_ne_top (hf : ae_measurable f (μ.restrict s)) (hμf : ∫⁻ x in s, f x ∂μ ≠ ∞) : μ {x ∈ s | f x = ∞} = 0 := of_not_not $ λ h, hμf $ set_lintegral_eq_top_of_measure_eq_top_ne_zero hf h /-- **Markov's inequality** also known as **Chebyshev's first inequality**. -/ lemma meas_ge_le_lintegral_div {f : α → ℝ≥0∞} (hf : ae_measurable f μ) {ε : ℝ≥0∞} (hε : ε ≠ 0) (hε' : ε ≠ ∞) : μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε := (ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $ by { rw [mul_comm], exact mul_meas_ge_le_lintegral₀ hf ε } lemma ae_eq_of_ae_le_of_lintegral_le {f g : α → ℝ≥0∞} (hfg : f ≤ᵐ[μ] g) (hf : ∫⁻ x, f x ∂μ ≠ ∞) (hg : ae_measurable g μ) (hgf : ∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ) : f =ᵐ[μ] g := begin have : ∀ n : ℕ, ∀ᵐ x ∂μ, g x < f x + n⁻¹, { intro n, simp only [ae_iff, not_lt], have : ∫⁻ x, f x ∂μ + (↑n)⁻¹ * μ {x : α | f x + n⁻¹ ≤ g x} ≤ ∫⁻ x, f x ∂μ, from (lintegral_add_mul_meas_add_le_le_lintegral hfg hg n⁻¹).trans hgf, rw [(ennreal.cancel_of_ne hf).add_le_iff_nonpos_right, nonpos_iff_eq_zero, mul_eq_zero] at this, exact this.resolve_left (ennreal.inv_ne_zero.2 (ennreal.nat_ne_top _)) }, refine hfg.mp ((ae_all_iff.2 this).mono (λ x hlt hle, hle.antisymm _)), suffices : tendsto (λ n : ℕ, f x + n⁻¹) at_top (𝓝 (f x)), from ge_of_tendsto' this (λ i, (hlt i).le), simpa only [inv_top, add_zero] using tendsto_const_nhds.add (ennreal.tendsto_inv_iff.2 ennreal.tendsto_nat_nhds_top) end @[simp] lemma lintegral_eq_zero_iff' {f : α → ℝ≥0∞} (hf : ae_measurable f μ) : ∫⁻ a, f a ∂μ = 0 ↔ f =ᵐ[μ] 0 := have ∫⁻ a : α, 0 ∂μ ≠ ∞, by simpa only [lintegral_zero] using zero_ne_top, ⟨λ h, (ae_eq_of_ae_le_of_lintegral_le (ae_of_all _ $ zero_le f) this hf (h.trans lintegral_zero.symm).le).symm, λ h, (lintegral_congr_ae h).trans lintegral_zero⟩ @[simp] lemma lintegral_eq_zero_iff {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f a ∂μ = 0 ↔ f =ᵐ[μ] 0 := lintegral_eq_zero_iff' hf.ae_measurable lemma lintegral_pos_iff_support {f : α → ℝ≥0∞} (hf : measurable f) : 0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) := by simp [pos_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support] /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ℝ≥0∞} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := let ⟨s, hs⟩ := exists_measurable_superset_of_null (ae_iff.1 (ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a, from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha), calc ∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ : lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha] ... = ⨆n, (∫⁻ a, g n a ∂μ) : lintegral_supr (assume n, measurable_const.piecewise hs.2.1 (hf n)) (monotone_nat_of_le_succ $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a ∂μ) : by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)] lemma lintegral_sub' {f g : α → ℝ≥0∞} (hg : ae_measurable g μ) (hg_fin : ∫⁻ a, g a ∂μ ≠ ∞) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := begin refine ennreal.eq_sub_of_add_eq hg_fin _, rw [← lintegral_add_right' _ hg], exact lintegral_congr_ae (h_le.mono $ λ x hx, tsub_add_cancel_of_le hx) end lemma lintegral_sub {f g : α → ℝ≥0∞} (hg : measurable g) (hg_fin : ∫⁻ a, g a ∂μ ≠ ∞) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := lintegral_sub' hg.ae_measurable hg_fin h_le lemma lintegral_sub_le' (f g : α → ℝ≥0∞) (hf : ae_measurable f μ) : ∫⁻ x, g x ∂μ - ∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x - f x ∂μ := begin rw tsub_le_iff_right, by_cases hfi : ∫⁻ x, f x ∂μ = ∞, { rw [hfi, add_top], exact le_top }, { rw [← lintegral_add_right' _ hf], exact lintegral_mono (λ x, le_tsub_add) } end lemma lintegral_sub_le (f g : α → ℝ≥0∞) (hf : measurable f) : ∫⁻ x, g x ∂μ - ∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x - f x ∂μ := lintegral_sub_le' f g hf.ae_measurable lemma lintegral_strict_mono_of_ae_le_of_frequently_ae_lt {f g : α → ℝ≥0∞} (hg : ae_measurable g μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h_le : f ≤ᵐ[μ] g) (h : ∃ᵐ x ∂μ, f x ≠ g x) : ∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ := begin contrapose! h, simp only [not_frequently, ne.def, not_not], exact ae_eq_of_ae_le_of_lintegral_le h_le hfi hg h end lemma lintegral_strict_mono_of_ae_le_of_ae_lt_on {f g : α → ℝ≥0∞} (hg : ae_measurable g μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h_le : f ≤ᵐ[μ] g) {s : set α} (hμs : μ s ≠ 0) (h : ∀ᵐ x ∂μ, x ∈ s → f x < g x) : ∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ := lintegral_strict_mono_of_ae_le_of_frequently_ae_lt hg hfi h_le $ ((frequently_ae_mem_iff.2 hμs).and_eventually h).mono $ λ x hx, (hx.2 hx.1).ne lemma lintegral_strict_mono {f g : α → ℝ≥0∞} (hμ : μ ≠ 0) (hg : ae_measurable g μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h : ∀ᵐ x ∂μ, f x < g x) : ∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ := begin rw [ne.def, ← measure.measure_univ_eq_zero] at hμ, refine lintegral_strict_mono_of_ae_le_of_ae_lt_on hg hfi (ae_le_of_ae_lt h) hμ _, simpa using h, end lemma set_lintegral_strict_mono {f g : α → ℝ≥0∞} {s : set α} (hsm : measurable_set s) (hs : μ s ≠ 0) (hg : measurable g) (hfi : ∫⁻ x in s, f x ∂μ ≠ ∞) (h : ∀ᵐ x ∂μ, x ∈ s → f x < g x) : ∫⁻ x in s, f x ∂μ < ∫⁻ x in s, g x ∂μ := lintegral_strict_mono (by simp [hs]) hg.ae_measurable hfi ((ae_restrict_iff' hsm).mpr h) /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from lintegral_mono (assume a, infi_le_of_le 0 le_rfl), have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 le_rfl, (ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $ show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from calc ∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ: (lintegral_sub (measurable_infi h_meas) (ne_top_of_le_ne_top h_fin $ lintegral_mono (assume a, infi_le _ _)) (ae_of_all _ $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ : lintegral_supr_ae (assume n, (h_meas 0).sub (h_meas n)) (assume n, (h_mono n).mono $ assume a ha, tsub_le_tsub le_rfl ha) ... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ : have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h, begin induction n with n ih, {exact le_rfl}, {exact le_trans (h n) ih} end, congr_arg supr $ funext $ assume n, lintegral_sub (h_meas _) (ne_top_of_le_ne_top h_fin $ lintegral_mono_ae $ h_mono n) (h_mono n) ... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n)) (h_anti : antitone f) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_anti n.le_succ) h_fin /-- Known as Fatou's lemma, version with `ae_measurable` functions -/ lemma lintegral_liminf_le' {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, ae_measurable (f n) μ) : ∫⁻ a, liminf (λ n, f n a) at_top ∂μ ≤ liminf (λ n, ∫⁻ a, f n a ∂μ) at_top := calc ∫⁻ a, liminf (λ n, f n a) at_top ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ : by simp only [liminf_eq_supr_infi_of_nat] ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ : lintegral_supr' (assume n, ae_measurable_binfi _ (to_countable _) h_meas) (ae_of_all μ (assume a n m hnm, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi)) ... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ : supr_mono $ λ n, le_infi₂_lintegral _ ... = at_top.liminf (λ n, ∫⁻ a, f n a ∂μ) : filter.liminf_eq_supr_infi_of_nat.symm /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n)) : ∫⁻ a, liminf (λ n, f n a) at_top ∂μ ≤ liminf (λ n, ∫⁻ a, f n a ∂μ) at_top := lintegral_liminf_le' (λ n, (h_meas n).ae_measurable) lemma limsup_lintegral_le {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ ≠ ∞) : limsup (λn, ∫⁻ a, f n a ∂μ) at_top ≤ ∫⁻ a, limsup (λn, f n a) at_top ∂μ := calc limsup (λn, ∫⁻ a, f n a ∂μ) at_top = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ : infi_mono $ assume n, supr₂_lintegral_le _ ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ : begin refine (lintegral_infi _ _ _).symm, { assume n, exact measurable_bsupr _ (to_countable _) hf_meas }, { assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) }, { refine ne_top_of_le_ne_top h_fin (lintegral_mono_ae _), refine (ae_all_iff.2 h_bound).mono (λ n hn, _), exact supr_le (λ i, supr_le $ λ hi, hn i) } end ... = ∫⁻ a, limsup (λn, f n a) at_top ∂μ : by simp only [limsup_eq_infi_supr_of_nat] /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf (λ (n : ℕ), F n a) at_top ∂μ : lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm ... ≤ liminf (λ n, ∫⁻ a, F n a ∂μ) at_top : lintegral_liminf_le hF_meas) (calc limsup (λ (n : ℕ), ∫⁻ a, F n a ∂μ) at_top ≤ ∫⁻ a, limsup (λn, F n a) at_top ∂μ : limsup_lintegral_le hF_meas h_bound h_fin ... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq) /-- Dominated convergence theorem for nonnegative functions which are just almost everywhere measurable. -/ lemma tendsto_lintegral_of_dominated_convergence' {F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀n, ae_measurable (F n) μ) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := begin have : ∀ n, ∫⁻ a, F n a ∂μ = ∫⁻ a, (hF_meas n).mk (F n) a ∂μ := λ n, lintegral_congr_ae (hF_meas n).ae_eq_mk, simp_rw this, apply tendsto_lintegral_of_dominated_convergence bound (λ n, (hF_meas n).measurable_mk) _ h_fin, { have : ∀ n, ∀ᵐ a ∂μ, (hF_meas n).mk (F n) a = F n a := λ n, (hF_meas n).ae_eq_mk.symm, have : ∀ᵐ a ∂μ, ∀ n, (hF_meas n).mk (F n) a = F n a := ae_all_iff.mpr this, filter_upwards [this, h_lim] with a H H', simp_rw H, exact H', }, { assume n, filter_upwards [h_bound n, (hF_meas n).ae_eq_mk] with a H H', rwa H' at H, }, end /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι} [l.is_countably_generated] {F : ι → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀ᶠ n in l, measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) := begin rw tendsto_iff_seq_tendsto, intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { refine h_lim.mono (λ a h_lim, _), apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } end section open encodable /-- Monotone convergence for a supremum over a directed family and indexed by a countable type -/ theorem lintegral_supr_directed_of_measurable [countable β] {f : β → α → ℝ≥0∞} (hf : ∀ b, measurable (f b)) (h_directed : directed (≤) f) : ∫⁻ a, ⨆ b, f b a ∂μ = ⨆ b, ∫⁻ a, f b a ∂μ := begin casesI nonempty_encodable β, casesI is_empty_or_nonempty β, { simp [supr_of_empty] }, inhabit β, have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) }, calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ : by simp only [this] ... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = ⨆ b, ∫⁻ a, f b a ∂μ : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_mono $ h_directed.le_sequence b) } end end /-- Monotone convergence for a supremum over a directed family and indexed by a countable type. -/ theorem lintegral_supr_directed [countable β] {f : β → α → ℝ≥0∞} (hf : ∀ b, ae_measurable (f b) μ) (h_directed : directed (≤) f) : ∫⁻ a, ⨆ b, f b a ∂μ = ⨆ b, ∫⁻ a, f b a ∂μ := begin simp_rw ←supr_apply, let p : α → (β → ennreal) → Prop := λ x f', directed has_le.le f', have hp : ∀ᵐ x ∂μ, p x (λ i, f i x), { filter_upwards with x i j, obtain ⟨z, hz₁, hz₂⟩ := h_directed i j, exact ⟨z, hz₁ x, hz₂ x⟩, }, have h_ae_seq_directed : directed has_le.le (ae_seq hf p), { intros b₁ b₂, obtain ⟨z, hz₁, hz₂⟩ := h_directed b₁ b₂, refine ⟨z, _, _⟩; { intros x, by_cases hx : x ∈ ae_seq_set hf p, { repeat { rw ae_seq.ae_seq_eq_fun_of_mem_ae_seq_set hf hx }, apply_rules [hz₁, hz₂], }, { simp only [ae_seq, hx, if_false], exact le_rfl, }, }, }, convert (lintegral_supr_directed_of_measurable (ae_seq.measurable hf p) h_ae_seq_directed) using 1, { simp_rw ←supr_apply, rw lintegral_congr_ae (ae_seq.supr hf hp).symm, }, { congr' 1, ext1 b, rw lintegral_congr_ae, symmetry, refine ae_seq.ae_seq_n_eq_fun_n_ae hf hp _, }, end end lemma lintegral_tsum [countable β] {f : β → α → ℝ≥0∞} (hf : ∀i, ae_measurable (f i) μ) : ∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum' _ (λ i _, hf i)] }, { assume b, exact finset.ae_measurable_sum _ (λ i _, hf i) }, { assume s t, use [s ∪ t], split, { exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), }, { exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } } end open measure lemma lintegral_Union₀ [countable β] {s : β → set α} (hm : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := by simp only [measure.restrict_Union_ae hd hm, lintegral_sum_measure] lemma lintegral_Union [countable β] {s : β → set α} (hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := lintegral_Union₀ (λ i, (hm i).null_measurable_set) hd.ae_disjoint f lemma lintegral_bUnion₀ {t : set β} {s : β → set α} (ht : t.countable) (hm : ∀ i ∈ t, null_measurable_set (s i) μ) (hd : t.pairwise (ae_disjoint μ on s)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i ∈ t, s i, f a ∂μ = ∑' i : t, ∫⁻ a in s i, f a ∂μ := begin haveI := ht.to_encodable, rw [bUnion_eq_Union, lintegral_Union₀ (set_coe.forall'.1 hm) (hd.subtype _ _)] end lemma lintegral_bUnion {t : set β} {s : β → set α} (ht : t.countable) (hm : ∀ i ∈ t, measurable_set (s i)) (hd : t.pairwise_disjoint s) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i ∈ t, s i, f a ∂μ = ∑' i : t, ∫⁻ a in s i, f a ∂μ := lintegral_bUnion₀ ht (λ i hi, (hm i hi).null_measurable_set) hd.ae_disjoint f lemma lintegral_bUnion_finset₀ {s : finset β} {t : β → set α} (hd : set.pairwise ↑s (ae_disjoint μ on t)) (hm : ∀ b ∈ s, null_measurable_set (t b) μ) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ b ∈ s, t b, f a ∂μ = ∑ b in s, ∫⁻ a in t b, f a ∂μ := by simp only [← finset.mem_coe, lintegral_bUnion₀ s.countable_to_set hm hd, ← s.tsum_subtype'] lemma lintegral_bUnion_finset {s : finset β} {t : β → set α} (hd : set.pairwise_disjoint ↑s t) (hm : ∀ b ∈ s, measurable_set (t b)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ b ∈ s, t b, f a ∂μ = ∑ b in s, ∫⁻ a in t b, f a ∂μ := lintegral_bUnion_finset₀ hd.ae_disjoint (λ b hb, (hm b hb).null_measurable_set) f lemma lintegral_Union_le [countable β] (s : β → set α) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ := begin rw [← lintegral_sum_measure], exact lintegral_mono' restrict_Union_le le_rfl end lemma lintegral_union {f : α → ℝ≥0∞} {A B : set α} (hB : measurable_set B) (hAB : disjoint A B) : ∫⁻ a in A ∪ B, f a ∂μ = ∫⁻ a in A, f a ∂μ + ∫⁻ a in B, f a ∂μ := by rw [restrict_union hAB hB, lintegral_add_measure] lemma lintegral_inter_add_diff {B : set α} (f : α → ℝ≥0∞) (A : set α) (hB : measurable_set B) : ∫⁻ x in A ∩ B, f x ∂μ + ∫⁻ x in A \ B, f x ∂μ = ∫⁻ x in A, f x ∂μ := by rw [← lintegral_add_measure, restrict_inter_add_diff _ hB] lemma lintegral_add_compl (f : α → ℝ≥0∞) {A : set α} (hA : measurable_set A) : ∫⁻ x in A, f x ∂μ + ∫⁻ x in Aᶜ, f x ∂μ = ∫⁻ x, f x ∂μ := by rw [← lintegral_add_measure, measure.restrict_add_restrict_compl hA] lemma lintegral_max {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) : ∫⁻ x, max (f x) (g x) ∂μ = ∫⁻ x in {x | f x ≤ g x}, g x ∂μ + ∫⁻ x in {x | g x < f x}, f x ∂μ := begin have hm : measurable_set {x | f x ≤ g x}, from measurable_set_le hf hg, rw [← lintegral_add_compl (λ x, max (f x) (g x)) hm], simp only [← compl_set_of, ← not_le], refine congr_arg2 (+) (set_lintegral_congr_fun hm _) (set_lintegral_congr_fun hm.compl _), exacts [ae_of_all _ (λ x, max_eq_right), ae_of_all _ (λ x hx, max_eq_left (not_le.1 hx).le)] end lemma set_lintegral_max {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) (s : set α) : ∫⁻ x in s, max (f x) (g x) ∂μ = ∫⁻ x in s ∩ {x | f x ≤ g x}, g x ∂μ + ∫⁻ x in s ∩ {x | g x < f x}, f x ∂μ := begin rw [lintegral_max hf hg, restrict_restrict, restrict_restrict, inter_comm s, inter_comm s], exacts [measurable_set_lt hg hf, measurable_set_le hf hg] end lemma lintegral_map {mβ : measurable_space β} {f : β → ℝ≥0∞} {g : α → β} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg], congr' with n : 1, convert simple_func.lintegral_map _ hg, ext1 x, simp only [eapprox_comp hf hg, coe_comp] end lemma lintegral_map' {mβ : measurable_space β} {f : β → ℝ≥0∞} {g : α → β} (hf : ae_measurable f (measure.map g μ)) (hg : ae_measurable g μ) : ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, f (g a) ∂μ := calc ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, hf.mk f a ∂(measure.map g μ) : lintegral_congr_ae hf.ae_eq_mk ... = ∫⁻ a, hf.mk f a ∂(measure.map (hg.mk g) μ) : by { congr' 1, exact measure.map_congr hg.ae_eq_mk } ... = ∫⁻ a, hf.mk f (hg.mk g a) ∂μ : lintegral_map hf.measurable_mk hg.measurable_mk ... = ∫⁻ a, hf.mk f (g a) ∂μ : lintegral_congr_ae $ hg.ae_eq_mk.symm.fun_comp _ ... = ∫⁻ a, f (g a) ∂μ : lintegral_congr_ae (ae_eq_comp hg hf.ae_eq_mk.symm) lemma lintegral_map_le {mβ : measurable_space β} (f : β → ℝ≥0∞) {g : α → β} (hg : measurable g) : ∫⁻ a, f a ∂(measure.map g μ) ≤ ∫⁻ a, f (g a) ∂μ := begin rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral], refine supr₂_le (λ i hi, supr_le $ λ h'i, _), refine le_supr₂_of_le (i ∘ g) (hi.comp hg) _, exact le_supr_of_le (λ x, h'i (g x)) (le_of_eq (lintegral_map hi hg)) end lemma lintegral_comp [measurable_space β] {f : β → ℝ≥0∞} {g : α → β} (hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) := (lintegral_map hf hg).symm lemma set_lintegral_map [measurable_space β] {f : β → ℝ≥0∞} {g : α → β} {s : set β} (hs : measurable_set s) (hf : measurable f) (hg : measurable g) : ∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] lemma lintegral_indicator_const_comp {mβ : measurable_space β} {f : α → β} {s : set β} (hf : measurable f) (hs : measurable_set s) (c : ℝ≥0∞) : ∫⁻ a, s.indicator (λ _, c) (f a) ∂μ = c * μ (f ⁻¹' s) := by rw [lintegral_comp (measurable_const.indicator hs) hf, lintegral_indicator_const hs, measure.map_apply hf hs] /-- If `g : α → β` is a measurable embedding and `f : β → ℝ≥0∞` is any function (not necessarily measurable), then `∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ`. Compare with `lintegral_map` wich applies to any measurable `g : α → β` but requires that `f` is measurable as well. -/ lemma _root_.measurable_embedding.lintegral_map [measurable_space β] {g : α → β} (hg : measurable_embedding g) (f : β → ℝ≥0∞) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin rw [lintegral, lintegral], refine le_antisymm (supr₂_le $ λ f₀ hf₀, _) (supr₂_le $ λ f₀ hf₀, _), { rw [simple_func.lintegral_map _ hg.measurable], have : (f₀.comp g hg.measurable : α → ℝ≥0∞) ≤ f ∘ g, from λ x, hf₀ (g x), exact le_supr_of_le (comp f₀ g hg.measurable) (le_supr _ this) }, { rw [← f₀.extend_comp_eq hg (const _ 0), ← simple_func.lintegral_map, ← simple_func.lintegral_eq_lintegral, ← lintegral], refine lintegral_mono_ae (hg.ae_map_iff.2 $ eventually_of_forall $ λ x, _), exact (extend_apply _ _ _ _).trans_le (hf₀ _) } end /-- The `lintegral` transforms appropriately under a measurable equivalence `g : α ≃ᵐ β`. (Compare `lintegral_map`, which applies to a wider class of functions `g : α → β`, but requires measurability of the function being integrated.) -/ lemma lintegral_map_equiv [measurable_space β] (f : β → ℝ≥0∞) (g : α ≃ᵐ β) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := g.measurable_embedding.lintegral_map f lemma measure_preserving.lintegral_comp {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) {f : β → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν := by rw [← hg.map_eq, lintegral_map hf hg.measurable] lemma measure_preserving.lintegral_comp_emb {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞) : ∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν := by rw [← hg.map_eq, hge.lintegral_map] lemma measure_preserving.set_lintegral_comp_preimage {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) {s : set β} (hs : measurable_set s) {f : β → ℝ≥0∞} (hf : measurable f) : ∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν := by rw [← hg.map_eq, set_lintegral_map hs hf hg.measurable] lemma measure_preserving.set_lintegral_comp_preimage_emb {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞) (s : set β) : ∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν := by rw [← hg.map_eq, hge.restrict_map, hge.lintegral_map] lemma measure_preserving.set_lintegral_comp_emb {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞) (s : set α) : ∫⁻ a in s, f (g a) ∂μ = ∫⁻ b in g '' s, f b ∂ν := by rw [← hg.set_lintegral_comp_preimage_emb hge, preimage_image_eq _ hge.injective] section dirac_and_count @[priority 10] instance _root_.measurable_space.top.measurable_singleton_class {α : Type*} : @measurable_singleton_class α (⊤ : measurable_space α) := { measurable_set_singleton := λ i, measurable_space.measurable_set_top, } variable [measurable_space α] lemma lintegral_dirac' (a : α) {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (ae_eq_dirac' hf)] lemma lintegral_dirac [measurable_singleton_class α] (a : α) (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (ae_eq_dirac f)] lemma set_lintegral_dirac' {a : α} {f : α → ℝ≥0∞} (hf : measurable f) {s : set α} (hs : measurable_set s) [decidable (a ∈ s)] : ∫⁻ x in s, f x ∂(measure.dirac a) = if a ∈ s then f a else 0 := begin rw [restrict_dirac' hs], swap, { apply_instance, }, split_ifs, { exact lintegral_dirac' _ hf, }, { exact lintegral_zero_measure _, }, end lemma set_lintegral_dirac {a : α} (f : α → ℝ≥0∞) (s : set α) [measurable_singleton_class α] [decidable (a ∈ s)] : ∫⁻ x in s, f x ∂(measure.dirac a) = if a ∈ s then f a else 0 := begin rw [restrict_dirac], split_ifs, { exact lintegral_dirac _ _, }, { exact lintegral_zero_measure _, }, end lemma lintegral_count' {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f a ∂count = ∑' a, f a := begin rw [count, lintegral_sum_measure], congr, exact funext (λ a, lintegral_dirac' a hf), end lemma lintegral_count [measurable_singleton_class α] (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂count = ∑' a, f a := begin rw [count, lintegral_sum_measure], congr, exact funext (λ a, lintegral_dirac a f), end lemma _root_.ennreal.tsum_const_eq [measurable_singleton_class α] (c : ℝ≥0∞) : (∑' (i : α), c) = c * (measure.count (univ : set α)) := by rw [← lintegral_count, lintegral_const] /-- Markov's inequality for the counting measure with hypothesis using `tsum` in `ℝ≥0∞`. -/ lemma _root_.ennreal.count_const_le_le_of_tsum_le [measurable_singleton_class α] {a : α → ℝ≥0∞} (a_mble : measurable a) {c : ℝ≥0∞} (tsum_le_c : ∑' i, a i ≤ c) {ε : ℝ≥0∞} (ε_ne_zero : ε ≠ 0) (ε_ne_top : ε ≠ ∞) : measure.count {i : α | ε ≤ a i} ≤ c / ε := begin rw ← lintegral_count at tsum_le_c, apply (measure_theory.meas_ge_le_lintegral_div a_mble.ae_measurable ε_ne_zero ε_ne_top).trans, exact ennreal.div_le_div tsum_le_c rfl.le, end /-- Markov's inequality for counting measure with hypothesis using `tsum` in `ℝ≥0`. -/ lemma _root_.nnreal.count_const_le_le_of_tsum_le [measurable_singleton_class α] {a : α → ℝ≥0} (a_mble : measurable a) (a_summable : summable a) {c : ℝ≥0} (tsum_le_c : ∑' i, a i ≤ c) {ε : ℝ≥0} (ε_ne_zero : ε ≠ 0) : measure.count {i : α | ε ≤ a i} ≤ c / ε := begin rw [show (λ i, ε ≤ a i) = (λ i, (ε : ℝ≥0∞) ≤ (coe ∘ a) i), by { funext i, simp only [ennreal.coe_le_coe], }], apply ennreal.count_const_le_le_of_tsum_le (measurable_coe_nnreal_ennreal.comp a_mble) _ (by exact_mod_cast ε_ne_zero) (@ennreal.coe_ne_top ε), convert ennreal.coe_le_coe.mpr tsum_le_c, rw ennreal.tsum_coe_eq a_summable.has_sum, end end dirac_and_count section countable /-! ### Lebesgue integral over finite and countable types and sets -/ lemma lintegral_countable' [countable α] [measurable_singleton_class α] (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂μ = ∑' a, f a * μ {a} := begin conv_lhs { rw [← sum_smul_dirac μ, lintegral_sum_measure] }, congr' 1 with a : 1, rw [lintegral_smul_measure, lintegral_dirac, mul_comm], end lemma lintegral_singleton' {f : α → ℝ≥0∞} (hf : measurable f) (a : α) : ∫⁻ x in {a}, f x ∂μ = f a * μ {a} := by simp only [restrict_singleton, lintegral_smul_measure, lintegral_dirac' _ hf, mul_comm] lemma lintegral_singleton [measurable_singleton_class α] (f : α → ℝ≥0∞) (a : α) : ∫⁻ x in {a}, f x ∂μ = f a * μ {a} := by simp only [restrict_singleton, lintegral_smul_measure, lintegral_dirac, mul_comm] lemma lintegral_countable [measurable_singleton_class α] (f : α → ℝ≥0∞) {s : set α} (hs : s.countable) : ∫⁻ a in s, f a ∂μ = ∑' a : s, f a * μ {(a : α)} := calc ∫⁻ a in s, f a ∂μ = ∫⁻ a in ⋃ x ∈ s, {x}, f a ∂μ : by rw [bUnion_of_singleton] ... = ∑' a : s, ∫⁻ x in {a}, f x ∂μ : lintegral_bUnion hs (λ _ _, measurable_set_singleton _) (pairwise_disjoint_fiber id s) _ ... = ∑' a : s, f a * μ {(a : α)} : by simp only [lintegral_singleton] lemma lintegral_insert [measurable_singleton_class α] {a : α} {s : set α} (h : a ∉ s) (f : α → ℝ≥0∞) : ∫⁻ x in insert a s, f x ∂μ = f a * μ {a} + ∫⁻ x in s, f x ∂μ := begin rw [← union_singleton, lintegral_union (measurable_set_singleton a), lintegral_singleton, add_comm], rwa disjoint_singleton_right end lemma lintegral_finset [measurable_singleton_class α] (s : finset α) (f : α → ℝ≥0∞) : ∫⁻ x in s, f x ∂μ = ∑ x in s, f x * μ {x} := by simp only [lintegral_countable _ s.countable_to_set, ← s.tsum_subtype'] lemma lintegral_fintype [measurable_singleton_class α] [fintype α] (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = ∑ x, f x * μ {x} := by rw [← lintegral_finset, finset.coe_univ, measure.restrict_univ] lemma lintegral_unique [unique α] (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = f default * μ univ := calc ∫⁻ x, f x ∂μ = ∫⁻ x, f default ∂μ : lintegral_congr $ unique.forall_iff.2 rfl ... = f default * μ univ : lintegral_const _ end countable lemma ae_lt_top {f : α → ℝ≥0∞} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ ≠ ∞) : ∀ᵐ x ∂μ, f x < ∞ := begin simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, apply h2f.lt_top.not_le, have : (f ⁻¹' {∞}).indicator ⊤ ≤ f, { intro x, by_cases hx : x ∈ f ⁻¹' {∞}; [simpa [hx], simp [hx]] }, convert lintegral_mono this, rw [lintegral_indicator _ (hf (measurable_set_singleton ∞))], simp [ennreal.top_mul, preimage, h] end lemma ae_lt_top' {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (h2f : ∫⁻ x, f x ∂μ ≠ ∞) : ∀ᵐ x ∂μ, f x < ∞ := begin have h2f_meas : ∫⁻ x, hf.mk f x ∂μ ≠ ∞, by rwa ← lintegral_congr_ae hf.ae_eq_mk, exact (ae_lt_top hf.measurable_mk h2f_meas).mp (hf.ae_eq_mk.mono (λ x hx h, by rwa hx)), end lemma set_lintegral_lt_top_of_bdd_above {s : set α} (hs : μ s ≠ ∞) {f : α → ℝ≥0} (hf : measurable f) (hbdd : bdd_above (f '' s)) : ∫⁻ x in s, f x ∂μ < ∞ := begin obtain ⟨M, hM⟩ := hbdd, rw mem_upper_bounds at hM, refine lt_of_le_of_lt (set_lintegral_mono hf.coe_nnreal_ennreal (@measurable_const _ _ _ _ ↑M) _) _, { simpa using hM }, { rw lintegral_const, refine ennreal.mul_lt_top ennreal.coe_lt_top.ne _, simp [hs] } end lemma set_lintegral_lt_top_of_is_compact [topological_space α] [opens_measurable_space α] {s : set α} (hs : μ s ≠ ∞) (hsc : is_compact s) {f : α → ℝ≥0} (hf : continuous f) : ∫⁻ x in s, f x ∂μ < ∞ := set_lintegral_lt_top_of_bdd_above hs hf.measurable (hsc.image hf).bdd_above lemma _root_.is_finite_measure.lintegral_lt_top_of_bounded_to_ennreal {α : Type*} [measurable_space α] (μ : measure α) [μ_fin : is_finite_measure μ] {f : α → ℝ≥0∞} (f_bdd : ∃ c : ℝ≥0, ∀ x, f x ≤ c) : ∫⁻ x, f x ∂μ < ∞ := begin cases f_bdd with c hc, apply lt_of_le_of_lt (@lintegral_mono _ _ μ _ _ hc), rw lintegral_const, exact ennreal.mul_lt_top ennreal.coe_lt_top.ne μ_fin.measure_univ_lt_top.ne, end /-- Given a measure `μ : measure α` and a function `f : α → ℝ≥0∞`, `μ.with_density f` is the measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/ def measure.with_density {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : measure α := measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _) @[simp] lemma with_density_apply (f : α → ℝ≥0∞) {s : set α} (hs : measurable_set s) : μ.with_density f s = ∫⁻ a in s, f a ∂μ := measure.of_measurable_apply s hs lemma with_density_congr_ae {f g : α → ℝ≥0∞} (h : f =ᵐ[μ] g) : μ.with_density f = μ.with_density g := begin apply measure.ext (λ s hs, _), rw [with_density_apply _ hs, with_density_apply _ hs], exact lintegral_congr_ae (ae_restrict_of_ae h) end lemma with_density_add_left {f : α → ℝ≥0∞} (hf : measurable f) (g : α → ℝ≥0∞) : μ.with_density (f + g) = μ.with_density f + μ.with_density g := begin refine measure.ext (λ s hs, _), rw [with_density_apply _ hs, measure.add_apply, with_density_apply _ hs, with_density_apply _ hs, ← lintegral_add_left hf], refl, end lemma with_density_add_right (f : α → ℝ≥0∞) {g : α → ℝ≥0∞} (hg : measurable g) : μ.with_density (f + g) = μ.with_density f + μ.with_density g := by simpa only [add_comm] using with_density_add_left hg f lemma with_density_add_measure {m : measurable_space α} (μ ν : measure α) (f : α → ℝ≥0∞) : (μ + ν).with_density f = μ.with_density f + ν.with_density f := begin ext1 s hs, simp only [with_density_apply f hs, restrict_add, lintegral_add_measure, measure.add_apply], end lemma with_density_sum {ι : Type*} {m : measurable_space α} (μ : ι → measure α) (f : α → ℝ≥0∞) : (sum μ).with_density f = sum (λ n, (μ n).with_density f) := begin ext1 s hs, simp_rw [sum_apply _ hs, with_density_apply f hs, restrict_sum μ hs, lintegral_sum_measure], end lemma with_density_smul (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) : μ.with_density (r • f) = r • μ.with_density f := begin refine measure.ext (λ s hs, _), rw [with_density_apply _ hs, measure.coe_smul, pi.smul_apply, with_density_apply _ hs, smul_eq_mul, ← lintegral_const_mul r hf], refl, end lemma with_density_smul' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞) : μ.with_density (r • f) = r • μ.with_density f := begin refine measure.ext (λ s hs, _), rw [with_density_apply _ hs, measure.coe_smul, pi.smul_apply, with_density_apply _ hs, smul_eq_mul, ← lintegral_const_mul' r f hr], refl, end lemma is_finite_measure_with_density {f : α → ℝ≥0∞} (hf : ∫⁻ a, f a ∂μ ≠ ∞) : is_finite_measure (μ.with_density f) := { measure_univ_lt_top := by rwa [with_density_apply _ measurable_set.univ, measure.restrict_univ, lt_top_iff_ne_top] } lemma with_density_absolutely_continuous {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : μ.with_density f ≪ μ := begin refine absolutely_continuous.mk (λ s hs₁ hs₂, _), rw with_density_apply _ hs₁, exact set_lintegral_measure_zero _ _ hs₂ end @[simp] lemma with_density_zero : μ.with_density 0 = 0 := begin ext1 s hs, simp [with_density_apply _ hs], end @[simp] lemma with_density_one : μ.with_density 1 = μ := begin ext1 s hs, simp [with_density_apply _ hs], end lemma with_density_tsum {f : ℕ → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : μ.with_density (∑' n, f n) = sum (λ n, μ.with_density (f n)) := begin ext1 s hs, simp_rw [sum_apply _ hs, with_density_apply _ hs], change ∫⁻ x in s, (∑' n, f n) x ∂μ = ∑' (i : ℕ), ∫⁻ x, f i x ∂(μ.restrict s), rw ← lintegral_tsum (λ i, (h i).ae_measurable), refine lintegral_congr (λ x, tsum_apply (pi.summable.2 (λ _, ennreal.summable))), end lemma with_density_indicator {s : set α} (hs : measurable_set s) (f : α → ℝ≥0∞) : μ.with_density (s.indicator f) = (μ.restrict s).with_density f := begin ext1 t ht, rw [with_density_apply _ ht, lintegral_indicator _ hs, restrict_comm hs, ← with_density_apply _ ht] end lemma with_density_indicator_one {s : set α} (hs : measurable_set s) : μ.with_density (s.indicator 1) = μ.restrict s := by rw [with_density_indicator hs, with_density_one] lemma with_density_of_real_mutually_singular {f : α → ℝ} (hf : measurable f) : μ.with_density (λ x, ennreal.of_real $ f x) ⟂ₘ μ.with_density (λ x, ennreal.of_real $ -f x) := begin set S : set α := { x | f x < 0 } with hSdef, have hS : measurable_set S := measurable_set_lt hf measurable_const, refine ⟨S, hS, _, _⟩, { rw [with_density_apply _ hS, lintegral_eq_zero_iff hf.ennreal_of_real, eventually_eq], exact (ae_restrict_mem hS).mono (λ x hx, ennreal.of_real_eq_zero.2 (le_of_lt hx)) }, { rw [with_density_apply _ hS.compl, lintegral_eq_zero_iff hf.neg.ennreal_of_real, eventually_eq], exact (ae_restrict_mem hS.compl).mono (λ x hx, ennreal.of_real_eq_zero.2 (not_lt.1 $ mt neg_pos.1 hx)) }, end lemma restrict_with_density {s : set α} (hs : measurable_set s) (f : α → ℝ≥0∞) : (μ.with_density f).restrict s = (μ.restrict s).with_density f := begin ext1 t ht, rw [restrict_apply ht, with_density_apply _ ht, with_density_apply _ (ht.inter hs), restrict_restrict ht], end lemma with_density_eq_zero {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (h : μ.with_density f = 0) : f =ᵐ[μ] 0 := by rw [← lintegral_eq_zero_iff' hf, ← set_lintegral_univ, ← with_density_apply _ measurable_set.univ, h, measure.coe_zero, pi.zero_apply] lemma with_density_apply_eq_zero {f : α → ℝ≥0∞} {s : set α} (hf : measurable f) : μ.with_density f s = 0 ↔ μ ({x | f x ≠ 0} ∩ s) = 0 := begin split, { assume hs, let t := to_measurable (μ.with_density f) s, apply measure_mono_null (inter_subset_inter_right _ (subset_to_measurable (μ.with_density f) s)), have A : μ.with_density f t = 0, by rw [measure_to_measurable, hs], rw [with_density_apply f (measurable_set_to_measurable _ s), lintegral_eq_zero_iff hf, eventually_eq, ae_restrict_iff, ae_iff] at A, swap, { exact hf (measurable_set_singleton 0) }, simp only [pi.zero_apply, mem_set_of_eq, filter.mem_mk] at A, convert A, ext x, simp only [and_comm, exists_prop, mem_inter_iff, iff_self, mem_set_of_eq, mem_compl_iff, not_forall] }, { assume hs, let t := to_measurable μ ({x | f x ≠ 0} ∩ s), have A : s ⊆ t ∪ {x | f x = 0}, { assume x hx, rcases eq_or_ne (f x) 0 with fx|fx, { simp only [fx, mem_union, mem_set_of_eq, eq_self_iff_true, or_true] }, { left, apply subset_to_measurable _ _, exact ⟨fx, hx⟩ } }, apply measure_mono_null A (measure_union_null _ _), { apply with_density_absolutely_continuous, rwa measure_to_measurable }, { have M : measurable_set {x : α | f x = 0} := hf (measurable_set_singleton _), rw [with_density_apply _ M, (lintegral_eq_zero_iff hf)], filter_upwards [ae_restrict_mem M], simp only [imp_self, pi.zero_apply, implies_true_iff] } } end lemma ae_with_density_iff {p : α → Prop} {f : α → ℝ≥0∞} (hf : measurable f) : (∀ᵐ x ∂(μ.with_density f), p x) ↔ ∀ᵐ x ∂μ, f x ≠ 0 → p x := begin rw [ae_iff, ae_iff, with_density_apply_eq_zero hf], congr', ext x, simp only [exists_prop, mem_inter_iff, iff_self, mem_set_of_eq, not_forall], end lemma ae_with_density_iff_ae_restrict {p : α → Prop} {f : α → ℝ≥0∞} (hf : measurable f) : (∀ᵐ x ∂(μ.with_density f), p x) ↔ (∀ᵐ x ∂(μ.restrict {x | f x ≠ 0}), p x) := begin rw [ae_with_density_iff hf, ae_restrict_iff'], { refl }, { exact hf (measurable_set_singleton 0).compl }, end lemma ae_measurable_with_density_ennreal_iff {f : α → ℝ≥0} (hf : measurable f) {g : α → ℝ≥0∞} : ae_measurable g (μ.with_density (λ x, (f x : ℝ≥0∞))) ↔ ae_measurable (λ x, (f x : ℝ≥0∞) * g x) μ := begin split, { rintros ⟨g', g'meas, hg'⟩, have A : measurable_set {x : α | f x ≠ 0} := (hf (measurable_set_singleton 0)).compl, refine ⟨λ x, f x * g' x, hf.coe_nnreal_ennreal.smul g'meas, _⟩, apply ae_of_ae_restrict_of_ae_restrict_compl {x | f x ≠ 0}, { rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal] at hg', rw ae_restrict_iff' A, filter_upwards [hg'], assume a ha h'a, have : (f a : ℝ≥0∞) ≠ 0, by simpa only [ne.def, coe_eq_zero] using h'a, rw ha this }, { filter_upwards [ae_restrict_mem A.compl], assume x hx, simp only [not_not, mem_set_of_eq, mem_compl_iff] at hx, simp [hx] } }, { rintros ⟨g', g'meas, hg'⟩, refine ⟨λ x, (f x)⁻¹ * g' x, hf.coe_nnreal_ennreal.inv.smul g'meas, _⟩, rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal], filter_upwards [hg'], assume x hx h'x, rw [← hx, ← mul_assoc, ennreal.inv_mul_cancel h'x ennreal.coe_ne_top, one_mul] } end end lintegral open measure_theory.simple_func variables {m m0 : measurable_space α} include m /-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density function, and `(μ.with_density f)` represents any continuous random variable as a probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution, the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4 of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances, and other moments as a function of the probability density function. -/ lemma lintegral_with_density_eq_lintegral_mul (μ : measure α) {f : α → ℝ≥0∞} (h_mf : measurable f) : ∀ {g : α → ℝ≥0∞}, measurable g → ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin apply measurable.ennreal_induction, { intros c s h_ms, simp [*, mul_comm _ c, ← indicator_mul_right], }, { intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h, simp [mul_add, *, measurable.mul] }, { intros g h_mea_g h_mono_g h_ind, have : monotone (λ n a, f a * g n a) := λ m n hmn x, mul_le_mul_left' (h_mono_g hmn x) _, simp [lintegral_supr, ennreal.mul_supr, h_mf.mul (h_mea_g _), *] } end lemma set_lintegral_with_density_eq_set_lintegral_mul (μ : measure α) {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) {s : set α} (hs : measurable_set s) : ∫⁻ x in s, g x ∂μ.with_density f = ∫⁻ x in s, (f * g) x ∂μ := by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul _ hf hg] /-- The Lebesgue integral of `g` with respect to the measure `μ.with_density f` coincides with the integral of `f * g`. This version assumes that `g` is almost everywhere measurable. For a version without conditions on `g` but requiring that `f` is almost everywhere finite, see `lintegral_with_density_eq_lintegral_mul_non_measurable` -/ lemma lintegral_with_density_eq_lintegral_mul₀' {μ : measure α} {f : α → ℝ≥0∞} (hf : ae_measurable f μ) {g : α → ℝ≥0∞} (hg : ae_measurable g (μ.with_density f)) : ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin let f' := hf.mk f, have : μ.with_density f = μ.with_density f' := with_density_congr_ae hf.ae_eq_mk, rw this at ⊢ hg, let g' := hg.mk g, calc ∫⁻ a, g a ∂(μ.with_density f') = ∫⁻ a, g' a ∂(μ.with_density f') : lintegral_congr_ae hg.ae_eq_mk ... = ∫⁻ a, (f' * g') a ∂μ : lintegral_with_density_eq_lintegral_mul _ hf.measurable_mk hg.measurable_mk ... = ∫⁻ a, (f' * g) a ∂μ : begin apply lintegral_congr_ae, apply ae_of_ae_restrict_of_ae_restrict_compl {x | f' x ≠ 0}, { have Z := hg.ae_eq_mk, rw [eventually_eq, ae_with_density_iff_ae_restrict hf.measurable_mk] at Z, filter_upwards [Z], assume x hx, simp only [hx, pi.mul_apply] }, { have M : measurable_set {x : α | f' x ≠ 0}ᶜ := (hf.measurable_mk (measurable_set_singleton 0).compl).compl, filter_upwards [ae_restrict_mem M], assume x hx, simp only [not_not, mem_set_of_eq, mem_compl_iff] at hx, simp only [hx, zero_mul, pi.mul_apply] } end ... = ∫⁻ (a : α), (f * g) a ∂μ : begin apply lintegral_congr_ae, filter_upwards [hf.ae_eq_mk], assume x hx, simp only [hx, pi.mul_apply], end end lemma lintegral_with_density_eq_lintegral_mul₀ {μ : measure α} {f : α → ℝ≥0∞} (hf : ae_measurable f μ) {g : α → ℝ≥0∞} (hg : ae_measurable g μ) : ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := lintegral_with_density_eq_lintegral_mul₀' hf (hg.mono' (with_density_absolutely_continuous μ f)) lemma lintegral_with_density_le_lintegral_mul (μ : measure α) {f : α → ℝ≥0∞} (f_meas : measurable f) (g : α → ℝ≥0∞) : ∫⁻ a, g a ∂(μ.with_density f) ≤ ∫⁻ a, (f * g) a ∂μ := begin rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral], refine supr₂_le (λ i i_meas, supr_le (λ hi, _)), have A : f * i ≤ f * g := λ x, mul_le_mul_left' (hi x) _, refine le_supr₂_of_le (f * i) (f_meas.mul i_meas) _, exact le_supr_of_le A (le_of_eq (lintegral_with_density_eq_lintegral_mul _ f_meas i_meas)) end lemma lintegral_with_density_eq_lintegral_mul_non_measurable (μ : measure α) {f : α → ℝ≥0∞} (f_meas : measurable f) (hf : ∀ᵐ x ∂μ, f x < ∞) (g : α → ℝ≥0∞) : ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin refine le_antisymm (lintegral_with_density_le_lintegral_mul μ f_meas g) _, rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral], refine supr₂_le (λ i i_meas, supr_le $ λ hi, _), have A : (λ x, (f x)⁻¹ * i x) ≤ g, { assume x, dsimp, rw [mul_comm, ← div_eq_mul_inv], exact div_le_of_le_mul' (hi x), }, refine le_supr_of_le (λ x, (f x)⁻¹ * i x) (le_supr_of_le (f_meas.inv.mul i_meas) _), refine le_supr_of_le A _, rw lintegral_with_density_eq_lintegral_mul _ f_meas (f_meas.inv.mul i_meas), apply lintegral_mono_ae, filter_upwards [hf], assume x h'x, rcases eq_or_ne (f x) 0 with hx|hx, { have := hi x, simp only [hx, zero_mul, pi.mul_apply, nonpos_iff_eq_zero] at this, simp [this] }, { apply le_of_eq _, dsimp, rw [← mul_assoc, ennreal.mul_inv_cancel hx h'x.ne, one_mul] } end lemma set_lintegral_with_density_eq_set_lintegral_mul_non_measurable (μ : measure α) {f : α → ℝ≥0∞} (f_meas : measurable f) (g : α → ℝ≥0∞) {s : set α} (hs : measurable_set s) (hf : ∀ᵐ x ∂(μ.restrict s), f x < ∞) : ∫⁻ a in s, g a ∂(μ.with_density f) = ∫⁻ a in s, (f * g) a ∂μ := by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul_non_measurable _ f_meas hf] lemma lintegral_with_density_eq_lintegral_mul_non_measurable₀ (μ : measure α) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (h'f : ∀ᵐ x ∂μ, f x < ∞) (g : α → ℝ≥0∞) : ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin let f' := hf.mk f, calc ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, g a ∂(μ.with_density f') : by rw with_density_congr_ae hf.ae_eq_mk ... = ∫⁻ a, (f' * g) a ∂μ : begin apply lintegral_with_density_eq_lintegral_mul_non_measurable _ hf.measurable_mk, filter_upwards [h'f, hf.ae_eq_mk], assume x hx h'x, rwa ← h'x, end ... = ∫⁻ a, (f * g) a ∂μ : begin apply lintegral_congr_ae, filter_upwards [hf.ae_eq_mk], assume x hx, simp only [hx, pi.mul_apply], end end lemma set_lintegral_with_density_eq_set_lintegral_mul_non_measurable₀ (μ : measure α) {f : α → ℝ≥0∞} {s : set α} (hf : ae_measurable f (μ.restrict s)) (g : α → ℝ≥0∞) (hs : measurable_set s) (h'f : ∀ᵐ x ∂(μ.restrict s), f x < ∞) : ∫⁻ a in s, g a ∂(μ.with_density f) = ∫⁻ a in s, (f * g) a ∂μ := by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul_non_measurable₀ _ hf h'f] lemma with_density_mul (μ : measure α) {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) : μ.with_density (f * g) = (μ.with_density f).with_density g := begin ext1 s hs, simp [with_density_apply _ hs, restrict_with_density hs, lintegral_with_density_eq_lintegral_mul _ hf hg], end /-- In a sigma-finite measure space, there exists an integrable function which is positive everywhere (and with an arbitrarily small integral). -/ lemma exists_pos_lintegral_lt_of_sigma_finite (μ : measure α) [sigma_finite μ] {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, 0 < g x) ∧ measurable g ∧ (∫⁻ x, g x ∂μ < ε) := begin /- Let `s` be a covering of `α` by pairwise disjoint measurable sets of finite measure. Let `δ : ℕ → ℝ≥0` be a positive function such that `∑' i, μ (s i) * δ i < ε`. Then the function that is equal to `δ n` on `s n` is a positive function with integral less than `ε`. -/ set s : ℕ → set α := disjointed (spanning_sets μ), have : ∀ n, μ (s n) < ∞, from λ n, (measure_mono $ disjointed_subset _ _).trans_lt (measure_spanning_sets_lt_top μ n), obtain ⟨δ, δpos, δsum⟩ : ∃ δ : ℕ → ℝ≥0, (∀ i, 0 < δ i) ∧ ∑' i, μ (s i) * δ i < ε, from ennreal.exists_pos_tsum_mul_lt_of_countable ε0 _ (λ n, (this n).ne), set N : α → ℕ := spanning_sets_index μ, have hN_meas : measurable N := measurable_spanning_sets_index μ, have hNs : ∀ n, N ⁻¹' {n} = s n := preimage_spanning_sets_index_singleton μ, refine ⟨δ ∘ N, λ x, δpos _, measurable_from_nat.comp hN_meas, _⟩, simpa [lintegral_comp measurable_from_nat.coe_nnreal_ennreal hN_meas, hNs, lintegral_countable', measurable_spanning_sets_index, mul_comm] using δsum, end lemma lintegral_trim {μ : measure α} (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : measurable[m] f) : ∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ := begin refine @measurable.ennreal_induction α m (λ f, ∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ) _ _ _ f hf, { intros c s hs, rw [lintegral_indicator _ hs, lintegral_indicator _ (hm s hs), set_lintegral_const, set_lintegral_const], suffices h_trim_s : μ.trim hm s = μ s, by rw h_trim_s, exact trim_measurable_set_eq hm hs, }, { intros f g hfg hf hg hf_prop hg_prop, have h_m := lintegral_add_left hf g, have h_m0 := lintegral_add_left (measurable.mono hf hm le_rfl) g, rwa [hf_prop, hg_prop, ← h_m0] at h_m, }, { intros f hf hf_mono hf_prop, rw lintegral_supr hf hf_mono, rw lintegral_supr (λ n, measurable.mono (hf n) hm le_rfl) hf_mono, congr, exact funext (λ n, hf_prop n), }, end lemma lintegral_trim_ae {μ : measure α} (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : ae_measurable f (μ.trim hm)) : ∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ := by rw [lintegral_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk), lintegral_congr_ae hf.ae_eq_mk, lintegral_trim hm hf.measurable_mk] section sigma_finite variables {E : Type*} [normed_add_comm_group E] [measurable_space E] [opens_measurable_space E] lemma univ_le_of_forall_fin_meas_le {μ : measure α} (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (C : ℝ≥0∞) {f : set α → ℝ≥0∞} (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → f s ≤ C) (h_F_lim : ∀ S : ℕ → set α, (∀ n, measurable_set[m] (S n)) → monotone S → f (⋃ n, S n) ≤ ⨆ n, f (S n)) : f univ ≤ C := begin let S := @spanning_sets _ m (μ.trim hm) _, have hS_mono : monotone S, from @monotone_spanning_sets _ m (μ.trim hm) _, have hS_meas : ∀ n, measurable_set[m] (S n), from @measurable_spanning_sets _ m (μ.trim hm) _, rw ← @Union_spanning_sets _ m (μ.trim hm), refine (h_F_lim S hS_meas hS_mono).trans _, refine supr_le (λ n, hf (S n) (hS_meas n) _), exact ((le_trim hm).trans_lt (@measure_spanning_sets_lt_top _ m (μ.trim hm) _ n)).ne, end /-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite measure in a sub-σ-algebra and the measure is σ-finite on that sub-σ-algebra, then the integral over the whole space is bounded by that same constant. Version for a measurable function. See `lintegral_le_of_forall_fin_meas_le'` for the more general `ae_measurable` version. -/ lemma lintegral_le_of_forall_fin_meas_le_of_measurable {μ : measure α} (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (C : ℝ≥0∞) {f : α → ℝ≥0∞} (hf_meas : measurable f) (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) : ∫⁻ x, f x ∂μ ≤ C := begin have : ∫⁻ x in univ, f x ∂μ = ∫⁻ x, f x ∂μ, by simp only [measure.restrict_univ], rw ← this, refine univ_le_of_forall_fin_meas_le hm C hf (λ S hS_meas hS_mono, _), rw ← lintegral_indicator, swap, { exact hm (⋃ n, S n) (@measurable_set.Union _ _ m _ _ hS_meas), }, have h_integral_indicator : (⨆ n, ∫⁻ x in S n, f x ∂μ) = ⨆ n, ∫⁻ x, (S n).indicator f x ∂μ, { congr, ext1 n, rw lintegral_indicator _ (hm _ (hS_meas n)), }, rw [h_integral_indicator, ← lintegral_supr], { refine le_of_eq (lintegral_congr (λ x, _)), simp_rw indicator_apply, by_cases hx_mem : x ∈ Union S, { simp only [hx_mem, if_true], obtain ⟨n, hxn⟩ := mem_Union.mp hx_mem, refine le_antisymm (trans _ (le_supr _ n)) (supr_le (λ i, _)), { simp only [hxn, le_refl, if_true], }, { by_cases hxi : x ∈ S i; simp [hxi], }, }, { simp only [hx_mem, if_false], rw mem_Union at hx_mem, push_neg at hx_mem, refine le_antisymm (zero_le _) (supr_le (λ n, _)), simp only [hx_mem n, if_false, nonpos_iff_eq_zero], }, }, { exact λ n, hf_meas.indicator (hm _ (hS_meas n)), }, { intros n₁ n₂ hn₁₂ a, simp_rw indicator_apply, split_ifs, { exact le_rfl, }, { exact absurd (mem_of_mem_of_subset h (hS_mono hn₁₂)) h_1, }, { exact zero_le _, }, { exact le_rfl, }, }, end /-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite measure in a sub-σ-algebra and the measure is σ-finite on that sub-σ-algebra, then the integral over the whole space is bounded by that same constant. -/ lemma lintegral_le_of_forall_fin_meas_le' {μ : measure α} (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (C : ℝ≥0∞) {f : _ → ℝ≥0∞} (hf_meas : ae_measurable f μ) (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) : ∫⁻ x, f x ∂μ ≤ C := begin let f' := hf_meas.mk f, have hf' : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f' x ∂μ ≤ C, { refine λ s hs hμs, (le_of_eq _).trans (hf s hs hμs), refine lintegral_congr_ae (ae_restrict_of_ae (hf_meas.ae_eq_mk.mono (λ x hx, _))), rw hx, }, rw lintegral_congr_ae hf_meas.ae_eq_mk, exact lintegral_le_of_forall_fin_meas_le_of_measurable hm C hf_meas.measurable_mk hf', end omit m /-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite measure and the measure is σ-finite, then the integral over the whole space is bounded by that same constant. -/ lemma lintegral_le_of_forall_fin_meas_le [measurable_space α] {μ : measure α} [sigma_finite μ] (C : ℝ≥0∞) {f : α → ℝ≥0∞} (hf_meas : ae_measurable f μ) (hf : ∀ s, measurable_set s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) : ∫⁻ x, f x ∂μ ≤ C := @lintegral_le_of_forall_fin_meas_le' _ _ _ _ _ (by rwa trim_eq_self) C _ hf_meas hf local infixr ` →ₛ `:25 := simple_func lemma simple_func.exists_lt_lintegral_simple_func_of_lt_lintegral {m : measurable_space α} {μ : measure α} [sigma_finite μ] {f : α →ₛ ℝ≥0} {L : ℝ≥0∞} (hL : L < ∫⁻ x, f x ∂μ) : ∃ g : α →ₛ ℝ≥0, (∀ x, g x ≤ f x) ∧ (∫⁻ x, g x ∂μ < ∞) ∧ (L < ∫⁻ x, g x ∂μ) := begin induction f using measure_theory.simple_func.induction with c s hs f₁ f₂ H h₁ h₂ generalizing L, { simp only [hs, const_zero, coe_piecewise, coe_const, simple_func.coe_zero, univ_inter, piecewise_eq_indicator, lintegral_indicator, lintegral_const, measure.restrict_apply', coe_indicator, function.const_apply] at hL, have c_ne_zero : c ≠ 0, { assume hc, simpa only [hc, ennreal.coe_zero, zero_mul, not_lt_zero] using hL }, have : L / c < μ s, { rwa [ennreal.div_lt_iff, mul_comm], { simp only [c_ne_zero, ne.def, coe_eq_zero, not_false_iff, true_or] }, { simp only [ne.def, coe_ne_top, not_false_iff, true_or] } }, obtain ⟨t, ht, ts, mut, t_top⟩ : ∃ (t : set α), measurable_set t ∧ t ⊆ s ∧ L / ↑c < μ t ∧ μ t < ∞ := measure.exists_subset_measure_lt_top hs this, refine ⟨piecewise t ht (const α c) (const α 0), λ x, _, _, _⟩, { apply indicator_le_indicator_of_subset ts (λ x, _), exact zero_le _ }, { simp only [ht, const_zero, coe_piecewise, coe_const, simple_func.coe_zero, univ_inter, piecewise_eq_indicator, coe_indicator, function.const_apply, lintegral_indicator, lintegral_const, measure.restrict_apply', ennreal.mul_lt_top ennreal.coe_ne_top t_top.ne] }, { simp only [ht, const_zero, coe_piecewise, coe_const, simple_func.coe_zero, piecewise_eq_indicator, coe_indicator, function.const_apply, lintegral_indicator, lintegral_const, measure.restrict_apply', univ_inter], rwa [mul_comm, ← ennreal.div_lt_iff], { simp only [c_ne_zero, ne.def, coe_eq_zero, not_false_iff, true_or] }, { simp only [ne.def, coe_ne_top, not_false_iff, true_or] } } }, { replace hL : L < ∫⁻ x, f₁ x ∂μ + ∫⁻ x, f₂ x ∂μ, { rwa ← lintegral_add_left f₁.measurable.coe_nnreal_ennreal }, by_cases hf₁ : ∫⁻ x, f₁ x ∂μ = 0, { simp only [hf₁, zero_add] at hL, rcases h₂ hL with ⟨g, g_le, g_top, gL⟩, refine ⟨g, λ x, (g_le x).trans _, g_top, gL⟩, simp only [simple_func.coe_add, pi.add_apply, le_add_iff_nonneg_left, zero_le'] }, by_cases hf₂ : ∫⁻ x, f₂ x ∂μ = 0, { simp only [hf₂, add_zero] at hL, rcases h₁ hL with ⟨g, g_le, g_top, gL⟩, refine ⟨g, λ x, (g_le x).trans _, g_top, gL⟩, simp only [simple_func.coe_add, pi.add_apply, le_add_iff_nonneg_right, zero_le'] }, obtain ⟨L₁, L₂, hL₁, hL₂, hL⟩ : ∃ (L₁ L₂ : ℝ≥0∞), L₁ < ∫⁻ x, f₁ x ∂μ ∧ L₂ < ∫⁻ x, f₂ x ∂μ ∧ L < L₁ + L₂ := ennreal.exists_lt_add_of_lt_add hL hf₁ hf₂, rcases h₁ hL₁ with ⟨g₁, g₁_le, g₁_top, hg₁⟩, rcases h₂ hL₂ with ⟨g₂, g₂_le, g₂_top, hg₂⟩, refine ⟨g₁ + g₂, λ x, add_le_add (g₁_le x) (g₂_le x), _, _⟩, { apply lt_of_le_of_lt _ (add_lt_top.2 ⟨g₁_top, g₂_top⟩), rw ← lintegral_add_left g₁.measurable.coe_nnreal_ennreal, exact le_rfl }, { apply hL.trans ((ennreal.add_lt_add hg₁ hg₂).trans_le _), rw ← lintegral_add_left g₁.measurable.coe_nnreal_ennreal, exact le_rfl } } end lemma exists_lt_lintegral_simple_func_of_lt_lintegral {m : measurable_space α} {μ : measure α} [sigma_finite μ] {f : α → ℝ≥0} {L : ℝ≥0∞} (hL : L < ∫⁻ x, f x ∂μ) : ∃ g : α →ₛ ℝ≥0, (∀ x, g x ≤ f x) ∧ (∫⁻ x, g x ∂μ < ∞) ∧ (L < ∫⁻ x, g x ∂μ) := begin simp_rw [lintegral_eq_nnreal, lt_supr_iff] at hL, rcases hL with ⟨g₀, hg₀, g₀L⟩, have h'L : L < ∫⁻ x, g₀ x ∂μ, { convert g₀L, rw ← simple_func.lintegral_eq_lintegral, refl }, rcases simple_func.exists_lt_lintegral_simple_func_of_lt_lintegral h'L with ⟨g, hg, gL, gtop⟩, exact ⟨g, λ x, (hg x).trans (coe_le_coe.1 (hg₀ x)), gL, gtop⟩, end /-- A sigma-finite measure is absolutely continuous with respect to some finite measure. -/ lemma exists_absolutely_continuous_is_finite_measure {m : measurable_space α} (μ : measure α) [sigma_finite μ] : ∃ (ν : measure α), is_finite_measure ν ∧ μ ≪ ν := begin obtain ⟨g, gpos, gmeas, hg⟩ : ∃ (g : α → ℝ≥0), (∀ (x : α), 0 < g x) ∧ measurable g ∧ ∫⁻ (x : α), ↑(g x) ∂μ < 1 := exists_pos_lintegral_lt_of_sigma_finite μ one_ne_zero, refine ⟨μ.with_density (λ x, g x), is_finite_measure_with_density hg.ne_top, _⟩, have : μ = (μ.with_density (λ x, g x)).with_density (λ x, (g x)⁻¹), { have A : (λ (x : α), (g x : ℝ≥0∞)) * (λ (x : α), (↑(g x))⁻¹) = 1, { ext1 x, exact ennreal.mul_inv_cancel (ennreal.coe_ne_zero.2 ((gpos x).ne')) ennreal.coe_ne_top }, rw [← with_density_mul _ gmeas.coe_nnreal_ennreal gmeas.coe_nnreal_ennreal.inv, A, with_density_one] }, conv_lhs { rw this }, exact with_density_absolutely_continuous _ _, end end sigma_finite end measure_theory
ba2c857fc5d578f30796123c7bb50e10f256f181
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/finset/default.lean
9450420fae5cfa86c19e027c0dc1e6f035c6ecc4
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
242
lean
import data.finset.basic import data.finset.fold import data.finset.interval import data.finset.lattice import data.finset.nat_antidiagonal import data.finset.pi import data.finset.powerset import data.finset.sort import data.finset.preimage