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
617068c16b3e6f2a7292f8bd43fda79d620a9688
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/imo/imo2019_q4.lean
700aa1be727aec97629bb368896abb3e899f7fbf
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,181
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 tactic.interval_cases import algebra.big_operators.order import algebra.big_operators.part_enat import data.nat.multiplicity /-! # IMO 2019 Q4 Find all pairs `(k, n)` of positive integers such that ``` k! = (2 ^ n - 1)(2 ^ n - 2)(2 ^ n - 4)···(2 ^ n - 2 ^ (n - 1)) ``` We show in this file that this property holds iff `(k, n) = (1, 1) ∨ (k, n) = (3, 2)`. Proof sketch: The idea of the proof is to count the factors of 2 on both sides. The LHS has less than `k` factors of 2, and the RHS has exactly `n * (n - 1) / 2` factors of 2. So we know that `n * (n - 1) / 2 < k`. Now for `n ≥ 6` we have `RHS < 2 ^ (n ^ 2) < (n(n-1)/2)! < k!`. We then treat the cases `n < 6` individually. -/ open_locale nat big_operators open finset multiplicity nat (hiding zero_le prime) theorem imo2019_q4_upper_bound {k n : ℕ} (hk : k > 0) (h : (k! : ℤ) = ∏ i in range n, (2 ^ n - 2 ^ i)) : n < 6 := begin have prime_2 : prime (2 : ℤ), { exact prime_iff_prime_int.mp prime_two }, have h2 : n * (n - 1) / 2 < k, { suffices : multiplicity 2 (k! : ℤ) = (n * (n - 1) / 2 : ℕ), { rw [← part_enat.coe_lt_coe, ← this], change multiplicity ((2 : ℕ) : ℤ) _ < _, simp_rw [int.coe_nat_multiplicity, multiplicity_two_factorial_lt hk.lt.ne.symm] }, rw [h, multiplicity.finset.prod prime_2, ← sum_range_id, ← sum_nat_coe_enat], apply sum_congr rfl, intros i hi, rw [multiplicity_sub_of_gt, multiplicity_pow_self_of_prime prime_2], rwa [multiplicity_pow_self_of_prime prime_2, multiplicity_pow_self_of_prime prime_2, part_enat.coe_lt_coe, ←mem_range] }, rw [←not_le], intro hn, apply ne_of_lt _ h.symm, suffices : (∏ i in range n, 2 ^ n : ℤ) < ↑k!, { apply lt_of_le_of_lt _ this, apply prod_le_prod, { intros, rw [sub_nonneg], apply pow_le_pow, norm_num, apply le_of_lt, rwa [← mem_range] }, { intros, apply sub_le_self, apply pow_nonneg, norm_num } }, suffices : 2 ^ (n * n) < (n * (n - 1) / 2)!, { rw [prod_const, card_range, ← pow_mul], rw [← int.coe_nat_lt_coe_nat_iff] at this, clear h, convert this.trans _, norm_cast, rwa [int.coe_nat_lt_coe_nat_iff, factorial_lt], refine nat.div_pos _ (by norm_num), refine le_trans _ (mul_le_mul hn (pred_le_pred hn) (zero_le _) (zero_le _)), norm_num }, refine le_induction _ _ n hn, { norm_num }, intros n' hn' ih, have h5 : 1 ≤ 2 * n', { linarith }, have : 2 ^ (2 + 2) ≤ (n' * (n' - 1) / 2).succ, { change succ (6 * (6 - 1) / 2) ≤ _, apply succ_le_succ, apply nat.div_le_div_right, exact mul_le_mul hn' (pred_le_pred hn') (zero_le _) (zero_le _) }, rw [triangle_succ], apply lt_of_lt_of_le _ factorial_mul_pow_le_factorial, refine lt_of_le_of_lt _ (mul_lt_mul ih (nat.pow_le_pow_of_le_left this _) (pow_pos (by norm_num) _) (zero_le _)), rw [← pow_mul, ← pow_add], apply pow_le_pow_of_le_right, norm_num, rw [add_mul 2 2], convert add_le_add_left (add_le_add_left h5 (2 * n')) (n' * n') using 1, ring end theorem imo2019_q4 {k n : ℕ} (hk : k > 0) (hn : n > 0) : (k! : ℤ) = (∏ i in range n, (2 ^ n - 2 ^ i)) ↔ (k, n) = (1, 1) ∨ (k, n) = (3, 2) := begin /- The implication `←` holds. -/ split, swap, { rintro (h|h); simp [prod.ext_iff] at h; rcases h with ⟨rfl, rfl⟩; norm_num [prod_range_succ, succ_mul] }, intro h, /- We know that n < 6. -/ have := imo2019_q4_upper_bound hk h, interval_cases n, /- n = 1 -/ { left, congr, norm_num at h, rw [factorial_eq_one] at h, apply antisymm h, apply succ_le_of_lt hk }, /- n = 2 -/ { right, congr, norm_num [prod_range_succ] at h, norm_cast at h, rw [← factorial_inj], exact h, rw [h], norm_num }, all_goals { exfalso, norm_num [prod_range_succ] at h, norm_cast at h, }, /- n = 3 -/ { refine monotone_factorial.ne_of_lt_of_lt_nat 5 _ _ _ h; norm_num }, /- n = 4 -/ { refine monotone_factorial.ne_of_lt_of_lt_nat 7 _ _ _ h; norm_num }, /- n = 5 -/ { refine monotone_factorial.ne_of_lt_of_lt_nat 10 _ _ _ h; norm_num }, end
37e03586e13845ab63137ea25c67fc48a0da847a
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Init/Notation.lean
8d06cf45d359a90e8e10e0c3f34b60e262465312
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,466
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 Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude -- DSL for specifying parser precedences and priorities namespace Lean.Parser.Syntax syntax:65 (name := addPrec) prec " + " prec:66 : prec syntax:65 (name := subPrec) prec " - " prec:66 : prec syntax:65 (name := addPrio) prio " + " prio:66 : prio syntax:65 (name := subPrio) prio " - " prio:66 : prio end Lean.Parser.Syntax macro "max" : prec => `(1024) -- maximum precedence used in term parsers macro "lead" : prec => `(1023) macro "(" p:prec ")" : prec => p macro "min" : prec => `(10) -- minimum precedence used in term parsers macro "min1" : prec => `(11) -- `(min+1) we can only `min+1` after `Meta.lean` /- `max:prec` as a term. It is equivalent to `evalPrec! max` for `evalPrec!` defined at `Meta.lean`. We use `maxPrec!` to workaround bootstrapping issues. -/ macro "maxPrec!" : term => `(1024) macro "default" : prio => `(1000) macro "low" : prio => `(100) macro "mid" : prio => `(1000) macro "high" : prio => `(10000) macro "(" p:prio ")" : prio => p -- Basic notation for defining parsers syntax stx "+" : stx syntax stx "*" : stx syntax stx "?" : stx syntax:2 stx " <|> " stx:1 : stx macro_rules | `(stx| $p +) => `(stx| many1($p)) | `(stx| $p *) => `(stx| many($p)) | `(stx| $p ?) => `(stx| optional($p)) | `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂)) /- Comma-separated sequence. -/ macro:max x:stx ",*" : stx => `(stx| sepBy($x, ",", ", ")) macro:max x:stx ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /- Comma-separated sequence with optional trailing comma. -/ macro:max x:stx ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) macro:max x:stx ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) macro "!" x:stx : stx => `(stx| notFollowedBy($x)) syntax (name := rawNatLit) "natLit! " num : term infixr:90 " ∘ " => Function.comp infixr:35 " × " => Prod infixl:65 " + " => HAdd.hAdd infixl:65 " - " => HSub.hSub infixl:70 " * " => HMul.hMul infixl:70 " / " => HDiv.hDiv infixl:70 " % " => HMod.hMod infixr:80 " ^ " => HPow.hPow prefix:100 "-" => Neg.neg -- declare ASCII alternatives first so that the latter Unicode unexpander wins infix:50 " <= " => HasLessEq.LessEq infix:50 " ≤ " => HasLessEq.LessEq infix:50 " < " => HasLess.Less infix:50 " >= " => GreaterEq infix:50 " ≥ " => GreaterEq infix:50 " > " => Greater infix:50 " = " => Eq infix:50 " == " => BEq.beq infix:50 " ~= " => HEq infix:50 " ≅ " => HEq /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binrel!` elaboration helper for binary relations. It has better support for applying coercions. For example, suppose we have `binrel! Eq n i` where `n : Nat` and `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but `binrel!` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/ macro_rules | `($x <= $y) => `(binrel! HasLessEq.LessEq $x $y) macro_rules | `($x ≤ $y) => `(binrel! HasLessEq.LessEq $x $y) macro_rules | `($x < $y) => `(binrel! HasLess.Less $x $y) macro_rules | `($x > $y) => `(binrel! Greater $x $y) macro_rules | `($x >= $y) => `(binrel! GreaterEq $x $y) macro_rules | `($x ≥ $y) => `(binrel! GreaterEq $x $y) macro_rules | `($x = $y) => `(binrel! Eq $x $y) macro_rules | `($x == $y) => `(binrel! BEq.beq $x $y) infixr:35 " /\\ " => And infixr:35 " ∧ " => And infixr:30 " \\/ " => Or infixr:30 " ∨ " => Or notation:max "¬" p:40 => Not p infixl:35 " && " => and infixl:30 " || " => or notation:max "!" b:40 => not b infixl:65 " ++ " => HAppend.hAppend infixr:67 " :: " => List.cons infixr:20 " <|> " => HOrElse.hOrElse infixr:60 " >> " => HAndThen.hAndThen infixl:55 " >>= " => Bind.bind infixl:60 " <*> " => Seq.seq infixl:60 " <* " => SeqLeft.seqLeft infixr:60 " *> " => SeqRight.seqRight infixr:100 " <$> " => Functor.map syntax (name := termDepIfThenElse) ppGroup(ppDedent("if " ident " : " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $h:ident : $c then $t:term else $e:term) => `(dite $c (fun $h:ident => $t) (fun $h:ident => $e)) syntax (name := termIfThenElse) ppGroup(ppDedent("if " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $c then $t:term else $e:term) => `(ite $c $t $e) macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term => `(match $d:term with | $pat:term => $t | _ => $e) syntax:min term "<|" term:min : term macro_rules | `($f $args* <| $a) => let args := args.push a; `($f $args*) | `($f <| $a) => `($f $a) syntax:min term "|>" term:min1 : term macro_rules | `($a |> $f $args*) => let args := args.push a; `($f $args*) | `($a |> $f) => `($f $a) -- Haskell-like pipe <| -- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations. syntax:min term atomic("$" ws) term:min : term macro_rules | `($f $args* $ $a) => let args := args.push a; `($f $args*) | `($f $ $a) => `($f $a) syntax "{ " ident (" : " term)? " // " term " }" : term macro_rules | `({ $x : $type // $p }) => `(Subtype (fun ($x:ident : $type) => $p)) | `({ $x // $p }) => `(Subtype (fun ($x:ident : _) => $p)) /- `withoutExpected! t` instructs Lean to elaborate `t` without an expected type. Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until expected type is known. So, `withoutExpected!` is not effective in this case. -/ macro "withoutExpectedType! " x:term : term => `(let aux := $x; aux) syntax "[" term,* "]" : term syntax "%[" term,* "|" term "]" : term -- auxiliary notation for creating big list literals namespace Lean macro_rules | `([ $elems,* ]) => do let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : MacroM Syntax := do match i, skip with | 0, _ => pure result | i+1, true => expandListLit i false result | i+1, false => expandListLit i true (← `(List.cons $(elems.elemsAndSeps[i]) $result)) if elems.elemsAndSeps.size < 64 then expandListLit elems.elemsAndSeps.size false (← `(List.nil)) else `(%[ $elems,* | List.nil ]) namespace Parser.Tactic syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic syntax (name := intros) "intros " (colGt (ident <|> "_"))* : tactic syntax (name := revert) "revert " (colGt ident)+ : tactic syntax (name := clear) "clear " (colGt ident)+ : tactic syntax (name := subst) "subst " (colGt ident)+ : tactic syntax (name := assumption) "assumption" : tactic syntax (name := apply) "apply " term : tactic syntax (name := exact) "exact " term : tactic syntax (name := refine) "refine " term : tactic syntax (name := refine!) "refine! " term : tactic syntax (name := case) "case " ident " => " tacticSeq : tactic syntax (name := allGoals) "allGoals " tacticSeq : tactic syntax (name := focus) "focus " tacticSeq : tactic syntax (name := skip) "skip" : tactic syntax (name := done) "done" : tactic syntax (name := traceState) "traceState" : tactic syntax (name := failIfSuccess) "failIfSuccess " tacticSeq : tactic syntax (name := generalize) "generalize " atomic(ident " : ")? term:51 " = " ident : tactic syntax (name := paren) "(" tacticSeq ")" : tactic syntax (name := withReducible) "withReducible " tacticSeq : tactic syntax (name := withReducibleAndInstances) "withReducibleAndInstances " tacticSeq : tactic syntax (name := first) "first " "|"? sepBy1(tacticSeq, "|") : tactic macro "try " t:tacticSeq : tactic => `(first $t | skip) macro:1 x:tactic " <;> " y:tactic:0 : tactic => `(tactic| focus ($x:tactic; allGoals $y:tactic)) macro "rfl" : tactic => `(exact rfl) macro "decide!" : tactic => `(exact decide!) macro "admit" : tactic => `(exact sorry) syntax locationWildcard := "*" syntax locationTarget := "⊢" <|> "|-" syntax locationHyp := (colGt ident)+ syntax location := withPosition("at " locationWildcard <|> locationTarget <|> locationHyp) syntax (name := change) "change " term (location)? : tactic syntax (name := changeWith) "change " term " with " term (location)? : tactic syntax rwRule := ("←" <|> "<-")? term syntax rwRuleSeq := "[" rwRule,+,? "]" syntax (name := rewrite) "rewrite " rwRule (location)? : tactic syntax (name := rewriteSeq) (priority := high) "rewrite " rwRuleSeq (location)? : tactic syntax (name := erewrite) "erewrite " rwRule (location)? : tactic syntax (name := erewriteSeq) (priority := high) "erewrite " rwRuleSeq (location)? : tactic syntax (name := rw) "rw " rwRule (location)? : tactic syntax (name := rwSeq) (priority := high) "rw " rwRuleSeq (location)? : tactic syntax (name := erw) "erw " rwRule (location)? : tactic syntax (name := erwSeq) (priority := high) "erw " rwRuleSeq (location)? : tactic private def withCheapRefl (tac : Syntax) : MacroM Syntax := `(tactic| $tac; try (withReducible rfl)) @[macro rw] def expandRw : Macro := fun stx => withCheapRefl (stx.setKind `Lean.Parser.Tactic.rewrite |>.setArg 0 (mkAtomFrom stx "rewrite")) @[macro rwSeq] def expandRwSeq : Macro := fun stx => withCheapRefl (stx.setKind `Lean.Parser.Tactic.rewriteSeq |>.setArg 0 (mkAtomFrom stx "rewrite")) @[macro erw] def expandERw : Macro := fun stx => withCheapRefl (stx.setKind `Lean.Parser.Tactic.erewrite |>.setArg 0 (mkAtomFrom stx "erewrite")) @[macro erwSeq] def expandERwSeq : Macro := fun stx => withCheapRefl (stx.setKind `Lean.Parser.Tactic.erewriteSeq |>.setArg 0 (mkAtomFrom stx "erewrite")) syntax (name := injection) "injection " term (" with " (colGt (ident <|> "_"))+)? : tactic syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? term syntax (name := simp) "simp " ("[" simpLemma,* "]")? (colGt term)? (location)? : tactic syntax (name := «have») "have " haveDecl : tactic syntax (name := «suffices») "suffices " sufficesDecl : tactic syntax (name := «show») "show " term : tactic syntax (name := «let») "let " letDecl : tactic syntax (name := «let!») "let! " letDecl : tactic syntax (name := letrec) withPosition(atomic(group("let " &"rec ")) letRecDecls) : tactic syntax inductionAlt := "| " (group("@"? ident) <|> "_") (ident <|> "_")* " => " (hole <|> syntheticHole <|> tacticSeq) syntax inductionAlts := "with " withPosition( (colGe inductionAlt)+) syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " ident+)? (inductionAlts)? : tactic syntax casesTarget := atomic(ident " : ")? term syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic syntax (name := existsIntro) "exists " term : tactic /- We use a priority > default, to avoid ambiguity with the builtin `have` notation -/ macro (priority := high) "have" x:ident " := " p:term : tactic => `(have $x:ident : _ := $p) syntax "repeat " tacticSeq : tactic macro_rules | `(tactic| repeat $seq) => `(tactic| first ($seq); repeat $seq | skip) end Tactic namespace Attr -- simp attribute syntax syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr end Attr end Parser end Lean
c8469953f82bf2fa30ddd84af97e6e47d94cca39
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/limits/lattice.lean
1f331094c6e5e623557b315b8a404a8ec792b50d
[ "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
1,532
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.limits import order.complete_lattice universes u open category_theory namespace category_theory.limits variables {α : Type u} -- It would be nice to only use the `Inf` half of the complete lattice, but -- this seems not to have been described separately. @[priority 100] -- see Note [lower instance priority] instance has_limits_of_complete_lattice [complete_lattice α] : has_limits.{u} α := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, { cone := { X := Inf (set.range F.obj), π := { app := λ j, ⟨⟨complete_lattice.Inf_le _ _ (set.mem_range_self _)⟩⟩ } }, is_limit := { lift := λ s, ⟨⟨complete_lattice.le_Inf _ _ begin rintros _ ⟨j, rfl⟩, exact (s.π.app j).down.down, end⟩⟩ } } } } @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_complete_lattice [complete_lattice α] : has_colimits.{u} α := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, { cocone := { X := Sup (set.range F.obj), ι := { app := λ j, ⟨⟨complete_lattice.le_Sup _ _ (set.mem_range_self _)⟩⟩ } }, is_colimit := { desc := λ s, ⟨⟨complete_lattice.Sup_le _ _ begin rintros _ ⟨j, rfl⟩, exact (s.ι.app j).down.down, end⟩⟩ } } } } end category_theory.limits
f39ea5024d685bcb3f9b7763f312006ea0ded231
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/polynomial/homogeneous.lean
785f5758e678d5ae454263233450dc347f93dc07
[ "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
10,360
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Eric Wieser -/ import algebra.direct_sum.internal import algebra.graded_monoid import data.fintype.card import data.mv_polynomial.variables /-! # Homogeneous polynomials A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. ## Main definitions/lemmas * `is_homogeneous φ n`: a predicate that asserts that `φ` is homogeneous of degree `n`. * `homogeneous_submodule σ R n`: the submodule of homogeneous polynomials of degree `n`. * `homogeneous_component n`: the additive morphism that projects polynomials onto their summand that is homogeneous of degree `n`. * `sum_homogeneous_component`: every polynomial is the sum of its homogeneous components -/ open_locale big_operators namespace mv_polynomial variables {σ : Type*} {τ : Type*} {R : Type*} {S : Type*} /- TODO * create definition for `∑ i in d.support, d i` * show that `mv_polynomial σ R ≃ₐ[R] ⨁ i, homogeneous_submodule σ R i` -/ /-- A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. -/ def is_homogeneous [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) := ∀ ⦃d⦄, coeff d φ ≠ 0 → ∑ i in d.support, d i = n variables (σ R) /-- The submodule of homogeneous `mv_polynomial`s of degree `n`. -/ noncomputable def homogeneous_submodule [comm_semiring R] (n : ℕ) : submodule R (mv_polynomial σ R) := { carrier := { x | x.is_homogeneous n }, smul_mem' := λ r a ha c hc, begin rw coeff_smul at hc, apply ha, intro h, apply hc, rw h, exact smul_zero r, end, zero_mem' := λ d hd, false.elim (hd $ coeff_zero _), add_mem' := λ a b ha hb c hc, begin rw coeff_add at hc, obtain h|h : coeff c a ≠ 0 ∨ coeff c b ≠ 0, { contrapose! hc, simp only [hc, add_zero] }, { exact ha h }, { exact hb h } end } variables {σ R} @[simp] lemma mem_homogeneous_submodule [comm_semiring R] (n : ℕ) (p : mv_polynomial σ R) : p ∈ homogeneous_submodule σ R n ↔ p.is_homogeneous n := iff.rfl variables (σ R) /-- While equal, the former has a convenient definitional reduction. -/ lemma homogeneous_submodule_eq_finsupp_supported [comm_semiring R] (n : ℕ) : homogeneous_submodule σ R n = finsupp.supported _ R {d | ∑ i in d.support, d i = n} := begin ext, rw [finsupp.mem_supported, set.subset_def], simp only [finsupp.mem_support_iff, finset.mem_coe], refl, end variables {σ R} lemma homogeneous_submodule_mul [comm_semiring R] (m n : ℕ) : homogeneous_submodule σ R m * homogeneous_submodule σ R n ≤ homogeneous_submodule σ R (m + n) := begin rw submodule.mul_le, intros φ hφ ψ hψ c hc, rw [coeff_mul] at hc, obtain ⟨⟨d, e⟩, hde, H⟩ := finset.exists_ne_zero_of_sum_ne_zero hc, have aux : coeff d φ ≠ 0 ∧ coeff e ψ ≠ 0, { contrapose! H, by_cases h : coeff d φ = 0; simp only [*, ne.def, not_false_iff, zero_mul, mul_zero] at * }, specialize hφ aux.1, specialize hψ aux.2, rw finsupp.mem_antidiagonal at hde, classical, have hd' : d.support ⊆ d.support ∪ e.support := finset.subset_union_left _ _, have he' : e.support ⊆ d.support ∪ e.support := finset.subset_union_right _ _, rw [← hde, ← hφ, ← hψ, finset.sum_subset (finsupp.support_add), finset.sum_subset hd', finset.sum_subset he', ← finset.sum_add_distrib], { congr }, all_goals { intros i hi, apply finsupp.not_mem_support_iff.mp }, end section variables [comm_semiring R] variables {σ R} lemma is_homogeneous_monomial (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : ∑ i in d.support, d i = n) : is_homogeneous (monomial d r) n := begin intros c hc, classical, rw coeff_monomial at hc, split_ifs at hc with h, { subst c, exact hn }, { contradiction } end variables (σ) {R} lemma is_homogeneous_of_total_degree_zero {p : mv_polynomial σ R} (hp : p.total_degree = 0) : is_homogeneous p 0 := begin erw [total_degree, finset.sup_eq_bot_iff] at hp, -- we have to do this in two steps to stop simp changing bot to zero simp_rw [mem_support_iff] at hp, exact hp, end lemma is_homogeneous_C (r : R) : is_homogeneous (C r : mv_polynomial σ R) 0 := begin apply is_homogeneous_monomial, simp only [finsupp.zero_apply, finset.sum_const_zero], end variables (σ R) lemma is_homogeneous_zero (n : ℕ) : is_homogeneous (0 : mv_polynomial σ R) n := (homogeneous_submodule σ R n).zero_mem lemma is_homogeneous_one : is_homogeneous (1 : mv_polynomial σ R) 0 := is_homogeneous_C _ _ variables {σ} (R) lemma is_homogeneous_X (i : σ) : is_homogeneous (X i : mv_polynomial σ R) 1 := begin apply is_homogeneous_monomial, simp only [finsupp.support_single_ne_zero one_ne_zero, finset.sum_singleton], exact finsupp.single_eq_same end end namespace is_homogeneous variables [comm_semiring R] {φ ψ : mv_polynomial σ R} {m n : ℕ} lemma coeff_eq_zero (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : ∑ i in d.support, d i ≠ n) : coeff d φ = 0 := by { have aux := mt (@hφ d) hd, classical, rwa not_not at aux } lemma inj_right (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) : m = n := begin obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero hφ, rw [← hm hd, ← hn hd] end lemma add (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) : is_homogeneous (φ + ψ) n := (homogeneous_submodule σ R n).add_mem hφ hψ lemma sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) n) : is_homogeneous (∑ i in s, φ i) n := (homogeneous_submodule σ R n).sum_mem h lemma mul (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) : is_homogeneous (φ * ψ) (m + n) := homogeneous_submodule_mul m n $ submodule.mul_mem_mul hφ hψ lemma prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) (n i)) : is_homogeneous (∏ i in s, φ i) (∑ i in s, n i) := begin classical, revert h, apply finset.induction_on s, { intro, simp only [is_homogeneous_one, finset.sum_empty, finset.prod_empty] }, { intros i s his IH h, simp only [his, finset.prod_insert, finset.sum_insert, not_false_iff], apply (h i (finset.mem_insert_self _ _)).mul (IH _), intros j hjs, exact h j (finset.mem_insert_of_mem hjs) } end lemma total_degree (hφ : is_homogeneous φ n) (h : φ ≠ 0) : total_degree φ = n := begin rw total_degree, apply le_antisymm, { apply finset.sup_le, intros d hd, rw mem_support_iff at hd, rw [finsupp.sum, hφ hd], }, { obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero h, simp only [← hφ hd, finsupp.sum], replace hd := finsupp.mem_support_iff.mpr hd, exact finset.le_sup hd, } end /-- The homogeneous submodules form a graded ring. This instance is used by `direct_sum.comm_semiring` and `direct_sum.algebra`. -/ instance homogeneous_submodule.gcomm_semiring : set_like.graded_monoid (homogeneous_submodule σ R) := { one_mem := is_homogeneous_one σ R, mul_mem := λ i j xi xj, is_homogeneous.mul} open_locale direct_sum noncomputable example : comm_semiring (⨁ i, homogeneous_submodule σ R i) := infer_instance noncomputable example : algebra R (⨁ i, homogeneous_submodule σ R i) := infer_instance end is_homogeneous section noncomputable theory open_locale classical open finset /-- `homogeneous_component n φ` is the part of `φ` that is homogeneous of degree `n`. See `sum_homogeneous_component` for the statement that `φ` is equal to the sum of all its homogeneous components. -/ def homogeneous_component [comm_semiring R] (n : ℕ) : mv_polynomial σ R →ₗ[R] mv_polynomial σ R := (submodule.subtype _).comp $ finsupp.restrict_dom _ _ {d | ∑ i in d.support, d i = n} section homogeneous_component open finset variables [comm_semiring R] (n : ℕ) (φ ψ : mv_polynomial σ R) lemma coeff_homogeneous_component (d : σ →₀ ℕ) : coeff d (homogeneous_component n φ) = if ∑ i in d.support, d i = n then coeff d φ else 0 := by convert finsupp.filter_apply (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ d lemma homogeneous_component_apply : homogeneous_component n φ = ∑ d in φ.support.filter (λ d, ∑ i in d.support, d i = n), monomial d (coeff d φ) := by convert finsupp.filter_eq_sum (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ lemma homogeneous_component_is_homogeneous : (homogeneous_component n φ).is_homogeneous n := begin intros d hd, contrapose! hd, rw [coeff_homogeneous_component, if_neg hd] end @[simp] lemma homogeneous_component_zero : homogeneous_component 0 φ = C (coeff 0 φ) := begin ext1 d, rcases em (d = 0) with (rfl|hd), { simp only [coeff_homogeneous_component, sum_eq_zero_iff, finsupp.zero_apply, if_true, coeff_C, eq_self_iff_true, forall_true_iff] }, { rw [coeff_homogeneous_component, if_neg, coeff_C, if_neg (ne.symm hd)], simp only [finsupp.ext_iff, finsupp.zero_apply] at hd, simp [hd] } end @[simp] lemma homogeneous_component_C_mul (n : ℕ) (r : R) : homogeneous_component n (C r * φ) = C r * homogeneous_component n φ := by simp only [C_mul', linear_map.map_smul] lemma homogeneous_component_eq_zero' (h : ∀ d : σ →₀ ℕ, d ∈ φ.support → ∑ i in d.support, d i ≠ n) : homogeneous_component n φ = 0 := begin rw [homogeneous_component_apply, sum_eq_zero], intros d hd, rw mem_filter at hd, exfalso, exact h _ hd.1 hd.2 end lemma homogeneous_component_eq_zero (h : φ.total_degree < n) : homogeneous_component n φ = 0 := begin apply homogeneous_component_eq_zero', rw [total_degree, finset.sup_lt_iff] at h, { intros d hd, exact ne_of_lt (h d hd), }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma sum_homogeneous_component : ∑ i in range (φ.total_degree + 1), homogeneous_component i φ = φ := begin ext1 d, suffices : φ.total_degree < d.support.sum d → 0 = coeff d φ, by simpa [coeff_sum, coeff_homogeneous_component], exact λ h, (coeff_eq_zero_of_total_degree_lt h).symm end end homogeneous_component end end mv_polynomial
6c139d7d3b212f2de466e9c4a438dec50698cae5
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world7/level6.lean
d8b5cff205466825a67c26859f76b6f73186a425
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
1,196
lean
import game.world7.level5 -- hide /- # Advanced proposition world. ## Level 6: Or, and the `left` and `right` tactics. `P ∨ Q` means "$P$ or $Q$". So to prove it, you need to choose one of `P` or `Q`, and prove that one. If `⊢ P ∨ Q` is your goal, then `left` changes this goal to `⊢ P`, and `right` changes it to `⊢ Q`. Note that you can take a wrong turn here. Let's start with trying to prove $Q\implies (P\lor Q)$. After the `intro`, one of `left` and `right` leads to an impossible goal, the other to an easy finish. -/ /- Lemma : no-side-bar If $P$ and $Q$ are true/false statements, then $$Q\implies(P\lor Q).$$ -/ example (P Q : Prop) : Q → (P ∨ Q) := begin intro q, right, assumption, end /- Tactic : left and right ## Summary `left` and `right` work on the goal, and they change `⊢ P ∨ Q` to `⊢ P` and `⊢ Q` respectively. ## Details The tactics `left` and `right` work on a goal which is a type with two constructors, the classic example being `P ∨ Q`. To prove `P ∨ Q` it suffices to either prove `P` or prove `Q`, and once you know which one you are going for you can change the goal with `left` or `right` to the appropriate choice. -/
5d1785374a8ee5129808ac99adff4f2468d4b7e2
59a4b050600ed7b3d5826a8478db0a9bdc190252
/src/category_theory/equivalence/default.lean
a866ebe342e852783e71b7bbb7c4e5125c06b888
[]
no_license
rwbarton/lean-category-theory
f720268d800b62a25d69842ca7b5d27822f00652
00df814d463406b7a13a56f5dcda67758ba1b419
refs/heads/master
1,585,366,296,767
1,536,151,349,000
1,536,151,349,000
147,652,096
0
0
null
1,536,226,960,000
1,536,226,960,000
null
UTF-8
Lean
false
false
2,285
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.embedding import category_theory.tactics.obviously namespace category_theory universes u₁ v₁ u₂ v₂ structure Equivalence (C : Type u₁) [category.{u₁ v₁} C] (D : Type u₂) [category.{u₂ v₂} D] := (functor : C ⥤ D) (inverse : D ⥤ C) (isomorphism_1' : (functor ⋙ inverse) ≅ (category_theory.functor.id C) . obviously) (isomorphism_2' : (inverse ⋙ functor) ≅ (category_theory.functor.id D) . obviously) restate_axiom Equivalence.isomorphism_1' restate_axiom Equivalence.isomorphism_2' variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒞 𝒟 namespace Equivalence def symm (e : Equivalence C D) : Equivalence D C := { functor := e.inverse, inverse := e.functor, isomorphism_1' := e.isomorphism_2, isomorphism_2' := e.isomorphism_1 } @[simp,search] lemma onMorphisms_1 (e : Equivalence C D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = (e.isomorphism_2.hom X) ≫ f ≫ (e.isomorphism_2.inv Y) := by obviously @[simp,search] lemma onMorphisms_2 (e : Equivalence C D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = (e.isomorphism_1.hom X) ≫ f ≫ (e.isomorphism_1.inv Y) := by obviously -- PROJECT a good way to do this? -- def EquivalenceComposition (e : Equivalence C D) (f : Equivalence D E) : Equivalence C E := -- { -- functor := e.functor ⋙ f.functor, -- inverse := f.inverse ⋙ e.inverse, -- isomorphism_1 := sorry, -- isomorphism_2 := sorry -- } end Equivalence class ess_surj (F : C ⥤ D) := (pre (d : D) : C) (iso (d : D) : F (pre d) ≅ d) class is_Equivalence (F : C ⥤ D) := (inverse : D ⥤ C) (isomorphism_1' : (F ⋙ inverse) ≅ (functor.id C)) (isomorphism_2' : (inverse ⋙ F) ≅ (functor.id D)) restate_axiom is_Equivalence.isomorphism_1' restate_axiom is_Equivalence.isomorphism_2' instance (e : Equivalence C D) : is_Equivalence e.functor := { inverse := e.inverse, isomorphism_1' := e.isomorphism_1, isomorphism_2' := e.isomorphism_2 } end category_theory
292a85f688e8e24355770c6dd455e09753f5695c
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/Transform.lean
dc9c7ca8c391a9046b9ab5f40deaa7ead2add5da
[ "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
7,424
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.Basic namespace Lean inductive TransformStep where | done (e : Expr) | visit (e : Expr) namespace Core /-- Tranform the expression `input` using `pre` and `post`. - `pre s` is invoked before visiting the children of subterm 's'. If the result is `TransformStep.visit sNew`, then `sNew` is traversed by transform. If the result is `TransformStep.done sNew`, then `s` is just replaced with `sNew`. In both cases, `sNew` must be definitionally equal to `s` - `post s` is invoked after visiting the children of subterm `s`. The term `s` in both `pre s` and `post s` may contain loose bound variables. So, this method is not appropriate for if one needs to apply operations (e.g., `whnf`, `inferType`) that do not handle loose bound variables. Consider using `Meta.transform` to avoid loose bound variables. This method is useful for applying transformations such as beta-reduction and delta-reduction. -/ partial def transform {m} [Monad m] [MonadLiftT CoreM m] [MonadControlT CoreM m] (input : Expr) (pre : Expr → m TransformStep := fun e => return TransformStep.visit e) (post : Expr → m TransformStep := fun e => return TransformStep.done e) : m Expr := let _ : STWorld IO.RealWorld m := ⟨⟩ let _ : MonadLiftT (ST IO.RealWorld) m := { monadLift := fun x => liftM (m := CoreM) (liftM (m := ST IO.RealWorld) x) } let rec visit (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := checkCache { val := e : ExprStructEq } fun _ => Core.withIncRecDepth do let rec visitPost (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do match (← post e) with | TransformStep.done e => pure e | TransformStep.visit e => visit e match (← pre e) with | TransformStep.done e => pure e | TransformStep.visit e => match e with | Expr.forallE _ d b _ => visitPost (e.updateForallE! (← visit d) (← visit b)) | Expr.lam _ d b _ => visitPost (e.updateLambdaE! (← visit d) (← visit b)) | Expr.letE _ t v b _ => visitPost (e.updateLet! (← visit t) (← visit v) (← visit b)) | Expr.app .. => e.withApp fun f args => do visitPost (mkAppN (← visit f) (← args.mapM visit)) | Expr.mdata _ b => visitPost (e.updateMData! (← visit b)) | Expr.proj _ _ b => visitPost (e.updateProj! (← visit b)) | _ => visitPost e visit input |>.run def betaReduce (e : Expr) : CoreM Expr := transform e (pre := fun e => return TransformStep.visit e.headBeta) end Core namespace Meta /-- Similar to `Core.transform`, but terms provided to `pre` and `post` do not contain loose bound variables. So, it is safe to use any `MetaM` method at `pre` and `post`. -/ partial def transform {m} [Monad m] [MonadLiftT MetaM m] [MonadControlT MetaM m] [MonadTrace m] [MonadRef m] [MonadOptions m] [AddMessageContext m] (input : Expr) (pre : Expr → m TransformStep := fun e => return TransformStep.visit e) (post : Expr → m TransformStep := fun e => return TransformStep.done e) (usedLetOnly := false) : m Expr := do let _ : STWorld IO.RealWorld m := ⟨⟩ let _ : MonadLiftT (ST IO.RealWorld) m := { monadLift := fun x => liftM (m := MetaM) (liftM (m := ST IO.RealWorld) x) } let rec visit (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := checkCache { val := e : ExprStructEq } fun _ => Meta.withIncRecDepth do let rec visitPost (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do match (← post e) with | TransformStep.done e => pure e | TransformStep.visit e => visit e let rec visitLambda (fvars : Array Expr) (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do match e with | Expr.lam n d b c => withLocalDecl n c (← visit (d.instantiateRev fvars)) fun x => visitLambda (fvars.push x) b | e => visitPost (← mkLambdaFVars (usedLetOnly := usedLetOnly) fvars (← visit (e.instantiateRev fvars))) let rec visitForall (fvars : Array Expr) (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do match e with | Expr.forallE n d b c => withLocalDecl n c (← visit (d.instantiateRev fvars)) fun x => visitForall (fvars.push x) b | e => visitPost (← mkForallFVars (usedLetOnly := usedLetOnly) fvars (← visit (e.instantiateRev fvars))) let rec visitLet (fvars : Array Expr) (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do match e with | Expr.letE n t v b _ => withLetDecl n (← visit (t.instantiateRev fvars)) (← visit (v.instantiateRev fvars)) fun x => visitLet (fvars.push x) b | e => visitPost (← mkLetFVars (usedLetOnly := usedLetOnly) fvars (← visit (e.instantiateRev fvars))) let visitApp (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := e.withApp fun f args => do visitPost (mkAppN (← visit f) (← args.mapM visit)) match (← pre e) with | TransformStep.done e => pure e | TransformStep.visit e => match e with | Expr.forallE .. => visitForall #[] e | Expr.lam .. => visitLambda #[] e | Expr.letE .. => visitLet #[] e | Expr.app .. => visitApp e | Expr.mdata _ b => visitPost (e.updateMData! (← visit b)) | Expr.proj _ _ b => visitPost (e.updateProj! (← visit b)) | _ => visitPost e visit input |>.run def zetaReduce (e : Expr) : MetaM Expr := do let pre (e : Expr) : MetaM TransformStep := do match e with | Expr.fvar fvarId => match (← getLCtx).find? fvarId with | none => return TransformStep.done e | some localDecl => if let some value := localDecl.value? then return TransformStep.visit value else return TransformStep.done e | e => return TransformStep.visit e transform e (pre := pre) (usedLetOnly := true) /-- Unfold definitions and theorems in `e` that are not in the current environment, but are in `biggerEnv`. -/ def unfoldDeclsFrom (biggerEnv : Environment) (e : Expr) : CoreM Expr := do withoutModifyingEnv do let env ← getEnv setEnv biggerEnv -- `e` has declarations from `biggerEnv` that are not in `env` let pre (e : Expr) : CoreM TransformStep := do match e with | Expr.const declName us .. => if env.contains declName then return TransformStep.done e else if let some info := biggerEnv.find? declName then if info.hasValue then return TransformStep.visit (← instantiateValueLevelParams info us) else return TransformStep.done e else return TransformStep.done e | _ => return TransformStep.visit e Core.transform e (pre := pre) def eraseInaccessibleAnnotations (e : Expr) : CoreM Expr := Core.transform e (post := fun e => return TransformStep.done <| if let some e := inaccessible? e then e else e) def erasePatternRefAnnotations (e : Expr) : CoreM Expr := Core.transform e (post := fun e => return TransformStep.done <| if let some (_, e) := patternWithRef? e then e else e) end Meta end Lean
e0c63adf7cc4077e5eb911e69de53cdc95119721
5c4b17dae42fab1d4f493f3b52977bffa54fefea
/5.8.2.lean
5a2925f5158abc2625dd8f6882316c39683beb2d
[]
no_license
hyponymous/theorem-proving-in-lean-solutions
9214cb45cc87347862fd17dfdea79fdf24b9df92
a95320ae81c90c1b15da04574602cd378794400d
refs/heads/master
1,585,777,733,214
1,541,039,359,000
1,541,039,359,000
153,676,525
2
0
null
null
null
null
UTF-8
Lean
false
false
602
lean
-- there are several ways of doing this, and probably more compact and/or -- idiomatic ways than what I have here example (p q r : Prop) (hp : p) : (p ∨ q ∨ r) ∧ (q ∨ p ∨ r) ∧ (q ∨ r ∨ p) := by simp * example (p q r : Prop) (hp : p) : (p ∨ q ∨ r) ∧ (q ∨ p ∨ r) ∧ (q ∨ r ∨ p) := by { constructor, left, assumption, constructor, right, left, assumption, right, right, assumption } example (p q r : Prop) (hp : p) : (p ∨ q ∨ r) ∧ (q ∨ p ∨ r) ∧ (q ∨ r ∨ p) := by { repeat { split; repeat { { left, assumption } <|> right <|> assumption } } }
080866301271daef841ca57b8f435fb22cdb14c4
fe84e287c662151bb313504482b218a503b972f3
/src/exercises/mathcomp_book/odd.lean
b3ed8a6b493e77acf831c5213be2c25ddeea6b46
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
3,125
lean
import tactic.interactive tactic.squeeze data.nat.modeq variables n m : nat @[simp] def is_odd_a : ℕ → bool | 0 := ff | (nat.succ n) := bnot (is_odd_a n) #reduce is_odd_a (n + 2) lemma odd_ss_a : is_odd_a (n + 2) = is_odd_a n := begin dsimp[is_odd_a], cases is_odd_a n; refl, end lemma odd_add_a : ∀ n m : ℕ , is_odd_a (n + m) = bxor (is_odd_a n) (is_odd_a m) | n 0 := by rw[is_odd_a,nat.add_zero,bxor_ff] | n (m + 1) := begin rw[nat.add_succ,is_odd_a,is_odd_a,(odd_add_a n m)], cases (is_odd_a n); cases (is_odd_a m); refl, end /- ------------------------------------------------------------ -/ @[simp] def s : ℕ × bool → ℕ × bool | ⟨n,ff⟩ := ⟨n,tt⟩ | ⟨n,tt⟩ := ⟨n.succ,ff⟩ @[simp] def ss : ℕ → ℕ × bool | 0 := ⟨0,ff⟩ | (nat.succ n) := s (ss n) def is_odd_b (n : ℕ) : bool := (ss n).2 #reduce ss (n + 2) lemma odd_ss_b : is_odd_b (n + 2) = is_odd_b n := begin dsimp[is_odd_b,ss,s], rcases (ss n) with ⟨k,tt|ff⟩;refl, end def Nb_add : ℕ × bool → ℕ × bool → ℕ × bool | ⟨n,ff⟩ ⟨m,b⟩ := ⟨n+m,b⟩ | ⟨n,tt⟩ ⟨m,ff⟩ := ⟨n+m,tt⟩ | ⟨n,tt⟩ ⟨m,tt⟩ := ⟨n+m+1,ff⟩ lemma Nb_add_s (u v) : Nb_add u (s v) = s (Nb_add u v) := begin rcases u with ⟨i,ff|tt⟩; rcases v with ⟨j,ff|tt⟩; refl, end lemma ss_add (n m : ℕ) : ss (n + m) = Nb_add (ss n) (ss m) := begin induction m with m ih_m, {rw[add_zero,ss],cases (ss n) with k b; cases b; refl}, {rw[nat.add_succ,ss,ss,ih_m,Nb_add_s],} end lemma odd_add_b : ∀ n m : ℕ, is_odd_b (n + m) = bxor (is_odd_b n) (is_odd_b m) := begin intros n m, rw[is_odd_b,is_odd_b,is_odd_b,ss_add], rcases (ss n) with ⟨i,ff|tt⟩; rcases (ss m) with ⟨j,ff|tt⟩; refl, end /- ------------------------------------------------------------ -/ @[simp] def is_odd_c (n : ℕ) : bool := if n % 2 = 0 then ff else tt lemma odd_ss_c : is_odd_c (n + 2) = is_odd_c n := begin dsimp[is_odd_c], rw [nat.add_mod_right n 2] end /- ------------------------------------------------------------ -/ mutual def is_odd_d, is_even_d with is_odd_d : nat → bool | 0 := ff | (n + 1) := is_even_d n with is_even_d : nat → bool | 0 := tt | (n + 1) := is_odd_d n #check n #reduce is_odd_d (n + 2) lemma odd_ss_d : is_odd_d (n + 2) = is_odd_d n := begin rw[is_odd_d,is_even_d], end lemma odd_even_d : ∀ (n : ℕ), is_odd_d n = bnot (is_even_d n) | 0 := by {rw[is_odd_d,is_even_d],refl} | (n + 1) := by {rw[is_odd_d,is_even_d,odd_even_d n,bnot_bnot],} @[inline] def beq : bool → bool → bool | tt tt := tt | ff ff := tt | _ _ := ff lemma even_add_d : ∀ n m : ℕ, is_even_d (n + m) = beq (is_even_d n) (is_even_d m) := begin intros n m, induction m with m ih_m, {rw[add_zero,is_even_d],cases is_even_d n;refl}, {rw[nat.add_succ,is_even_d,is_even_d,odd_even_d,odd_even_d,ih_m], cases is_even_d n;cases is_even_d m; refl, } end lemma odd_add_d : ∀ n m : ℕ, is_odd_d (n + m) = bxor (is_odd_d n) (is_odd_d m) := begin intros n m, rw[odd_even_d,odd_even_d,odd_even_d,even_add_d], cases is_even_d n;cases is_even_d m; refl, end
7d6463dda91bd2da2e3788ab948dcb1b57c4eac4
d5ecf6c46a2f605470a4a7724909dc4b9e7350e0
/data/int/basic.lean
80304a71a2944b33ded2f006938df251a4a53939
[ "Apache-2.0" ]
permissive
MonoidMusician/mathlib
41f79df478987a636b735c338396813d2e8e44c4
72234ef1a050eea3a2197c23aeb345fc13c08ff3
refs/heads/master
1,583,672,205,771
1,522,892,143,000
1,522,892,143,000
128,144,032
0
0
Apache-2.0
1,522,892,144,000
1,522,890,892,000
Lean
UTF-8
Lean
false
false
42,194
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 algebra.char_zero algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨0⟩ meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩ attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ @[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 theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n 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'] @[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_le_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 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] }, { have := hn _ n_ih, simpa } }, exact this (i + 1) } end /- / -/ theorem of_nat_div (m n : nat) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl theorem neg_succ_of_nat_div (m : nat) {b : ℤ} (H : b > 0) : -[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 : b > 0) : 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 : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 := 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 : a ≥ 0) (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 : b > 0) : 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 @[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, c > 0 → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) : -[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 _ _) @[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ @[simp] 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 _ @[simp] 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 → a % b ≥ 0 | (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 : b > 0) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] 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] @[simp] theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : 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 : b > 0) : 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 : a > 0) : 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 : b > 0) : 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 : a ≥ 0) : 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] /- dvd -/ 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 dvd_antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : 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⟩ theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (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 : a ≥ 0) (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 : a ≥ 0) (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 : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) /- / 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 : c > 0) (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 : c > 0) (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 : c > 0) (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 : c > 0) (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 : c > 0) : 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 : c > 0) (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 : c > 0) (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 : c > 0) (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 : c > 0) : 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 : b ≥ 0) (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 : b ≥ 0) (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 : c > 0) (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 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (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 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 : m ≥ n.succ) : 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 /- 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, { 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) : 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 [(*), int.mul, nat_abs_neg_of_nat] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq] /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le (a : ℤ) (n : ℕ) : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp] 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 i m; simp [bodd]; cases i.bodd; cases m.bodd; refl @[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; unfold has_neg.neg; simp [int.coe_nat_eq, int.neg, bodd] @[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, bodd]; cases m.bodd; cases n.bodd; refl @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd]; cases m.bodd; cases n.bodd; refl theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * (2 ^ n : ℕ) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / (2 ^ n : ℕ) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (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} [HP : decidable_pred P] (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⟩ /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) @[priority 0] instance cast_coe : has_coe ℤ α := ⟨int.cast⟩ @[simp] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl @[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl @[simp] theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n := by simp @[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add]; apply congr_arg (λ x:ℕ, -(x:α)); simp @[simp] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 @[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a := by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *] @[simp] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] theorem eq_cast [add_group α] [has_one α] (f : ℤ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n := begin have H : ∀ (n : ℕ), f n = n := nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y), cases n, {apply H}, apply eq_neg_of_add_eq_zero, rw [← nat.cast_zero, ← H 0, int.coe_nat_zero, ← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1), Hadd, show f (n+1) = n+1, from H (n+1)] end @[simp] theorem cast_id (n : ℤ) : ↑n = n := (eq_cast id rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast end int
8ff2e73711f0f160d58c5d3b3d4aaf560be665cb
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/zmod/polynomial.lean
8b50ceedbc88d8c9f8ee0c4d2b76b81758580744
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
627
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.mv_polynomial.basic import data.zmod.basic /-! ## Facts concerning polynomials over `zmod n` -/ namespace mv_polynomial /-- A polynomial over the integers is divisible by `n : ℕ` if and only if it is zero over `zmod n`. -/ lemma C_dvd_iff_zmod {σ : Type*} (n : ℕ) (φ : mv_polynomial σ ℤ) : C (n:ℤ) ∣ φ ↔ map (int.cast_ring_hom (zmod n)) φ = 0 := C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _ end mv_polynomial
fb33494bcebb25fdf34bd3c56795ea1df4488800
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/noncomp.lean
162d670aa1ab5886567b75b8b5f12c2186b17d63
[ "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
137
lean
open nat axiom n : nat definition f (x : nat) := -- Error this is not computable x + n noncomputable definition g (x : nat) := x + n
ad10162425653b7a593ed88cbda94c4bd9f193d0
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/category_theory/monoidal/of_has_finite_products.lean
b339970530563af6d33593c43209c301967b0aed
[ "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
4,802
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Simon Hudon -/ import category_theory.monoidal.category import category_theory.limits.shapes.binary_products import category_theory.limits.types /-! # The natural monoidal structure on any category with finite (co)products. A category with a monoidal structure provided in this way is sometimes called a (co)cartesian category, although this is also sometimes used to mean a finitely complete category. (See <https://ncatlab.org/nlab/show/cartesian+category>.) As this works with either products or coproducts, and sometimes we want to think of a different monoidal structure entirely, we don't set up either construct as an instance. ## Implementation For the sake of nicer definitional properties, we rely on `has_terminal` and `has_binary_products` instead of `has_finite_products`, so that if a particular category provides customised instances of these we pick those up instead. -/ universes v u namespace category_theory open category_theory.limits variables (C : Type u) [category.{v} C] section local attribute [tidy] tactic.case_bash /-- A category with a terminal object and binary products has a natural monoidal structure. -/ def monoidal_of_has_finite_products [has_terminal C] [has_binary_products C] : monoidal_category C := { tensor_unit := ⊤_ C, tensor_obj := λ X Y, X ⨯ Y, tensor_hom := λ _ _ _ _ f g, limits.prod.map f g, associator := prod.associator, left_unitor := prod.left_unitor, right_unitor := prod.right_unitor, pentagon' := prod.pentagon, triangle' := prod.triangle, associator_naturality' := @prod.associator_naturality _ _ _, } end namespace monoidal_of_has_finite_products variables [has_terminal C] [has_binary_products C] local attribute [instance] monoidal_of_has_finite_products @[simp] lemma tensor_obj (X Y : C) : X ⊗ Y = (X ⨯ Y) := rfl @[simp] lemma tensor_hom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : f ⊗ g = limits.prod.map f g := rfl @[simp] lemma left_unitor_hom (X : C) : (λ_ X).hom = limits.prod.snd := rfl @[simp] lemma left_unitor_inv (X : C) : (λ_ X).inv = prod.lift (terminal.from X) (𝟙 _) := rfl @[simp] lemma right_unitor_hom (X : C) : (ρ_ X).hom = limits.prod.fst := rfl @[simp] lemma right_unitor_inv (X : C) : (ρ_ X).inv = prod.lift (𝟙 _) (terminal.from X) := rfl -- We don't mark this as a simp lemma, even though in many particular -- categories the right hand side will simplify significantly further. -- For now, we'll plan to create specialised simp lemmas in each particular category. lemma associator_hom (X Y Z : C) : (α_ X Y Z).hom = prod.lift (limits.prod.fst ≫ limits.prod.fst) (prod.lift (limits.prod.fst ≫ limits.prod.snd) limits.prod.snd) := rfl end monoidal_of_has_finite_products section local attribute [tidy] tactic.case_bash /-- A category with an initial object and binary coproducts has a natural monoidal structure. -/ def monoidal_of_has_finite_coproducts [has_initial C] [has_binary_coproducts C] : monoidal_category C := { tensor_unit := ⊥_ C, tensor_obj := λ X Y, X ⨿ Y, tensor_hom := λ _ _ _ _ f g, limits.coprod.map f g, associator := coprod.associator, left_unitor := coprod.left_unitor, right_unitor := coprod.right_unitor, pentagon' := coprod.pentagon, triangle' := coprod.triangle, associator_naturality' := @coprod.associator_naturality _ _ _, } end namespace monoidal_of_has_finite_coproducts variables [has_initial C] [has_binary_coproducts C] local attribute [instance] monoidal_of_has_finite_coproducts @[simp] lemma tensor_obj (X Y : C) : X ⊗ Y = (X ⨿ Y) := rfl @[simp] lemma tensor_hom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : f ⊗ g = limits.coprod.map f g := rfl @[simp] lemma left_unitor_hom (X : C) : (λ_ X).hom = coprod.desc (initial.to X) (𝟙 _) := rfl @[simp] lemma right_unitor_hom (X : C) : (ρ_ X).hom = coprod.desc (𝟙 _) (initial.to X) := rfl @[simp] lemma left_unitor_inv (X : C) : (λ_ X).inv = limits.coprod.inr := rfl @[simp] lemma right_unitor_inv (X : C) : (ρ_ X).inv = limits.coprod.inl := rfl -- We don't mark this as a simp lemma, even though in many particular -- categories the right hand side will simplify significantly further. -- For now, we'll plan to create specialised simp lemmas in each particular category. lemma associator_hom (X Y Z : C) : (α_ X Y Z).hom = coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr) := rfl end monoidal_of_has_finite_coproducts end category_theory -- TODO in fact, a category with finite products is braided, and symmetric, -- and we should say that here, once braided categories arrive in mathlib.
8dc86b325a3f3c81bcaab448a7dc6723be030454
618003631150032a5676f229d13a079ac875ff77
/src/data/set/finite.lean
bb843129581adb79ec1c9fa7fa9bffe23f82d23e
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
23,131
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.fintype.basic import algebra.big_operators /-! # Finite sets This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some basic facts about finite sets. -/ open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s /-- The subtype corresponding to a finite set is a finite type. Note that because `finite` isn't a typeclass, this will not fire if it is made into an instance -/ noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ h.fintype @[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s := @set.coe_to_finset _ s h.fintype theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := ⟨hs.to_finset, hs.coe_to_finset⟩ /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) := { coe := coe, cond := finite, prf := λ s hs, hs.exists_finset_coe } theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype.of_finset s (λ _, iff.rfl)⟩ theorem finite.of_fintype [fintype α] (s : set α) : finite s := by classical; exact ⟨set_fintype s⟩ /-- Membership of a subset of a finite type is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ /-- A `fintype` structure on `insert a s`. -/ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a :: s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert' s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h section local attribute [instance] decidable_mem_of_fintype instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h end @[simp] theorem finite_insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (finite_insert a hs).to_finset = insert a hs.to_finset := finset.ext.mpr $ by simp @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (finite_insert a h)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := unique.fintype @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton theorem finite_pure (a : α) : finite (pure a : set α) := ⟨set.fintype_pure a⟩ instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α $ (equiv.set.univ α).symm theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩ theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α := ⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ $ @fintype.of_equiv _ _ h₂ $ equiv.set.univ _⟩ theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) := infinite_univ_iff.2 h instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp theorem finite_union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) := set.fintype_sep s t def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t := by rw ← inter_eq_self_of_subset_right h; apply_instance theorem finite_subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype.of_finset (finset.univ.image f) $ by simp [range] theorem finite_range (f : α → β) [fintype α] : finite (range f) := by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩ theorem finite_image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ lemma finite_dependent_image {s : set α} (hs : finite s) {F : Π i ∈ s, β} {t : set β} (H : ∀ y ∈ t, ∃ x (hx : x ∈ s), y = F x hx) : set.finite t := begin let G : s → β := λ x, F x.1 x.2, have A : t ⊆ set.range G, { assume y hy, rcases H y hy with ⟨x, hx, xy⟩, refine ⟨⟨x, hx⟩, xy.symm⟩ }, letI : fintype s := finite.fintype hs, exact finite_subset (finite_range G) A end instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image theorem finite_map {α β} {s : set α} : ∀ (f : α → β), finite s → finite (f <$> s) := finite_image def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end theorem finite_of_finite_image_on {s : set α} {f : α → β} (hi : set.inj_on f s) : finite (f '' s) → finite s | ⟨h⟩ := ⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $ assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext.1 eq⟩ theorem finite_image_iff_on {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := ⟨finite_of_finite_image_on hi, finite_image _⟩ theorem finite_of_finite_image {s : set α} {f : α → β} (I : set.inj_on f s) : finite (f '' s) → finite s := finite_of_finite_image_on I theorem finite_preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (finite_subset h (image_preimage_subset f s)) instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) := by rw bUnion_eq_Union; exact @set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi) instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) := fintype_bUnion _ (λ i _, H i) theorem finite_sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H theorem finite_bUnion {α} {ι : Type*} {s : set ι} {f : ι → set α} : finite s → (∀i, finite (f i)) → finite (⋃ i∈s, f i) | ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _) theorem finite_bUnion' {α} {ι : Type*} {s : set ι} (f : ι → set α) : finite s → (∀i ∈ s, finite (f i)) → finite (⋃ i∈s, f i) | ⟨hs⟩ h := by { rw [bUnion_eq_Union], exactI finite_Union (λ i, h i.1 i.2) } instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype.of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite_prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion _ H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := fintype_bind _ _ (λ i _, H i) theorem finite_bind {α β} {s : set α} {f : α → set β} : finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f) | ⟨hs⟩ H := ⟨@fintype_bind _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩ instance fintype_seq {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := by rw seq_eq_bind_map; apply set.fintype_bind' theorem finite_seq {α β : Type u} {f : set (α → β)} {s : set α} : finite f → finite s → finite (f <*> s) | ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ } /-- There are finitely many subsets of a given finite set -/ lemma finite_subsets_of_finite {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} := begin -- we just need to translate the result, already known for finsets, -- to the language of finite sets let s : set (set α) := coe '' (↑(finset.powerset (finite.to_finset h)) : set (finset α)), have : finite s := finite_image _ (finite_mem_finset _), apply finite_subset this, refine λ b hb, ⟨(finite_subset h hb).to_finset, _, finite.coe_to_finset _⟩, simpa [finset.subset_iff] end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_min_image f ⟨x, finite.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_max_image f ⟨x, finite.mem_to_finset.2 hx⟩ end set namespace finset variables [decidable_eq β] variables {s : finset α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] end finset namespace set lemma finite_subset_Union {s : set α} (hs : finite s) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i := begin unfreezeI, cases hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, _⟩, rintro x hx, simp, exact ⟨x, ⟨hx, hf _⟩⟩, end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, finite_subset tfin (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f)) (hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) := finite_subset (finite_union hf hg) range_ite_subset lemma finite_range_const {c : β} : finite (range (λ x : α, c)) := finite_subset (finite_singleton c) range_const_subset lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}: range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) := by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] } lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : finite (range (λ x, nat.find_greatest (P x) b)) := finite_subset (finset.finite_to_set $ finset.range (b + 1)) range_find_greatest_subset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := begin rw [← s.coe_to_finset, ← t.coe_to_finset, finset.coe_ssubset] at h, rw [fintype.card_of_finset' _ (λ x, mem_to_finset), fintype.card_of_finset' _ (λ x, mem_to_finset)], exact finset.card_lt_card h, end lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := calc fintype.card s = s.to_finset.card : fintype.card_of_finset' _ (by simp) ... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *) ... = fintype.card t : eq.symm (fintype.card_of_finset' _ (by simp)) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr (@equiv.of_bijective _ _ (λ a : α, show range f, from ⟨f a, a, rfl⟩) ⟨λ x y h, hf $ subtype.mk.inj h, λ b, let ⟨a, ha⟩ := b.2 in ⟨a, by simp *⟩⟩) lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' := begin classical, refine h.induction_on _ _, { assume h, exact absurd h empty_not_nonempty }, assume a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end section local attribute [instance, priority 1] classical.prop_decidable lemma to_finset_card {α : Type*} [fintype α] (H : set α) : H.to_finset.card = fintype.card H := multiset.card_map subtype.val finset.univ.val lemma to_finset_inter {α : Type*} [fintype α] (s t : set α) [decidable_eq α] : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by ext; simp end section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ lemma bdd_above_finite (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma bdd_above_finite_union {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ lemma bdd_below_finite (hs : finite s) : bdd_below s := finite.induction_on hs bdd_below_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded below is still bounded below.-/ lemma bdd_below_finite_union {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := @bdd_above_finite_union (order_dual α) _ _ _ _ _ H end end set namespace finset section preimage /-- Preimage of `s : finset β` under a map `f` injective of `f ⁻¹' s` as a `finset`. -/ noncomputable def preimage {f : α → β} (s : finset β) (hf : set.inj_on f (f ⁻¹' ↑s)) : finset α := (set.finite_preimage hf (set.finite_mem_finset s)).to_finset @[simp] lemma mem_preimage {f : α → β} {s : finset β} {hf : set.inj_on f (f ⁻¹' ↑s)} {x : α} : x ∈ preimage s hf ↔ f x ∈ s := set.finite.mem_to_finset @[simp, norm_cast] lemma coe_preimage {f : α → β} (s : finset β) (hf : set.inj_on f (f ⁻¹' ↑s)) : (↑(preimage s hf) : set α) = f ⁻¹' ↑s := set.finite.coe_to_finset _ lemma image_preimage [decidable_eq β] (f : α → β) (s : finset β) (hf : set.bij_on f (f ⁻¹' ↑s) ↑s) : image f (preimage s hf.inj_on) = s := finset.coe_inj.1 $ suffices f '' (f ⁻¹' ↑s) = ↑s, by simpa, (set.subset.antisymm (image_preimage_subset _ _) hf.surj_on) end preimage @[to_additive] lemma prod_preimage [comm_monoid β] (f : α → γ) (s : finset γ) (hf : set.bij_on f (f ⁻¹' ↑s) ↑s) (g : γ → β) : (preimage s hf.inj_on).prod (g ∘ f) = s.prod g := by classical; calc (preimage s hf.inj_on).prod (g ∘ f) = (image f (preimage s hf.inj_on)).prod g : begin rw prod_image, intros x hx y hy hxy, apply hf.inj_on, repeat { try { rw mem_preimage at hx hy, rw [set.mem_preimage, mem_coe] }, assumption }, end ... = s.prod g : by rw [image_preimage] /-- A finset is bounded above. -/ lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := set.bdd_above_finite (finset.finite_to_set s) /-- A finset is bounded below. -/ lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := set.bdd_below_finite (finset.finite_to_set s) end finset lemma fintype.exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := begin rcases set.finite_univ.exists_maximal_wrt f _ univ_nonempty with ⟨x, _, hx⟩, exact ⟨x, λ y, (le_total (f x) (f y)).elim (λ h, ge_of_eq $ hx _ trivial h) id⟩ end
7c74369915c16f6b28a61b173635edc693e3a848
022547453607c6244552158ff25ab3bf17361760
/src/algebra/pointwise.lean
246b77dd56d5caf136ca9d796e78f380e0069108
[ "Apache-2.0" ]
permissive
1293045656/mathlib
5f81741a7c1ff1873440ec680b3680bfb6b7b048
4709e61525a60189733e72a50e564c58d534bed8
refs/heads/master
1,687,010,200,553
1,626,245,646,000
1,626,245,646,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,624
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import algebra.module.basic import data.set.finite import group_theory.submonoid.basic /-! # Pointwise addition, multiplication, and scalar multiplication of sets. This file defines pointwise algebraic operations on sets. * For a type `α` with multiplication, multiplication is defined on `set α` by taking `s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Similarly for addition. * For `α` a semigroup, `set α` is a semigroup. * If `α` is a (commutative) monoid, we define an alias `set_semiring α` for `set α`, which then becomes a (commutative) semiring with union as addition and pointwise multiplication as multiplication. * For a type `β` with scalar multiplication by another type `α`, this file defines a scalar multiplication of `set β` by `set α` and a separate scalar multiplication of `set β` by `α`. * We also define pointwise multiplication on `finset`. Appropriate definitions and results are also transported to the additive theory via `to_additive`. ## Implementation notes * The following expressions are considered in simp-normal form in a group: `(λ h, h * g) ⁻¹' s`, `(λ h, g * h) ⁻¹' s`, `(λ h, h * g⁻¹) ⁻¹' s`, `(λ h, g⁻¹ * h) ⁻¹' s`, `s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants). Expressions equal to one of these will be simplified. ## Tags set multiplication, set addition, pointwise addition, pointwise multiplication -/ namespace set open function variables {α : Type*} {β : Type*} {s s₁ s₂ t t₁ t₂ u : set α} {a b : α} {x y : β} /-! ### Properties about 1 -/ @[to_additive] instance [has_one α] : has_one (set α) := ⟨{1}⟩ @[to_additive] lemma singleton_one [has_one α] : ({1} : set α) = 1 := rfl @[simp, to_additive] lemma mem_one [has_one α] : a ∈ (1 : set α) ↔ a = 1 := iff.rfl @[to_additive] lemma one_mem_one [has_one α] : (1 : α) ∈ (1 : set α) := eq.refl _ @[simp, to_additive] theorem one_subset [has_one α] : 1 ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff @[to_additive] theorem one_nonempty [has_one α] : (1 : set α).nonempty := ⟨1, rfl⟩ @[simp, to_additive] theorem image_one [has_one α] {f : α → β} : f '' 1 = {f 1} := image_singleton /-! ### Properties about multiplication -/ @[to_additive] instance [has_mul α] : has_mul (set α) := ⟨image2 has_mul.mul⟩ @[simp, to_additive] lemma image2_mul [has_mul α] : image2 has_mul.mul s t = s * t := rfl @[to_additive] lemma mem_mul [has_mul α] : a ∈ s * t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x * y = a := iff.rfl @[to_additive] lemma mul_mem_mul [has_mul α] (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := mem_image2_of_mem ha hb @[to_additive add_image_prod] lemma image_mul_prod [has_mul α] : (λ x : α × α, x.fst * x.snd) '' s.prod t = s * t := image_prod _ @[simp, to_additive] lemma image_mul_left [group α] : (λ b, a * b) '' t = (λ b, a⁻¹ * b) ⁻¹' t := by { rw image_eq_preimage_of_inverse; intro c; simp } @[simp, to_additive] lemma image_mul_right [group α] : (λ a, a * b) '' t = (λ a, a * b⁻¹) ⁻¹' t := by { rw image_eq_preimage_of_inverse; intro c; simp } @[to_additive] lemma image_mul_left' [group α] : (λ b, a⁻¹ * b) '' t = (λ b, a * b) ⁻¹' t := by simp @[to_additive] lemma image_mul_right' [group α] : (λ a, a * b⁻¹) '' t = (λ a, a * b) ⁻¹' t := by simp @[simp, to_additive] lemma preimage_mul_left_singleton [group α] : ((*) a) ⁻¹' {b} = {a⁻¹ * b} := by rw [← image_mul_left', image_singleton] @[simp, to_additive] lemma preimage_mul_right_singleton [group α] : (* a) ⁻¹' {b} = {b * a⁻¹} := by rw [← image_mul_right', image_singleton] @[simp, to_additive] lemma preimage_mul_left_one [group α] : (λ b, a * b) ⁻¹' 1 = {a⁻¹} := by rw [← image_mul_left', image_one, mul_one] @[simp, to_additive] lemma preimage_mul_right_one [group α] : (λ a, a * b) ⁻¹' 1 = {b⁻¹} := by rw [← image_mul_right', image_one, one_mul] @[to_additive] lemma preimage_mul_left_one' [group α] : (λ b, a⁻¹ * b) ⁻¹' 1 = {a} := by simp @[to_additive] lemma preimage_mul_right_one' [group α] : (λ a, a * b⁻¹) ⁻¹' 1 = {b} := by simp @[simp, to_additive] lemma mul_singleton [has_mul α] : s * {b} = (λ a, a * b) '' s := image2_singleton_right @[simp, to_additive] lemma singleton_mul [has_mul α] : {a} * t = (λ b, a * b) '' t := image2_singleton_left @[simp, to_additive] lemma singleton_mul_singleton [has_mul α] : ({a} : set α) * {b} = {a * b} := image2_singleton @[to_additive set.add_zero_class] instance [mul_one_class α] : mul_one_class (set α) := { mul_one := λ s, by { simp only [← singleton_one, mul_singleton, mul_one, image_id'] }, one_mul := λ s, by { simp only [← singleton_one, singleton_mul, one_mul, image_id'] }, ..set.has_one, ..set.has_mul } @[to_additive set.add_semigroup] instance [semigroup α] : semigroup (set α) := { mul_assoc := λ _ _ _, image2_assoc mul_assoc, ..set.has_mul } @[to_additive set.add_monoid] instance [monoid α] : monoid (set α) := { ..set.semigroup, ..set.mul_one_class } lemma pow_mem_pow [monoid α] (ha : a ∈ s) (n : ℕ) : a ^ n ∈ s ^ n := begin induction n with n ih, { rw pow_zero, exact set.mem_singleton 1 }, { rw pow_succ, exact set.mul_mem_mul ha ih }, end @[to_additive] protected lemma mul_comm [comm_semigroup α] : s * t = t * s := by simp only [← image2_mul, image2_swap _ s, mul_comm] @[to_additive set.add_comm_monoid] instance [comm_monoid α] : comm_monoid (set α) := { mul_comm := λ _ _, set.mul_comm, ..set.monoid } @[to_additive] lemma singleton.is_mul_hom [has_mul α] : is_mul_hom (singleton : α → set α) := { map_mul := λ a b, singleton_mul_singleton.symm } @[simp, to_additive] lemma empty_mul [has_mul α] : ∅ * s = ∅ := image2_empty_left @[simp, to_additive] lemma mul_empty [has_mul α] : s * ∅ = ∅ := image2_empty_right lemma empty_pow [monoid α] (n : ℕ) (hn : n ≠ 0) : (∅ : set α) ^ n = ∅ := by rw [←nat.sub_add_cancel (nat.pos_of_ne_zero hn), pow_succ, empty_mul] instance decidable_mem_mul [monoid α] [fintype α] [decidable_eq α] [decidable_pred (∈ s)] [decidable_pred (∈ t)] : decidable_pred (∈ s * t) := λ _, decidable_of_iff _ mem_mul.symm instance decidable_mem_pow [monoid α] [fintype α] [decidable_eq α] [decidable_pred (∈ s)] (n : ℕ) : decidable_pred (∈ (s ^ n)) := begin induction n with n ih, { simp_rw [pow_zero, mem_one], apply_instance }, { letI := ih, rw pow_succ, apply_instance } end @[to_additive] lemma mul_subset_mul [has_mul α] (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ := image2_subset h₁ h₂ lemma pow_subset_pow [monoid α] (hst : s ⊆ t) (n : ℕ) : s ^ n ⊆ t ^ n := begin induction n with n ih, { rw pow_zero, exact subset.rfl }, { rw [pow_succ, pow_succ], exact mul_subset_mul hst ih }, end @[to_additive] lemma union_mul [has_mul α] : (s ∪ t) * u = (s * u) ∪ (t * u) := image2_union_left @[to_additive] lemma mul_union [has_mul α] : s * (t ∪ u) = (s * t) ∪ (s * u) := image2_union_right @[to_additive] lemma Union_mul_left_image [has_mul α] : (⋃ a ∈ s, (λ x, a * x) '' t) = s * t := Union_image_left _ @[to_additive] lemma Union_mul_right_image [has_mul α] : (⋃ a ∈ t, (λ x, x * a) '' s) = s * t := Union_image_right _ @[simp, to_additive] lemma univ_mul_univ [monoid α] : (univ : set α) * univ = univ := begin have : ∀x, ∃a b : α, a * b = x := λx, ⟨x, ⟨1, mul_one x⟩⟩, simpa only [mem_mul, eq_univ_iff_forall, mem_univ, true_and] end /-- `singleton` is a monoid hom. -/ @[to_additive singleton_add_hom "singleton is an add monoid hom"] def singleton_hom [monoid α] : α →* set α := { to_fun := singleton, map_one' := rfl, map_mul' := λ a b, singleton_mul_singleton.symm } @[to_additive] lemma nonempty.mul [has_mul α] : s.nonempty → t.nonempty → (s * t).nonempty := nonempty.image2 @[to_additive] lemma finite.mul [has_mul α] (hs : finite s) (ht : finite t) : finite (s * t) := hs.image2 _ ht /-- multiplication preserves finiteness -/ @[to_additive "addition preserves finiteness"] def fintype_mul [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] : fintype (s * t : set α) := set.fintype_image2 _ s t @[to_additive] lemma bdd_above_mul [ordered_comm_monoid α] {A B : set α} : bdd_above A → bdd_above B → bdd_above (A * B) := begin rintros ⟨bA, hbA⟩ ⟨bB, hbB⟩, use bA * bB, rintros x ⟨xa, xb, hxa, hxb, rfl⟩, exact mul_le_mul' (hbA hxa) (hbB hxb), end section big_operators open_locale big_operators variables {ι : Type*} [comm_monoid α] /-- The n-ary version of `set.mem_mul`. -/ @[to_additive /-" The n-ary version of `set.mem_add`. "-/] lemma mem_finset_prod (t : finset ι) (f : ι → set α) (a : α) : a ∈ ∏ i in t, f i ↔ ∃ (g : ι → α) (hg : ∀ {i}, i ∈ t → g i ∈ f i), ∏ i in t, g i = a := begin classical, induction t using finset.induction_on with i is hi ih generalizing a, { simp_rw [finset.prod_empty, set.mem_one], exact ⟨λ h, ⟨λ i, a, λ i, false.elim, h.symm⟩, λ ⟨f, _, hf⟩, hf.symm⟩ }, rw [finset.prod_insert hi, set.mem_mul], simp_rw [finset.prod_insert hi], simp_rw ih, split, { rintros ⟨x, y, hx, ⟨g, hg, rfl⟩, rfl⟩, refine ⟨function.update g i x, λ j hj, _, _⟩, obtain rfl | hj := finset.mem_insert.mp hj, { rw function.update_same, exact hx }, { rw update_noteq (ne_of_mem_of_not_mem hj hi), exact hg hj, }, rw [finset.prod_update_of_not_mem hi, function.update_same], }, { rintros ⟨g, hg, rfl⟩, exact ⟨g i, is.prod g, hg (is.mem_insert_self _), ⟨g, λ i hi, hg (finset.mem_insert_of_mem hi), rfl⟩, rfl⟩ }, end /-- A version of `set.mem_finset_prod` with a simpler RHS for products over a fintype. -/ @[to_additive /-" A version of `set.mem_finset_sum` with a simpler RHS for sums over a fintype. "-/] lemma mem_fintype_prod [fintype ι] (f : ι → set α) (a : α) : a ∈ ∏ i, f i ↔ ∃ (g : ι → α) (hg : ∀ i, g i ∈ f i), ∏ i, g i = a := by { rw mem_finset_prod, simp } /-- The n-ary version of `set.mul_mem_mul`. -/ @[to_additive /-" The n-ary version of `set.add_mem_add`. "-/] lemma finset_prod_mem_finset_prod (t : finset ι) (f : ι → set α) (g : ι → α) (hg : ∀ i ∈ t, g i ∈ f i) : ∏ i in t, g i ∈ ∏ i in t, f i := by { rw mem_finset_prod, exact ⟨g, hg, rfl⟩ } /-- The n-ary version of `set.mul_subset_mul`. -/ @[to_additive /-" The n-ary version of `set.add_subset_add`. "-/] lemma finset_prod_subset_finset_prod (t : finset ι) (f₁ f₂ : ι → set α) (hf : ∀ {i}, i ∈ t → f₁ i ⊆ f₂ i) : ∏ i in t, f₁ i ⊆ ∏ i in t, f₂ i := begin intro a, rw [mem_finset_prod, mem_finset_prod], rintro ⟨g, hg, rfl⟩, exact ⟨g, λ i hi, hf hi $ hg hi, rfl⟩ end /-! TODO: define `decidable_mem_finset_prod` and `decidable_mem_finset_sum`. -/ end big_operators /-! ### Properties about inversion -/ @[to_additive set.has_neg] instance [has_inv α] : has_inv (set α) := ⟨preimage has_inv.inv⟩ @[simp, to_additive] lemma mem_inv [has_inv α] : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := iff.rfl @[to_additive] lemma inv_mem_inv [group α] : a⁻¹ ∈ s⁻¹ ↔ a ∈ s := by simp only [mem_inv, inv_inv] @[simp, to_additive] lemma inv_preimage [has_inv α] : has_inv.inv ⁻¹' s = s⁻¹ := rfl @[simp, to_additive] lemma image_inv [group α] : has_inv.inv '' s = s⁻¹ := by { simp only [← inv_preimage], rw [image_eq_preimage_of_inverse]; intro; simp only [inv_inv] } @[simp, to_additive] lemma inter_inv [has_inv α] : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := preimage_inter @[simp, to_additive] lemma union_inv [has_inv α] : (s ∪ t)⁻¹ = s⁻¹ ∪ t⁻¹ := preimage_union @[simp, to_additive] lemma compl_inv [has_inv α] : (sᶜ)⁻¹ = (s⁻¹)ᶜ := preimage_compl @[simp, to_additive] protected lemma inv_inv [group α] : s⁻¹⁻¹ = s := by { simp only [← inv_preimage, preimage_preimage, inv_inv, preimage_id'] } @[simp, to_additive] protected lemma univ_inv [group α] : (univ : set α)⁻¹ = univ := preimage_univ @[simp, to_additive] lemma inv_subset_inv [group α] {s t : set α} : s⁻¹ ⊆ t⁻¹ ↔ s ⊆ t := (equiv.inv α).surjective.preimage_subset_preimage_iff @[to_additive] lemma inv_subset [group α] {s t : set α} : s⁻¹ ⊆ t ↔ s ⊆ t⁻¹ := by { rw [← inv_subset_inv, set.inv_inv] } @[to_additive] lemma finite.inv [group α] {s : set α} (hs : finite s) : finite s⁻¹ := hs.preimage $ inv_injective.inj_on _ /-! ### Properties about scalar multiplication -/ /-- Scaling a set: multiplying every element by a scalar. -/ instance has_scalar_set [has_scalar α β] : has_scalar α (set β) := ⟨λ a, image (has_scalar.smul a)⟩ @[simp] lemma image_smul [has_scalar α β] {t : set β} : (λ x, a • x) '' t = a • t := rfl lemma mem_smul_set [has_scalar α β] {t : set β} : x ∈ a • t ↔ ∃ y, y ∈ t ∧ a • y = x := iff.rfl lemma smul_mem_smul_set [has_scalar α β] {t : set β} (hy : y ∈ t) : a • y ∈ a • t := ⟨y, hy, rfl⟩ lemma smul_set_union [has_scalar α β] {s t : set β} : a • (s ∪ t) = a • s ∪ a • t := by simp only [← image_smul, image_union] @[simp] lemma smul_set_empty [has_scalar α β] (a : α) : a • (∅ : set β) = ∅ := by rw [← image_smul, image_empty] lemma smul_set_mono [has_scalar α β] {s t : set β} (h : s ⊆ t) : a • s ⊆ a • t := by { simp only [← image_smul, image_subset, h] } /-- Pointwise scalar multiplication by a set of scalars. -/ instance [has_scalar α β] : has_scalar (set α) (set β) := ⟨image2 has_scalar.smul⟩ @[simp] lemma image2_smul [has_scalar α β] {t : set β} : image2 has_scalar.smul s t = s • t := rfl lemma mem_smul [has_scalar α β] {t : set β} : x ∈ s • t ↔ ∃ a y, a ∈ s ∧ y ∈ t ∧ a • y = x := iff.rfl lemma image_smul_prod [has_scalar α β] {t : set β} : (λ x : α × β, x.fst • x.snd) '' s.prod t = s • t := image_prod _ theorem range_smul_range [has_scalar α β] {ι κ : Type*} (b : ι → α) (c : κ → β) : range b • range c = range (λ p : ι × κ, b p.1 • c p.2) := ext $ λ x, ⟨λ hx, let ⟨p, q, ⟨i, hi⟩, ⟨j, hj⟩, hpq⟩ := set.mem_smul.1 hx in ⟨(i, j), hpq ▸ hi ▸ hj ▸ rfl⟩, λ ⟨⟨i, j⟩, h⟩, set.mem_smul.2 ⟨b i, c j, ⟨i, rfl⟩, ⟨j, rfl⟩, h⟩⟩ lemma singleton_smul [has_scalar α β] {t : set β} : ({a} : set α) • t = a • t := image2_singleton_left section monoid /-! ### `set α` as a `(∪,*)`-semiring -/ /-- An alias for `set α`, which has a semiring structure given by `∪` as "addition" and pointwise multiplication `*` as "multiplication". -/ @[derive inhabited] def set_semiring (α : Type*) : Type* := set α /-- The identitiy function `set α → set_semiring α`. -/ protected def up (s : set α) : set_semiring α := s /-- The identitiy function `set_semiring α → set α`. -/ protected def set_semiring.down (s : set_semiring α) : set α := s @[simp] protected lemma down_up {s : set α} : s.up.down = s := rfl @[simp] protected lemma up_down {s : set_semiring α} : s.down.up = s := rfl instance set_semiring.add_comm_monoid : add_comm_monoid (set_semiring α) := { add := λ s t, (s ∪ t : set α), zero := (∅ : set α), add_assoc := union_assoc, zero_add := empty_union, add_zero := union_empty, add_comm := union_comm, } instance set_semiring.non_unital_non_assoc_semiring [has_mul α] : non_unital_non_assoc_semiring (set_semiring α) := { zero_mul := λ s, empty_mul, mul_zero := λ s, mul_empty, left_distrib := λ _ _ _, mul_union, right_distrib := λ _ _ _, union_mul, ..set.has_mul, ..set_semiring.add_comm_monoid } instance set_semiring.non_assoc_semiring [mul_one_class α] : non_assoc_semiring (set_semiring α) := { ..set_semiring.non_unital_non_assoc_semiring, ..set.mul_one_class } instance set_semiring.non_unital_semiring [semigroup α] : non_unital_semiring (set_semiring α) := { ..set_semiring.non_unital_non_assoc_semiring, ..set.semigroup } instance set_semiring.semiring [monoid α] : semiring (set_semiring α) := { ..set_semiring.non_assoc_semiring, ..set_semiring.non_unital_semiring } instance set_semiring.comm_semiring [comm_monoid α] : comm_semiring (set_semiring α) := { ..set.comm_monoid, ..set_semiring.semiring } /-- A multiplicative action of a monoid on a type β gives also a multiplicative action on the subsets of β. -/ instance mul_action_set [monoid α] [mul_action α β] : mul_action α (set β) := { mul_smul := by { intros, simp only [← image_smul, image_image, ← mul_smul] }, one_smul := by { intros, simp only [← image_smul, image_eta, one_smul, image_id'] }, ..set.has_scalar_set } section is_mul_hom open is_mul_hom variables [has_mul α] [has_mul β] (m : α → β) [is_mul_hom m] @[to_additive] lemma image_mul : m '' (s * t) = m '' s * m '' t := by { simp only [← image2_mul, image_image2, image2_image_left, image2_image_right, map_mul m] } @[to_additive] lemma preimage_mul_preimage_subset {s t : set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) := by { rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, _, ‹_›, ‹_›, (map_mul _ _ _).symm ⟩ } end is_mul_hom /-- The image of a set under function is a ring homomorphism with respect to the pointwise operations on sets. -/ def image_hom [monoid α] [monoid β] (f : α →* β) : set_semiring α →+* set_semiring β := { to_fun := image f, map_zero' := image_empty _, map_one' := by simp only [← singleton_one, image_singleton, is_monoid_hom.map_one f], map_add' := image_union _, map_mul' := λ _ _, image_mul _ } end monoid end set open set section variables {α : Type*} {β : Type*} /-- A nonempty set in a module is scaled by zero to the singleton containing 0 in the module. -/ lemma zero_smul_set [semiring α] [add_comm_monoid β] [module α β] {s : set β} (h : s.nonempty) : (0 : α) • s = (0 : set β) := by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero] lemma mem_inv_smul_set_iff [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A := by simp only [← image_smul, mem_image, inv_smul_eq_iff' ha, exists_eq_right] lemma mem_smul_set_iff_inv_smul_mem [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A := by rw [← mem_inv_smul_set_iff $ inv_ne_zero ha, inv_inv'] end namespace finset variables {α : Type*} [decidable_eq α] /-- The pointwise product of two finite sets `s` and `t`: `st = s ⬝ t = s * t = { x * y | x ∈ s, y ∈ t }`. -/ @[to_additive "The pointwise sum of two finite sets `s` and `t`: `s + t = { x + y | x ∈ s, y ∈ t }`."] instance [has_mul α] : has_mul (finset α) := ⟨λ s t, (s.product t).image (λ p : α × α, p.1 * p.2)⟩ @[to_additive] lemma mul_def [has_mul α] {s t : finset α} : s * t = (s.product t).image (λ p : α × α, p.1 * p.2) := rfl @[to_additive] lemma mem_mul [has_mul α] {s t : finset α} {x : α} : x ∈ s * t ↔ ∃ y z, y ∈ s ∧ z ∈ t ∧ y * z = x := by { simp only [finset.mul_def, and.assoc, mem_image, exists_prop, prod.exists, mem_product] } @[simp, norm_cast, to_additive] lemma coe_mul [has_mul α] {s t : finset α} : (↑(s * t) : set α) = ↑s * ↑t := by { ext, simp only [mem_mul, set.mem_mul, mem_coe] } @[to_additive] lemma mul_mem_mul [has_mul α] {s t : finset α} {x y : α} (hx : x ∈ s) (hy : y ∈ t) : x * y ∈ s * t := by { simp only [finset.mem_mul], exact ⟨x, y, hx, hy, rfl⟩ } lemma add_card_le [has_add α] {s t : finset α} : (s + t).card ≤ s.card * t.card := by { convert finset.card_image_le, rw [finset.card_product, mul_comm] } @[to_additive] lemma mul_card_le [has_mul α] {s t : finset α} : (s * t).card ≤ s.card * t.card := by { convert finset.card_image_le, rw [finset.card_product, mul_comm] } open_locale classical /-- A finite set `U` contained in the product of two sets `S * S'` is also contained in the product of two finite sets `T * T' ⊆ S * S'`. -/ @[to_additive] lemma subset_mul {M : Type*} [monoid M] {S : set M} {S' : set M} {U : finset M} (f : ↑U ⊆ S * S') : ∃ (T T' : finset M), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ U ⊆ T * T' := begin apply finset.induction_on' U, { use [∅, ∅], simp only [finset.empty_subset, finset.coe_empty, set.empty_subset, and_self], }, rintros a s haU hs has ⟨T, T', hS, hS', h⟩, obtain ⟨x, y, hx, hy, ha⟩ := set.mem_mul.1 (f haU), use [insert x T, insert y T'], simp only [finset.coe_insert], repeat { rw [set.insert_subset], }, use [hx, hS, hy, hS'], refine finset.insert_subset.mpr ⟨_, _⟩, { rw finset.mem_mul, use [x,y], simpa only [true_and, true_or, eq_self_iff_true, finset.mem_insert], }, { suffices g : (s : set M) ⊆ insert x T * insert y T', { norm_cast at g, assumption, }, transitivity ↑(T * T'), apply h, rw finset.coe_mul, apply set.mul_subset_mul (set.subset_insert x T) (set.subset_insert y T'), }, end end finset /-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in `group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/ namespace submonoid variables {M : Type*} [monoid M] @[to_additive] lemma mul_subset {s t : set M} {S : submonoid M} (hs : s ⊆ S) (ht : t ⊆ S) : s * t ⊆ S := by { rintro _ ⟨p, q, hp, hq, rfl⟩, exact submonoid.mul_mem _ (hs hp) (ht hq) } @[to_additive] lemma mul_subset_closure {s t u : set M} (hs : s ⊆ u) (ht : t ⊆ u) : s * t ⊆ submonoid.closure u := mul_subset (subset.trans hs submonoid.subset_closure) (subset.trans ht submonoid.subset_closure) @[to_additive] lemma coe_mul_self_eq (s : submonoid M) : (s : set M) * s = s := begin ext x, refine ⟨_, λ h, ⟨x, 1, h, s.one_mem, mul_one x⟩⟩, rintros ⟨a, b, ha, hb, rfl⟩, exact s.mul_mem ha hb end @[to_additive] lemma closure_mul_le (S T : set M) : closure (S * T) ≤ closure S ⊔ closure T := Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem (set_like.le_def.mp le_sup_left $ subset_closure hs) (set_like.le_def.mp le_sup_right $ subset_closure ht) @[to_additive] lemma sup_eq_closure (H K : submonoid M) : H ⊔ K = closure (H * K) := le_antisymm (sup_le (λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩) (λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩)) (by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le) end submonoid namespace group lemma card_pow_eq_card_pow_card_univ_aux {f : ℕ → ℕ} (h1 : monotone f) {B : ℕ} (h2 : ∀ n, f n ≤ B) (h3 : ∀ n, f n = f (n + 1) → f (n + 1) = f (n + 2)) : ∀ k, B ≤ k → f k = f B := begin have key : ∃ n : ℕ, n ≤ B ∧ f n = f (n + 1), { contrapose! h2, suffices : ∀ n : ℕ, n ≤ B + 1 → n ≤ f n, { exact ⟨B + 1, this (B + 1) (le_refl (B + 1))⟩ }, exact λ n, nat.rec (λ h, nat.zero_le (f 0)) (λ n ih h, lt_of_le_of_lt (ih (n.le_succ.trans h)) (lt_of_le_of_ne (h1 n.le_succ) (h2 n (nat.succ_le_succ_iff.mp h)))) n }, { obtain ⟨n, hn1, hn2⟩ := key, replace key : ∀ k : ℕ, f (n + k) = f (n + k + 1) ∧ f (n + k) = f n := λ k, nat.rec ⟨hn2, rfl⟩ (λ k ih, ⟨h3 _ ih.1, ih.1.symm.trans ih.2⟩) k, replace key : ∀ k : ℕ, n ≤ k → f k = f n := λ k hk, (congr_arg f (nat.add_sub_cancel' hk)).symm.trans (key (k - n)).2, exact λ k hk, (key k (hn1.trans hk)).trans (key B hn1).symm }, end variables {G : Type*} [group G] [fintype G] (S : set G) lemma card_pow_eq_card_pow_card_univ [∀ (k : ℕ), decidable_pred (∈ (S ^ k))] : ∀ k, fintype.card G ≤ k → fintype.card ↥(S ^ k) = fintype.card ↥(S ^ (fintype.card G)) := begin have hG : 0 < fintype.card G := fintype.card_pos_iff.mpr ⟨1⟩, by_cases hS : S = ∅, { intros k hk, congr' 2, rw [hS, empty_pow _ (ne_of_gt (lt_of_lt_of_le hG hk)), empty_pow _ (ne_of_gt hG)] }, obtain ⟨a, ha⟩ := set.ne_empty_iff_nonempty.mp hS, classical, have key : ∀ a (s t : set G), (∀ b : G, b ∈ s → a * b ∈ t) → fintype.card s ≤ fintype.card t, { refine λ a s t h, fintype.card_le_of_injective (λ ⟨b, hb⟩, ⟨a * b, h b hb⟩) _, rintros ⟨b, hb⟩ ⟨c, hc⟩ hbc, exact subtype.ext (mul_left_cancel (subtype.ext_iff.mp hbc)) }, have mono : monotone (λ n, fintype.card ↥(S ^ n) : ℕ → ℕ) := monotone_of_monotone_nat (λ n, key a _ _ (λ b hb, set.mul_mem_mul ha hb)), convert card_pow_eq_card_pow_card_univ_aux mono (λ n, set_fintype_card_le_univ (S ^ n)) (λ n h, le_antisymm (mono (n + 1).le_succ) (key a⁻¹ _ _ _)), { simp only [finset.filter_congr_decidable, fintype.card_of_finset] }, replace h : {a} * S ^ n = S ^ (n + 1), { refine set.eq_of_subset_of_card_le _ (le_trans (ge_of_eq h) _), { exact mul_subset_mul (set.singleton_subset_iff.mpr ha) set.subset.rfl }, { convert key a (S ^ n) ({a} * S ^ n) (λ b hb, set.mul_mem_mul (set.mem_singleton a) hb) } }, rw [pow_succ', ←h, mul_assoc, ←pow_succ', h], rintros _ ⟨b, c, hb, hc, rfl⟩, rwa [set.mem_singleton_iff.mp hb, inv_mul_cancel_left], end end group
1bccfd3295061a578b661a20200d3a517599052b
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/hints/thursday/afternoon/category_theory/exercise4/hint4.lean
9fd7fe7ef1c8f09190dbd33dc67550addb99808c
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
1,662
lean
import algebra.category.CommRing import category_theory.yoneda noncomputable theory open category_theory open opposite open polynomial /-! It would be nice to use `polynomial.aeval`, which produces an algebra homomorphism, and then convert that use `.to_ring_hom`. However we get a mysterious error message: -/ def CommRing_forget_representable : Σ (R : CommRing), (forget CommRing) ≅ coyoneda.obj (op R) := ⟨CommRing.of (polynomial ℤ), { hom := { app := λ R r, (polynomial.aeval ℤ R r).to_ring_hom, }, inv := { app := λ R f, by { dsimp at f, exact f X, }, }, }⟩ /-! If you turn on `set_option pp.all true` above that definition, you'll get a more detailed message: ``` synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized @polynomial.algebra'.{0 0} int int.comm_semiring int (@comm_semiring.to_semiring.{0} int int.comm_semiring) (@algebra_int.{0} int int.ring) inferred @polynomial.algebra'.{0 0} int int.comm_semiring int (@comm_semiring.to_semiring.{0} int int.comm_semiring) (@algebra.id.{0} int int.comm_semiring) ``` The difference here is that Lean has found two different ways to consider `ℤ` as an `ℤ`-algebra, via `(@algebra_int.{0} int int.ring)` and via `(@algebra.id.{0} int int.comm_semiring)`. The elaborator is not clever enough to see these are the same, even though there is actually a `subsingleton (algebra ℤ R)` instance available. At present, the work-around I know of is to use `polynomial.eval₂_ring_hom (algebra_map ℤ R) r` instead of `(polynomial.aeval ℤ R r).to_ring_hom`. If you find something better, let me know! -/
d400fba3e2957a4a4eb7f21730558cf9fddfa38f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/sum/default.lean
8e1ff90018e1cc15af6b42839e8ecb0e74465ea7
[]
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
253
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.sum.basic namespace Mathlib
2aef9f1a1fd85aff92fef67890e4892d7a439722
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Elab/Structure.lean
6cf47c33aaa6e757caa07f155eec3329da966d5b
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
27,852
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.Parser.Command import Lean.Meta.Closure import Lean.Meta.SizeOf import Lean.Elab.Command import Lean.Elab.DeclModifiers import Lean.Elab.DeclUtil import Lean.Elab.Inductive import Lean.Elab.DeclarationRange namespace Lean.Elab.Command open Meta /- Recall that the `structure command syntax is ``` leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) ``` -/ structure StructCtorView where ref : Syntax modifiers : Modifiers inferMod : Bool -- true if `{}` is used in the constructor declaration name : Name declName : Name structure StructFieldView where ref : Syntax modifiers : Modifiers binderInfo : BinderInfo inferMod : Bool declName : Name name : Name binders : Syntax type? : Option Syntax value? : Option Syntax structure StructView where ref : Syntax modifiers : Modifiers scopeLevelNames : List Name -- All `universe` declarations in the current scope allUserLevelNames : List Name -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command isClass : Bool declName : Name scopeVars : Array Expr -- All `variable` declaration in the current scope params : Array Expr -- Explicit parameters provided in the `structure` command parents : Array Syntax type : Syntax ctor : StructCtorView fields : Array StructFieldView inductive StructFieldKind where | newField | fromParent | subobject deriving Inhabited structure StructFieldInfo where name : Name declName : Name -- Remark: this field value doesn't matter for fromParent fields. fvar : Expr kind : StructFieldKind inferMod : Bool := false value? : Option Expr := none deriving Inhabited def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.fromParent => true | _ => false def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.subobject => true | _ => false /- Auxiliary declaration for `mkProjections` -/ structure ProjectionInfo where declName : Name inferMod : Bool structure ElabStructResult where decl : Declaration projInfos : List ProjectionInfo projInstances : List Name -- projections (to parent classes) that must be marked as instances. mctx : MetavarContext lctx : LocalContext localInsts : LocalInstances defaultAuxDecls : Array (Name × Expr × Expr) private def defaultCtorName := `mk /- The structure constructor syntax is ``` leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") ``` -/ private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do let useDefault := do let declName := structDeclName ++ defaultCtorName addAuxDeclarationRanges declName structStx[2] structStx[2] pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName := declName } if structStx[5].isNone then useDefault else let optCtor := structStx[5][1] if optCtor.isNone then useDefault else let ctor := optCtor[0] withRef ctor do let ctorModifiers ← elabModifiers ctor[0] checkValidCtorModifier ctorModifiers if ctorModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' structure" if ctorModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' structure" let inferMod := !ctor[2].isNone let name := ctor[1].getId let declName := structDeclName ++ name let declName ← applyVisibility ctorModifiers.visibility declName addDocString' declName ctorModifiers.docString? addAuxDeclarationRanges declName ctor[1] ctor[1] pure { ref := ctor, name := name, modifiers := ctorModifiers, inferMod := inferMod, declName := declName } def checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do if modifiers.isNoncomputable then throwError "invalid use of 'noncomputable' in field declaration" if modifiers.isPartial then throwError "invalid use of 'partial' in field declaration" if modifiers.isUnsafe then throwError "invalid use of 'unsafe' in field declaration" if modifiers.attrs.size != 0 then throwError "invalid use of attributes in field declaration" if modifiers.isPrivate then throwError "private fields are not supported yet" /- ``` def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional Term.binderDefault >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional Term.binderDefault def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) ``` -/ private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) := let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do let mut fieldBinder := fieldBinder if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then fieldBinder := Syntax.node ``Parser.Command.structExplicitBinder #[ fieldBinder[0], mkAtomFrom fieldBinder "(", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ] let k := fieldBinder.getKind let binfo ← if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit else throwError "unexpected kind of structure field" let fieldModifiers ← elabModifiers fieldBinder[0] checkValidFieldModifier fieldModifiers if fieldModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' field in a 'private' structure" if fieldModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' field in a 'private' structure" let inferMod := !fieldBinder[3].isNone let (binders, type?) := if binfo == BinderInfo.default then expandOptDeclSig fieldBinder[4] else let (binders, type) := expandDeclSig fieldBinder[4] (binders, some type) let value? := if binfo != BinderInfo.default then none else let optBinderDefault := fieldBinder[5] if optBinderDefault.isNone then none else -- binderDefault := leading_parser " := " >> termParser some optBinderDefault[0][1] let idents := fieldBinder[2].getArgs idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do let name := ident.getId if isInternalSubobjectFieldName name then throwError "invalid field name '{name}', identifiers starting with '_' are reserved to the system" let declName := structDeclName ++ name let declName ← applyVisibility fieldModifiers.visibility declName addDocString' declName fieldModifiers.docString? return views.push { ref := ident, modifiers := fieldModifiers, binderInfo := binfo, inferMod := inferMod, declName := declName, name := name, binders := binders, type? := type?, value? := value? } private def validStructType (type : Expr) : Bool := match type with | Expr.sort .. => true | _ => false private def checkParentIsStructure (parent : Expr) : TermElabM Name := match parent.getAppFn with | Expr.const c _ _ => do unless isStructure (← getEnv) c do throwError "'{c}' is not a structure" pure c | _ => throwError "expected structure" private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo := infos.find? fun info => info.name == fieldName private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool := (findFieldInfo? infos fieldName).isSome private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := let rec loop (i : Nat) (infos : Array StructFieldInfo) := do if h : i < subfieldNames.size then let subfieldName := subfieldNames.get ⟨i, h⟩ if containsFieldName infos subfieldName then throwError "field '{subfieldName}' from '{parentStructName}' has already been declared" let val ← mkProjection parentFVar subfieldName let type ← inferType val withLetDecl subfieldName type val fun subfieldFVar => /- The following `declName` is only used for creating the `_default` auxiliary declaration name when its default value is overwritten in the structure. -/ let declName := structDeclName ++ subfieldName let infos := infos.push { name := subfieldName, declName := declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent } loop (i+1) infos else k infos loop 0 infos private partial def withParents (view : StructView) (i : Nat) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do if h : i < view.parents.size then let parentStx := view.parents.get ⟨i, h⟩ withRef parentStx do let parent ← Term.elabType parentStx let parentName ← checkParentIsStructure parent let toParentName := Name.mkSimple $ "to" ++ parentName.eraseMacroScopes.getString! -- erase macro scopes? if containsFieldName infos toParentName then throwErrorAt parentStx "field '{toParentName}' has already been declared" let env ← getEnv let binfo := if view.isClass && isClass env parentName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl toParentName binfo parent fun parentFVar => let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject } let subfieldNames := getStructureFieldsFlattened env parentName processSubfields view.declName parentFVar parentName subfieldNames infos fun infos => withParents view (i+1) infos k else k infos private def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr × Option Expr) := do Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do match view.type? with | none => match view.value? with | none => return (none, none) | some valStx => Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let value ← Term.elabTerm valStx none let value ← mkLambdaFVars params value return (none, value) | some typeStx => let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params match view.value? with | none => let type ← mkForallFVars params type return (type, none) | some valStx => let value ← Term.elabTermEnsuringType valStx type Term.synthesizeSyntheticMVarsNoPostponing let type ← mkForallFVars params type let value ← mkLambdaFVars params value return (type, value) private partial def withFields (views : Array StructFieldView) (i : Nat) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do if h : i < views.size then let view := views.get ⟨i, h⟩ withRef view.ref $ match findFieldInfo? infos view.name with | none => do let (type?, value?) ← elabFieldTypeValue view match type?, value? with | none, none => throwError "invalid field, type expected" | some type, _ => withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?, kind := StructFieldKind.newField, inferMod := view.inferMod } withFields views (i+1) infos k | none, some value => let type ← inferType value withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value, kind := StructFieldKind.newField, inferMod := view.inferMod } withFields views (i+1) infos k | some info => match info.kind with | StructFieldKind.newField => throwError "field '{view.name}' has already been declared" | StructFieldKind.fromParent => match view.value? with | none => throwError "field '{view.name}' has been declared in parent structure" | some valStx => do if let some type := view.type? then throwErrorAt type "omit field '{view.name}' type to set default value" else let mut valStx := valStx if view.binders.getArgs.size > 0 then valStx ← `(fun $(view.binders.getArgs)* => $valStx:term) let fvarType ← inferType info.fvar let value ← Term.elabTermEnsuringType valStx fvarType let infos := infos.push { info with value? := value } withFields views (i+1) infos k | StructFieldKind.subobject => unreachable! else k infos private def getResultUniverse (type : Expr) : TermElabM Level := do let type ← whnf type match type with | Expr.sort u _ => pure u | _ => throwError "unexpected structure resulting type" private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do params.forM fun p => do let type ← inferType p Term.collectUsedFVars type fieldInfos.forM fun info => do let fvarType ← inferType info.fvar Term.collectUsedFVars fvarType match info.value? with | none => pure () | some value => Term.collectUsedFVars value private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed params fieldInfos).run {} Term.removeUnused scopeVars used private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos withLCtx lctx localInsts $ k vars private def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do let type ← inferType fvar discard <| Term.levelMVarToParam' type private def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit := fvars.forM levelMVarToParamFVar private def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT Nat TermElabM (Array StructFieldInfo) := do levelMVarToParamFVars scopeVars levelMVarToParamFVars params fieldInfos.mapM fun info => do levelMVarToParamFVar info.fvar match info.value? with | none => pure info | some value => let value ← Term.levelMVarToParam' value pure { info with value? := value } private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) := (levelMVarToParamAux scopeVars params fieldInfos).run' 1 private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do let type ← inferType info.fvar let u ← getLevel type let u ← instantiateLevelMVars u accLevelAtCtor u r rOffset us private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do let r ← getResultUniverse type let rOffset : Nat := r.getOffset let r : Level := r.getLevelOffset match r with | Level.mvar mvarId _ => let us ← collectUniversesFromFields r rOffset fieldInfos let rNew := mkResultUniverse us rOffset assignLevelMVar mvarId rNew instantiateMVars type | _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly" private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do let type ← inferType fvar let type ← instantiateMVars type pure $ collectLevelParams s type private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State := fvars.foldlM collectLevelParamsInFVar s private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Name) := do let s := collectLevelParams {} structType let s ← collectLevelParamsInFVars scopeVars s let s ← collectLevelParamsInFVars params s let s ← fieldInfos.foldlM (fun (s : CollectLevelParams.State) info => collectLevelParamsInFVar s info.fvar) s pure s.params private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr | 0, type => pure type | i+1, type => do let info := fieldInfos[i] let decl ← Term.getFVarLocalDecl! info.fvar let type ← instantiateMVars type let type := type.abstract #[info.fvar] match info.kind with | StructFieldKind.fromParent => let val := decl.value addCtorFields fieldInfos i (type.instantiate1 val) | StructFieldKind.subobject => let n := mkInternalSubobjectFieldName $ decl.userName addCtorFields fieldInfos i (mkForall n decl.binderInfo decl.type type) | StructFieldKind.newField => addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type) private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor := withRef view.ref do let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params let type ← addCtorFields fieldInfos fieldInfos.size type let type ← mkForallFVars params type let type ← instantiateMVars type let type := type.inferImplicit params.size !view.ctor.inferMod pure { name := view.ctor.declName, type := type } @[extern "lean_mk_projections"] private constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except KernelException Environment private def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do let env ← getEnv match mkProjections env structName projs isClass with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def mkAuxConstructions (declName : Name) : TermElabM Unit := do let env ← getEnv let hasUnit := env.contains `PUnit let hasEq := env.contains `Eq let hasHEq := env.contains `HEq mkRecOn declName if hasUnit then mkCasesOn declName if hasUnit && hasEq && hasHEq then mkNoConfusion declName private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do let localInsts ← getLocalInstances withLCtx lctx localInsts do defaultAuxDecls.forM fun (declName, type, value) => do let value ← instantiateMVars value if value.hasExprMVar then throwError "invalid default value for field, it contains metavariables{indentExpr value}" /- The identity function is used as "marker". -/ let value ← mkId value discard <| mkAuxDefinition declName type value (zeta := true) setReducibleAttribute declName private def elabStructureView (view : StructView) : TermElabM Unit := do view.fields.forM fun field => do if field.declName == view.ctor.declName then throwErrorAt field.ref "invalid field name '{field.name}', it is equal to structure constructor name" addAuxDeclarationRanges field.declName field.ref field.ref let numExplicitParams := view.params.size let type ← Term.elabType view.type unless validStructType type do throwErrorAt view.type "expected Type" withRef view.ref do withParents view 0 #[] fun fieldInfos => withFields view.fields 0 fieldInfos fun fieldInfos => do Term.synthesizeSyntheticMVarsNoPostponing let u ← getResultUniverse type let inferLevel ← shouldInferResultUniverse u withUsed view.scopeVars view.params fieldInfos $ fun scopeVars => do let numParams := scopeVars.size + numExplicitParams let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos let type ← withRef view.ref do if inferLevel then updateResultingUniverse fieldInfos type else checkResultingUniverse (← getResultUniverse type) pure type trace[Elab.structure] "type: {type}" let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with | Except.error msg => withRef view.ref <| throwError msg | Except.ok levelParams => let params := scopeVars ++ view.params let ctor ← mkCtor view levelParams params fieldInfos let type ← mkForallFVars params type let type ← instantiateMVars type let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType } let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe Term.ensureNoUnassignedMVars decl addDecl decl let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => { declName := info.declName, inferMod := info.inferMod : ProjectionInfo } addProjections view.declName projInfos view.isClass mkAuxConstructions view.declName let instParents ← fieldInfos.filterM fun info => do let decl ← Term.getFVarLocalDecl! info.fvar pure (info.isSubobject && decl.binderInfo.isInstImplicit) let projInstances := instParents.toList.map fun info => info.declName Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default) let lctx ← getLCtx let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do let type ← inferType info.fvar pure (info.declName ++ `_default, type, info.value?.get!) /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary `_default` declarations The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/ let lctx := params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) => lctx.setBinderInfo p.fvarId! BinderInfo.implicit let lctx := fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) => if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating `_default`. else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default addDefaults lctx defaultAuxDecls /- leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields >> optDeriving where def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) def structCtor := leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") -/ def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do checkValidInductiveModifier modifiers let isClass := stx[0].getKind == ``Parser.Command.classTk let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers let declId := stx[1] let params := stx[2].getArgs let exts := stx[3] let parents := if exts.isNone then #[] else exts[0][1].getSepArgs let optType := stx[4] let derivingClassViews ← getOptDerivingClasses stx[6] let type ← if optType.isNone then `(Sort _) else pure optType[0][1] let declName ← runTermElabM none fun scopeVars => do let scopeLevelNames ← Term.getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← Elab.expandDeclId (← getCurrNamespace) scopeLevelNames declId modifiers addDeclarationRanges declName stx Term.withDeclName declName do let ctor ← expandCtor stx modifiers declName let fields ← expandFields stx modifiers declName Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <| Term.elabBinders params fun params => do Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let allUserLevelNames ← Term.getLevelNames elabStructureView { ref := stx modifiers := modifiers scopeLevelNames := scopeLevelNames allUserLevelNames := allUserLevelNames declName := declName isClass := isClass scopeVars := scopeVars params := params parents := parents type := type ctor := ctor fields := fields } unless isClass do mkSizeOfInstances declName return declName derivingClassViews.forM fun view => view.applyHandlers #[declName] builtin_initialize registerTraceClass `Elab.structure end Lean.Elab.Command
924bbf115786383a3e4d846a1275f9a86ef9405b
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/is_norm.lean
22d581a836bf11787696fff73da7e0c151640098
[]
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
5,987
lean
-- TODO: move class is_norm (α : Type*) {β : Type*} (N : β → ℝ) [normed_field α] [add_comm_group β] [vector_space α β] := (norm_eq_zero_iff: ∀ x : β, N x = 0 ↔ x = 0) (norm_smul : ∀ c : α, ∀ x : β, N (c • x) = @has_norm.norm α (normed_field.to_has_norm α) c * N x) (triangle : ∀ x y : β, N (x + y) ≤ N x + N y) -- TODO: move namespace is_norm variables (α : Type*) {β : Type*} (N : β → ℝ) [normed_field α] [add_comm_group β] [vector_space α β] --local notation `∥` x `∥` := N x lemma norm_zero [is_norm α N] : N 0 = 0 := by rw norm_eq_zero_iff α N 0 lemma norm_neg [is_norm α N] (x : β) :N (-x) = N x := begin rw [←one_smul α x, ←neg_smul, @norm_smul α β N, @norm_neg α normed_ring.to_normed_group], rw [@norm_one α (by apply_instance),one_mul,one_smul] end lemma norm_nonneg [is_norm α N] (x : β) : 0 ≤ N x := begin apply (@mul_le_mul_left _ _ _ _ (2 : ℝ) (lt_trans zero_lt_one one_lt_two)).1, convert is_norm.triangle α N x (-x), { rw [add_neg_self, norm_zero α N, mul_zero] }, { rw [two_mul,norm_neg α N] } end /- /-- Equivalent norms with explicit coefficients -/ def equiv_by (b₁ : ℝ) (b₂ : ℝ) (N₁ : β → ℝ) (N₂ : β → ℝ) := ∀ x, N₁ x ≤ b₂ * N₂ x ∧ N₂ x ≤ b₁ * N₁ x /-- Equivalent norms -/ def equiv (N₁ : β → ℝ) (N₂ : β → ℝ) := ∃ b₁ b₂, equiv_by b₁ b₂ N₁ N₂ lemma equiv_by_abs {N₁ : β → ℝ} {N₂ : β → ℝ} [is_norm α N₁] [is_norm α N₂] {b₁ : ℝ} {b₂ : ℝ} (h : equiv_by b₁ b₂ N₁ N₂) : equiv_by (abs b₁) (abs b₂) N₁ N₂ := begin unfold equiv_by at *, intros x, apply and.intro, { apply le_trans (h x).1, apply mul_le_mul _ (le_refl _) (norm_nonneg α N₂ _) (abs_nonneg _), apply le_abs_self }, { apply le_trans (h x).2, apply mul_le_mul _ (le_refl _) (norm_nonneg α N₁ _) (abs_nonneg _), apply le_abs_self } end --set_option pp.all true instance normed_space_is_norm [normed_space α β] : is_norm α (norm : β → ℝ) := { norm_eq_zero_iff := begin intros x, apply iff.intro, intros hx, apply eq_of_dist_eq_zero, rw [normed_group.dist_eq x], simp [hx], end, norm_smul := sorry, triangle := sorry, } -/ end is_norm section norm variables {α : Type*} (N : α → ℝ) [hα : add_comm_group α] [hℝα : vector_space ℝ α] [hN : is_norm ℝ N] def norm_cone : set (α × ℝ) := { x : α × ℝ | N x.1 ≤ x.2 } set_option trace.class_instances true -- TODO: why does ` variables ` not work? lemma cone_norm_cone {α : Type*} (N : α → ℝ) [hα : add_comm_group α] [hℝα : vector_space ℝ α] [hN : is_norm ℝ N] : @cone (α × ℝ) (@prod.add_comm_group α ℝ hα (ring.to_add_comm_group ℝ) ) (@prod.vector_space ℝ α ℝ _ _ (/-ring.to_add_comm_group ℝ-/_) hℝα discrete_field.to_vector_space) (@norm_cone α N) := begin intros x ha c hc, unfold norm_cone at *, simp [is_norm.norm_smul N c x.fst, real.norm_eq_abs, abs_of_nonneg hc], apply mul_le_mul (le_refl _), { simp at ha, assumption }, { apply is_norm.norm_nonneg ℝ N }, { exact hc } end open lattice -- TODO: why does ` variables ` not work? -- def dual_norm {α : Type*} (N : α → ℝ) [hα : add_comm_group α] [hℝα : vector_space ℝ α] [hN : is_norm ℝ N] [real_inner_product_space α] : α → ℝ := lattice.Sup { c : ℝ | ∃ x, c = ⟪ y, x ⟫ ∧ N x ≤ 1 } /-- The dual norm is well defined if the norm induced by the inner product (norm) can be bounded by the primal norm. In finite dimensional real vector spaces all norms are equivalent and the condition is always true. -/ lemma dual_norm_bounded [real_inner_product_space α] (y : α) (b : ℝ) (hb : 0 ≤ b ∧ ∀x, norm x ≤ b * N x): bdd_above { c | ∃ x, c = ⟪ y, x ⟫ ∧ N x ≤ 1 } := begin unfold bdd_above, use norm y * b, intros c hc, apply exists.elim hc, intros x hx, rw hx.1, have h_norm_x : norm x ≤ b, begin apply le_trans (hb.2 x) _, apply mul_le_of_le_one_right hb.1 hx.2, end, apply le_trans (real_inner_product_space.cauchy_schwartz' y x), apply mul_le_mul (le_refl _) h_norm_x (norm_nonneg _) (norm_nonneg _) end --set_option pp.all true instance dual_norm_is_norm {α : Type*} (N : α → ℝ) [hα : real_inner_product_space α] [vector_space ℝ α] [is_norm ℝ N] (b : ℝ) (hb : 0 ≤ b ∧ ∀x, norm x ≤ b * N x): is_norm ℝ (dual_norm N) := { norm_eq_zero_iff := begin intros y, apply iff.intro, { unfold dual_norm, intro h, have h_nonempty : { c | ∃ x, c = ⟪ y, x ⟫ ∧ N x ≤ 1 } ≠ ∅, begin apply @set.ne_empty_of_mem ℝ _ 0, use 0, apply and.intro, apply (real_inner_product_space.inner_zero_right y).symm, rw is_norm.norm_zero ℝ N, linarith end, have hy : ⟪y, (N y)⁻¹ • y⟫ ≤ 0, begin apply (lattice.cSup_le_iff (dual_norm_bounded _ y b hb) h_nonempty).1 (le_of_eq h) ⟪y, (N y)⁻¹ • y⟫, use (N y)⁻¹ • y, apply and.intro rfl, rw @is_norm.norm_smul ℝ α N _, rw real.norm_eq_abs, rw abs_of_nonneg (inv_nonneg.2 (is_norm.norm_nonneg ℝ N y)), by_cases h_cases: N y = 0, { simp [h_cases], linarith }, { rw inv_mul_cancel h_cases }, end, have hy : (N y)⁻¹ * ⟪y, y⟫ ≤ 0, begin rw [←real_inner_product_space.inner_smul_right], exact hy, end show y = 0, begin apply real_inner_product_space.eq_zero_of_inner_self_eq_zero, end }, { sorry } end, norm_smul := sorry, triangle := sorry } lemma inner_product_cone [real_inner_product_space α] : dual_cone (norm_cone norm) = norm_cone (dual_norm norm) := --TODO use dual norm begin apply set.subset.antisymm, { intros x hx, unfold norm_cone, }, {sorry} end end norm .
ef260eca166acffc20184cf548b0c6bc9c689c03
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/order_bigops.lean
45794111029acba160b6daad65795f4915f323a5
[ "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
19,034
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Min and max over finite sets. To support constructive theories, we start with the class decidable_linear_ordered_cancel_comm_monoid, because: (1) We need a decidable linear order to have min and max (2) We need a default element for min and max over the empty set, and max empty = 0 is the right choice for nat. (3) All our number classes are instances. We can define variants of Min and Max if needed. -/ import .group_bigops .ordered_ring variables {A B : Type} section variable [decidable_linear_order A] definition max_comm_semigroup : comm_semigroup A := ⦃ comm_semigroup, mul := max, mul_assoc := max.assoc, mul_comm := max.comm ⦄ definition min_comm_semigroup : comm_semigroup A := ⦃ comm_semigroup, mul := min, mul_assoc := min.assoc, mul_comm := min.comm ⦄ end /- finset versions -/ namespace finset section deceq_A variable [decidable_eq A] section decidable_linear_ordered_cancel_comm_monoid_B variable [decidable_linear_ordered_cancel_comm_monoid B] section max_comm_semigroup local attribute max_comm_semigroup [instance] open Prod_semigroup definition Max (s : finset A) (f : A → B) : B := Prod_semigroup 0 s f notation `Max` binders `∈` s `, ` r:(scoped f, Max s f) := r proposition Max_empty (f : A → B) : (Max x ∈ ∅, f x) = 0 := !Prod_semigroup_empty proposition Max_singleton (f : A → B) (a : A) : (Max x ∈ '{a}, f x) = f a := !Prod_semigroup_singleton proposition Max_insert_insert (f : A → B) {a₁ a₂ : A} {s : finset A} : a₂ ∉ s → a₁ ∉ insert a₂ s → (Max x ∈ insert a₁ (insert a₂ s), f x) = max (f a₁) (Max x ∈ insert a₂ s, f x) := !Prod_semigroup_insert_insert proposition Max_insert (f : A → B) {a : A} {s : finset A} (anins : a ∉ s) (sne : s ≠ ∅) : (Max x ∈ insert a s, f x) = max (f a) (Max x ∈ s, f x) := !Prod_semigroup_insert anins sne end max_comm_semigroup proposition Max_pair (f : A → B) (a₁ a₂ : A) : (Max x ∈ '{a₁, a₂}, f x) = max (f a₁) (f a₂) := decidable.by_cases (suppose a₁ = a₂, by rewrite [this, pair_eq_singleton, max_self] ) (suppose a₁ ≠ a₂, have a₁ ∉ '{a₂}, by rewrite [mem_singleton_iff]; apply this, using this, by rewrite [Max_insert f this !singleton_ne_empty]) proposition le_Max (f : A → B) {a : A} {s : finset A} (H : a ∈ s) : f a ≤ Max x ∈ s, f x := begin induction s with a' s' a'nins' ih, {exact false.elim (not_mem_empty a H)}, cases (decidable.em (s' = ∅)) with s'empty s'nempty, {rewrite [s'empty at *, Max_singleton, eq_of_mem_singleton H]}, rewrite [Max_insert f a'nins' s'nempty], cases (eq_or_mem_of_mem_insert H) with aeqa' ains', {rewrite aeqa', apply le_max_left}, apply le.trans (ih ains') !le_max_right end proposition Max_le (f : A → B) {s : finset A} {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → f a ≤ b) : (Max x ∈ s, f x) ≤ b := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'nempty, {rewrite [s'empty, Max_singleton], exact H a' !mem_insert}, rewrite [Max_insert f a'nins' s'nempty], apply max_le (H a' !mem_insert), apply ih s'nempty, intro a H', exact H a (mem_insert_of_mem a' H') end proposition Max_add_right (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) : (Max x ∈ s, f x + b) = (Max x ∈ s, f x) + b := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'ne, {rewrite [s'empty, Max_singleton]}, rewrite [*Max_insert _ a'nins' s'ne, ih s'ne, max_add_add_right] end proposition Max_add_left (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) : (Max x ∈ s, b + f x) = b + (Max x ∈ s, f x) := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'ne, {rewrite [s'empty, Max_singleton]}, rewrite [*Max_insert _ a'nins' s'ne, ih s'ne, max_add_add_left] end section min_comm_semigroup local attribute min_comm_semigroup [instance] open Prod_semigroup definition Min (s : finset A) (f : A → B) : B := Prod_semigroup 0 s f notation `Min` binders `∈` s `, ` r:(scoped f, Min s f) := r proposition Min_empty (f : A → B) : (Min x ∈ ∅, f x) = 0 := !Prod_semigroup_empty proposition Min_singleton (f : A → B) (a : A) : (Min x ∈ '{a}, f x) = f a := !Prod_semigroup_singleton proposition Min_insert_insert (f : A → B) {a₁ a₂ : A} {s : finset A} : a₂ ∉ s → a₁ ∉ insert a₂ s → (Min x ∈ insert a₁ (insert a₂ s), f x) = min (f a₁) (Min x ∈ insert a₂ s, f x) := !Prod_semigroup_insert_insert proposition Min_insert (f : A → B) {a : A} {s : finset A} (anins : a ∉ s) (sne : s ≠ ∅) : (Min x ∈ insert a s, f x) = min (f a) (Min x ∈ s, f x) := !Prod_semigroup_insert anins sne end min_comm_semigroup proposition Min_pair (f : A → B) (a₁ a₂ : A) : (Min x ∈ '{a₁, a₂}, f x) = min (f a₁) (f a₂) := decidable.by_cases (suppose a₁ = a₂, by rewrite [this, pair_eq_singleton, min_self] ) (suppose a₁ ≠ a₂, have a₁ ∉ '{a₂}, by rewrite [mem_singleton_iff]; apply this, using this, by rewrite [Min_insert f this !singleton_ne_empty]) proposition Min_le (f : A → B) {a : A} {s : finset A} (H : a ∈ s) : (Min x ∈ s, f x) ≤ f a := begin induction s with a' s' a'nins' ih, {exact false.elim (not_mem_empty a H)}, cases (decidable.em (s' = ∅)) with s'empty s'nempty, {rewrite [s'empty at *, Min_singleton, eq_of_mem_singleton H]}, rewrite [Min_insert f a'nins' s'nempty], cases (eq_or_mem_of_mem_insert H) with aeqa' ains', {rewrite aeqa', apply min_le_left}, apply le.trans !min_le_right (ih ains') end proposition le_Min (f : A → B) {s : finset A} {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → b ≤ f a) : b ≤ Min x ∈ s, f x := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'nempty, {rewrite [s'empty, Min_singleton], exact H a' !mem_insert}, rewrite [Min_insert f a'nins' s'nempty], apply le_min (H a' !mem_insert), apply ih s'nempty, intro a H', exact H a (mem_insert_of_mem a' H') end proposition Min_add_right (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) : (Min x ∈ s, f x + b) = (Min x ∈ s, f x) + b := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'ne, {rewrite [s'empty, Min_singleton]}, rewrite [*Min_insert _ a'nins' s'ne, ih s'ne, min_add_add_right] end proposition Min_add_left (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) : (Min x ∈ s, b + f x) = b + (Min x ∈ s, f x) := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'ne, {rewrite [s'empty, Min_singleton]}, rewrite [*Min_insert _ a'nins' s'ne, ih s'ne, min_add_add_left] end end decidable_linear_ordered_cancel_comm_monoid_B section decidable_linear_ordered_comm_group_B variable [decidable_linear_ordered_comm_group B] proposition Max_neg (f : A → B) (s : finset A) : (Max x ∈ s, - f x) = - Min x ∈ s, f x := begin cases (decidable.em (s = ∅)) with se sne, {rewrite [se, Max_empty, Min_empty, neg_zero]}, apply eq_of_le_of_ge, {apply !Max_le sne, intro a ains, apply neg_le_neg, apply !Min_le ains}, apply neg_le_of_neg_le, apply !le_Min sne, intro a ains, apply neg_le_of_neg_le, apply !le_Max ains end proposition Min_neg (f : A → B) (s : finset A) : (Min x ∈ s, - f x) = - Max x ∈ s, f x := begin cases (decidable.em (s = ∅)) with se sne, {rewrite [se, Max_empty, Min_empty, neg_zero]}, apply eq_of_le_of_ge, {apply le_neg_of_le_neg, apply !Max_le sne, intro a ains, apply le_neg_of_le_neg, apply !Min_le ains}, apply !le_Min sne, intro a ains, apply neg_le_neg, apply !le_Max ains end proposition Max_eq_neg_Min_neg (f : A → B) (s : finset A) : (Max x ∈ s, f x) = - Min x ∈ s, - f x := by rewrite [Min_neg, neg_neg] proposition Min_eq_neg_Max_neg (f : A → B) (s : finset A) : (Min x ∈ s, f x) = - Max x ∈ s, - f x := by rewrite [Max_neg, neg_neg] end decidable_linear_ordered_comm_group_B end deceq_A /- Min and Max *of* a finset -/ section decidable_linear_ordered_semiring_A variable [decidable_linear_ordered_semiring A] definition Max₀ (s : finset A) : A := Max x ∈ s, x definition Min₀ (s : finset A) : A := Min x ∈ s, x proposition Max₀_empty : Max₀ ∅ = (0 : A) := !Max_empty proposition Max₀_singleton (a : A) : Max₀ '{a} = a := !Max_singleton proposition Max₀_insert_insert {a₁ a₂ : A} {s : finset A} (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) : Max₀ (insert a₁ (insert a₂ s)) = max a₁ (Max₀ (insert a₂ s)) := !Max_insert_insert H₁ H₂ proposition Max₀_insert {s : finset A} {a : A} (anins : a ∉ s) (sne : s ≠ ∅) : Max₀ (insert a s) = max a (Max₀ s) := !Max_insert anins sne proposition Max₀_pair (a₁ a₂ : A) : Max₀ '{a₁, a₂} = max a₁ a₂ := !Max_pair proposition le_Max₀ {a : A} {s : finset A} (H : a ∈ s) : a ≤ Max₀ s := !le_Max H proposition Max₀_le {s : finset A} {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → x ≤ a) : Max₀ s ≤ a := !Max_le sne H proposition Min₀_empty : Min₀ ∅ = (0 : A) := !Min_empty proposition Min₀_singleton (a : A) : Min₀ '{a} = a := !Min_singleton proposition Min₀_insert_insert {a₁ a₂ : A} {s : finset A} (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) : Min₀ (insert a₁ (insert a₂ s)) = min a₁ (Min₀ (insert a₂ s)) := !Min_insert_insert H₁ H₂ proposition Min₀_insert {s : finset A} {a : A} (anins : a ∉ s) (sne : s ≠ ∅) : Min₀ (insert a s) = min a (Min₀ s) := !Min_insert anins sne proposition Min₀_pair (a₁ a₂ : A) : Min₀ '{a₁, a₂} = min a₁ a₂ := !Min_pair proposition Min₀_le {a : A} {s : finset A} (H : a ∈ s) : Min₀ s ≤ a := !Min_le H proposition le_Min₀ {s : finset A} {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → a ≤ x) : a ≤ Min₀ s := !le_Min sne H end decidable_linear_ordered_semiring_A end finset /- finite set versions -/ namespace set local attribute classical.prop_decidable [instance] section decidable_linear_ordered_cancel_comm_monoid_B variable [decidable_linear_ordered_cancel_comm_monoid B] noncomputable definition Max (s : set A) (f : A → B) : B := finset.Max (to_finset s) f notation `Max` binders `∈` s `, ` r:(scoped f, Max s f) := r noncomputable definition Min (s : set A) (f : A → B) : B := finset.Min (to_finset s) f notation `Min` binders `∈` s `, ` r:(scoped f, Min s f) := r proposition Max_empty (f : A → B) : (Max x ∈ ∅, f x) = 0 := by rewrite [↑set.Max, to_finset_empty, finset.Max_empty] proposition Max_singleton (f : A → B) (a : A) : (Max x ∈ '{a}, f x) = f a := by rewrite [↑set.Max, to_finset_insert, to_finset_empty, finset.Max_singleton] proposition Max_insert_insert (f : A → B) {a₁ a₂ : A} {s : set A} [h : finite s] : a₂ ∉ s → a₁ ∉ insert a₂ s → (Max x ∈ insert a₁ (insert a₂ s), f x) = max (f a₁) (Max x ∈ insert a₂ s, f x) := begin rewrite [↑set.Max, -+mem_to_finset_eq, +to_finset_insert], apply finset.Max_insert_insert end proposition Max_insert (f : A → B) {a : A} {s : set A} [h : finite s] (anins : a ∉ s) (sne : s ≠ ∅) : (Max x ∈ insert a s, f x) = max (f a) (Max x ∈ s, f x) := begin revert anins sne, rewrite [↑set.Max, -+mem_to_finset_eq, +to_finset_insert], intro h1 h2, apply finset.Max_insert f h1 (λ h', h2 (eq_empty_of_to_finset_eq_empty h')), end proposition Max_pair (f : A → B) (a₁ a₂ : A) : (Max x ∈ '{a₁, a₂}, f x) = max (f a₁) (f a₂) := by rewrite [↑set.Max, +to_finset_insert, +to_finset_empty, finset.Max_pair] proposition le_Max (f : A → B) {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : f a ≤ Max x ∈ s, f x := by rewrite [-+mem_to_finset_eq at H, ↑set.Max]; exact finset.le_Max f H proposition Max_le (f : A → B) {s : set A} [fins : finite s] {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → f a ≤ b) : (Max x ∈ s, f x) ≤ b := begin rewrite [↑set.Max], apply finset.Max_le f (λ H', sne (eq_empty_of_to_finset_eq_empty H')), intro a H', apply H a, rewrite mem_to_finset_eq at H', exact H' end proposition Max_add_right (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) : (Max x ∈ s, f x + b) = (Max x ∈ s, f x) + b := begin rewrite [↑set.Max], apply finset.Max_add_right f b (λ h, sne (eq_empty_of_to_finset_eq_empty h)) end proposition Max_add_left (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) : (Max x ∈ s, b + f x) = b + (Max x ∈ s, f x) := begin rewrite [↑set.Max], apply finset.Max_add_left f b (λ h, sne (eq_empty_of_to_finset_eq_empty h)) end proposition Min_empty (f : A → B) : (Min x ∈ ∅, f x) = 0 := by rewrite [↑set.Min, to_finset_empty, finset.Min_empty] proposition Min_singleton (f : A → B) (a : A) : (Min x ∈ '{a}, f x) = f a := by rewrite [↑set.Min, to_finset_insert, to_finset_empty, finset.Min_singleton] proposition Min_insert_insert (f : A → B) {a₁ a₂ : A} {s : set A} [h : finite s] : a₂ ∉ s → a₁ ∉ insert a₂ s → (Min x ∈ insert a₁ (insert a₂ s), f x) = min (f a₁) (Min x ∈ insert a₂ s, f x) := begin rewrite [↑set.Min, -+mem_to_finset_eq, +to_finset_insert], apply finset.Min_insert_insert end proposition Min_insert (f : A → B) {a : A} {s : set A} [h : finite s] (anins : a ∉ s) (sne : s ≠ ∅) : (Min x ∈ insert a s, f x) = min (f a) (Min x ∈ s, f x) := begin revert anins sne, rewrite [↑set.Min, -+mem_to_finset_eq, +to_finset_insert], intro h1 h2, apply finset.Min_insert f h1 (λ h', h2 (eq_empty_of_to_finset_eq_empty h')), end proposition Min_pair (f : A → B) (a₁ a₂ : A) : (Min x ∈ '{a₁, a₂}, f x) = min (f a₁) (f a₂) := by rewrite [↑set.Min, +to_finset_insert, +to_finset_empty, finset.Min_pair] proposition Min_le (f : A → B) {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : (Min x ∈ s, f x) ≤ f a := by rewrite [-+mem_to_finset_eq at H, ↑set.Min]; exact finset.Min_le f H proposition le_Min (f : A → B) {s : set A} [fins : finite s] {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → b ≤ f a) : b ≤ Min x ∈ s, f x := begin rewrite [↑set.Min], apply finset.le_Min f (λ H', sne (eq_empty_of_to_finset_eq_empty H')), intro a H', apply H a, rewrite mem_to_finset_eq at H', exact H' end proposition Min_add_right (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) : (Min x ∈ s, f x + b) = (Min x ∈ s, f x) + b := begin rewrite [↑set.Min], apply finset.Min_add_right f b (λ h, sne (eq_empty_of_to_finset_eq_empty h)) end proposition Min_add_left (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) : (Min x ∈ s, b + f x) = b + (Min x ∈ s, f x) := begin rewrite [↑set.Min], apply finset.Min_add_left f b (λ h, sne (eq_empty_of_to_finset_eq_empty h)) end end decidable_linear_ordered_cancel_comm_monoid_B section decidable_linear_ordered_comm_group_B variable [decidable_linear_ordered_comm_group B] proposition Max_neg (f : A → B) (s : set A) : (Max x ∈ s, - f x) = - Min x ∈ s, f x := by rewrite [↑set.Max, finset.Max_neg] proposition Min_neg (f : A → B) (s : set A) : (Min x ∈ s, - f x) = - Max x ∈ s, f x := by rewrite [↑set.Min, finset.Min_neg] proposition Max_eq_neg_Min_neg (f : A → B) (s : set A) : (Max x ∈ s, f x) = - Min x ∈ s, - f x := by rewrite [↑set.Max, ↑set.Min, finset.Max_eq_neg_Min_neg] proposition Min_eq_neg_Max_neg (f : A → B) (s : set A) : (Min x ∈ s, f x) = - Max x ∈ s, - f x := by rewrite [↑set.Max, ↑set.Min, finset.Min_eq_neg_Max_neg] end decidable_linear_ordered_comm_group_B section decidable_linear_ordered_semiring_A variable [decidable_linear_ordered_semiring A] noncomputable definition Max₀ (s : set A) : A := Max x ∈ s, x noncomputable definition Min₀ (s : set A) : A := Min x ∈ s, x proposition Max₀_empty : Max₀ ∅ = (0 : A) := !Max_empty proposition Max₀_singleton (a : A) : Max₀ '{a} = a := !Max_singleton proposition Max₀_insert_insert {a₁ a₂ : A} {s : set A} [fins : finite s] (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) : Max₀ (insert a₁ (insert a₂ s)) = max a₁ (Max₀ (insert a₂ s)) := !Max_insert_insert H₁ H₂ proposition Max₀_insert {s : set A} [fins : finite s] {a : A} (anins : a ∉ s) (sne : s ≠ ∅) : Max₀ (insert a s) = max a (Max₀ s) := !Max_insert anins sne proposition Max₀_pair (a₁ a₂ : A) : Max₀ '{a₁, a₂} = max a₁ a₂ := !Max_pair proposition le_Max₀ {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : a ≤ Max₀ s := !le_Max H proposition Max₀_le {s : set A} [fins : finite s] {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → x ≤ a) : Max₀ s ≤ a := !Max_le sne H proposition Min₀_empty : Min₀ ∅ = (0 : A) := !Min_empty proposition Min₀_singleton (a : A) : Min₀ '{a} = a := !Min_singleton proposition Min₀_insert_insert {a₁ a₂ : A} {s : set A} [fins : finite s] (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) : Min₀ (insert a₁ (insert a₂ s)) = min a₁ (Min₀ (insert a₂ s)) := !Min_insert_insert H₁ H₂ proposition Min₀_insert {s : set A} [fins : finite s] {a : A} (anins : a ∉ s) (sne : s ≠ ∅) : Min₀ (insert a s) = min a (Min₀ s) := !Min_insert anins sne proposition Min₀_pair (a₁ a₂ : A) : Min₀ '{a₁, a₂} = min a₁ a₂ := !Min_pair proposition Min₀_le {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : Min₀ s ≤ a := !Min_le H proposition le_Min₀ {s : set A} [fins : finite s] {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → a ≤ x) : a ≤ Min₀ s := !le_Min sne H end decidable_linear_ordered_semiring_A end set
917a7ae210bb9a67d97159d9ba258d332bc2176e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/string/default.lean
bdd6c61ab2c31c9101abcbabe104abc5bedee7a6
[]
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
301
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.string.basic import Mathlib.Lean3Lib.init.data.string.ops namespace Mathlib
eb77dacdb6a6c9cdacaa59b49457e1d256357e5a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Tactic/Conv/Delta.lean
433ff2b40ff2d14c550262ebf353592bc8d4cee3
[ "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
567
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.Delta import Lean.Elab.Tactic.Conv.Basic namespace Lean.Elab.Tactic.Conv open Meta @[builtinTactic Lean.Parser.Tactic.Conv.delta] def evalDelta : Tactic := fun stx => withMainContext do let declName ← resolveGlobalConstNoOverloadWithInfo stx[1] let lhsNew ← deltaExpand (← instantiateMVars (← getLhs)) (· == declName) changeLhs lhsNew end Lean.Elab.Tactic.Conv
7fe043fb2155314ba8a91c6349e56d16ca07ab7b
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/Exercises week 5/22_exercise_sheet.lean
5efb051878fe1b9fe8b54a4379b575030b7c5637
[]
no_license
KjellZijlemaker/Logical_Verification_VU
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
4578b93bf1615466996157bb333c84122b201d99
refs/heads/master
1,585,966,086,108
1,549,187,704,000
1,549,187,704,000
155,690,284
0
0
null
null
null
null
UTF-8
Lean
false
false
3,798
lean
/- Exercise 2.2: Functional Programming — Trees -/ /- Question 1: Even and odd -/ /- 1.1. Define an inductive predicate `even` on `ℕ` that is true for even numbers and false for odd numbers. Hint: Your predicate should have two introduction rules, one for the 0 case and one for the `n + 2` case. -/ inductive even : ℕ → Prop | zero : even 0 | even_plus_two (n: ℕ) (h: even n): even(n + 2) /- 1.2. Prove that 0, 2, 4, and 6 are even. -/ lemma iseven0: even 0 := by {apply even.zero} lemma iseven2: even 2 := by {apply even.even_plus_two; apply even.zero} lemma iseven4: even 4 := by {repeat{apply even.even_plus_two}; apply even.zero} lemma iseven6: even 6 := by {repeat{apply even.even_plus_two}; apply even.zero} def odd (n : ℕ) : Prop := ¬ even n /- 1.3. Prove that 1 is odd and register this fact as a `simp` rule. Hint: `cases` is useful to reason about hypotheses of the form `even ...`. -/ lemma isodd: odd 1 := by {intro h; cases h} /- 1.4. Prove that 3, 5, and 7 are odd. -/ lemma isodd3 : odd 3 := by {intro s; cases s, cases s_h} lemma isodd5 : odd 5 := by {intro s; cases s, cases s_h, cases s_h_h} lemma isodd7 : odd 7 := by {intro s; cases s, cases s_h, cases s_h_h, cases s_h_h_h} /- 1.5. Complete the following proof by structural induction. -/ lemma even_two_times : ∀m : ℕ, even (2 * m) | 0 := even.zero | (n + 1) := begin apply even.even_plus_two, apply even_two_times n end /- 1.6. Complete the following proof by rule induction. Hint: You can use the `cases` tactic or `match ... with` to destruct an existential quantifier and extract the witness. -/ lemma even_imp_exists_two_times : ∀n : ℕ, even n → ∃m, n = 2 * m | _ even.zero := ⟨0, by simp⟩ | _ (even.add_two n h) := sorry /- 1.7. Using `even_two_times` and `even_imp_exists_two_times`, prove the following equivalence. -/ lemma even_iff_exists_two_times (n : ℕ) : even n ↔ ∃m, n = 2 * m := sorry /- Question 2: Binary trees -/ namespace my_bin_tree /- Recall the binary trees from the lecture. As usual, we omit the proofs using `sorry`. -/ inductive tree (α : Type) : Type | empty {} : tree | node (a : α) (l : tree) (r : tree) : tree export tree (empty node) def mirror {α : Type} : tree α → tree α | empty := empty | (node a l r) := node a (mirror r) (mirror l) lemma empty_mirror_iff {α : Type} : ∀t : tree α, mirror t = empty ↔ t = empty := sorry lemma mirror_mirror {α : Type} : ∀t : tree α, mirror (mirror t) = t := sorry inductive is_full {α : Type} : tree α → Prop | empty : is_full empty | node (a : α) (l r : tree α) (hl : is_full l) (hr : is_full r) (empty_iff : l = empty ↔ r = empty) : is_full (node a l r) lemma is_full_singleton {α : Type} (a : α) : is_full (node a empty empty) := sorry lemma is_full_mirror {α : Type} : ∀t : tree α, is_full t → is_full (mirror t) := sorry /- 2.1. State and prove the converse of `is_full_mirror`. -/ -- enter your answer here /- 2.2. Define a function that counts the number of constructors (`empty` or `node`) in a tree. -/ def count {α : Type} : tree α → ℕ := sorry end my_bin_tree /- Question 3: λ-terms -/ namespace my_lambda_term /- 3.1. Define an inductive type corresponding to the untyled λ-terms, as given by the following context-free grammar: <lam> ::= 'var' <string> | 'abs' <string> <lam> | 'app' <lam> <lam> -/ -- enter your definition here /- 3.2. Define an inductive predicate `is_βnf` that determines whether a lambda term is in β-normal form (https://en.wikipedia.org/wiki/Beta_normal_form). -/ -- enter your answer here /- 3.3. Register a textual representation of the type `lam`, as we did for Huffman trees in the lecture. -/ -- enter your answer here end my_lambda_term
efe84c8f9d9d1588a3436e5896506d65556d1ff1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/unicode_lit.lean
69438d5c5501e50615a542dc47138968289cfc7d
[ "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
86
lean
#eval "≠∀Π∃⁻ʰℵ⬝" #eval "≠∀Π∃⁻ʰℵ⬝".to_list.map char.to_nat
d6308b1b6eb4774aa56ff78299dc68f6ee665e12
94e33a31faa76775069b071adea97e86e218a8ee
/src/field_theory/normal.lean
527e38883137cd1c730fb7b2ca6558e8e1097786
[ "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,830
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Thomas Browning, Patrick Lutz -/ import field_theory.adjoin import field_theory.tower import group_theory.solvable import ring_theory.power_basis /-! # Normal field extensions In this file we define normal field extensions and prove that for a finite extension, being normal is the same as being a splitting field (`normal.of_is_splitting_field` and `normal.exists_is_splitting_field`). ## Main Definitions - `normal F K` where `K` is a field extension of `F`. -/ noncomputable theory open_locale big_operators open_locale classical polynomial open polynomial is_scalar_tower variables (F K : Type*) [field F] [field K] [algebra F K] --TODO(Commelin): refactor normal to extend `is_algebraic`?? /-- Typeclass for normal field extension: `K` is a normal extension of `F` iff the minimal polynomial of every element `x` in `K` splits in `K`, i.e. every conjugate of `x` is in `K`. -/ class normal : Prop := (is_integral' (x : K) : is_integral F x) (splits' (x : K) : splits (algebra_map F K) (minpoly F x)) variables {F K} theorem normal.is_integral (h : normal F K) (x : K) : is_integral F x := normal.is_integral' x theorem normal.splits (h : normal F K) (x : K) : splits (algebra_map F K) (minpoly F x) := normal.splits' x theorem normal_iff : normal F K ↔ ∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := ⟨λ h x, ⟨h.is_integral x, h.splits x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩ theorem normal.out : normal F K → ∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := normal_iff.1 variables (F K) instance normal_self : normal F F := ⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact splits_X_sub_C _ }⟩ variables {K} variables (K) theorem normal.exists_is_splitting_field [h : normal F K] [finite_dimensional F K] : ∃ p : F[X], is_splitting_field F K p := begin let s := basis.of_vector_space F K, refine ⟨∏ x, minpoly F (s x), splits_prod _ $ λ x hx, h.splits (s x), subalgebra.to_submodule_injective _⟩, rw [algebra.top_to_submodule, eq_top_iff, ← s.span_eq, submodule.span_le, set.range_subset_iff], refine λ x, algebra.subset_adjoin (multiset.mem_to_finset.mpr $ (mem_roots $ mt (map_eq_zero $ algebra_map F K).1 $ finset.prod_ne_zero_iff.2 $ λ x hx, _).2 _), { exact minpoly.ne_zero (h.is_integral (s x)) }, rw [is_root.def, eval_map, ← aeval_def, alg_hom.map_prod], exact finset.prod_eq_zero (finset.mem_univ _) (minpoly.aeval _ _) end section normal_tower variables (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma normal.tower_top_of_normal [h : normal F E] : normal K E := normal_iff.2 $ λ x, begin cases h.out x with hx hhx, rw algebra_map_eq F K E at hhx, exact ⟨is_integral_of_is_scalar_tower x hx, polynomial.splits_of_splits_of_dvd (algebra_map K E) (polynomial.map_ne_zero (minpoly.ne_zero hx)) ((polynomial.splits_map_iff (algebra_map F K) (algebra_map K E)).mpr hhx) (minpoly.dvd_map_of_is_scalar_tower F K x)⟩, end lemma alg_hom.normal_bijective [h : normal F E] (ϕ : E →ₐ[F] K) : function.bijective ϕ := ⟨ϕ.to_ring_hom.injective, λ x, by { letI : algebra E K := ϕ.to_ring_hom.to_algebra, obtain ⟨h1, h2⟩ := h.out (algebra_map K E x), cases minpoly.mem_range_of_degree_eq_one E x (or.resolve_left h2 (minpoly.ne_zero h1) (minpoly.irreducible (is_integral_of_is_scalar_tower x ((is_integral_algebra_map_iff (algebra_map K E).injective).mp h1))) (minpoly.dvd E x ((algebra_map K E).injective (by { rw [ring_hom.map_zero, aeval_map, ←is_scalar_tower.to_alg_hom_apply F K E, ←alg_hom.comp_apply, ←aeval_alg_hom], exact minpoly.aeval F (algebra_map K E x) })))) with y hy, exact ⟨y, hy⟩ }⟩ variables {F} {E} {E' : Type*} [field E'] [algebra F E'] lemma normal.of_alg_equiv [h : normal F E] (f : E ≃ₐ[F] E') : normal F E' := normal_iff.2 $ λ x, begin cases h.out (f.symm x) with hx hhx, have H := is_integral_alg_hom f.to_alg_hom hx, rw [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_equiv.apply_symm_apply] at H, use H, apply polynomial.splits_of_splits_of_dvd (algebra_map F E') (minpoly.ne_zero hx), { rw ← alg_hom.comp_algebra_map f.to_alg_hom, exact polynomial.splits_comp_of_splits (algebra_map F E) f.to_alg_hom.to_ring_hom hhx }, { apply minpoly.dvd _ _, rw ← add_equiv.map_eq_zero_iff f.symm.to_add_equiv, exact eq.trans (polynomial.aeval_alg_hom_apply f.symm.to_alg_hom x (minpoly F (f.symm x))).symm (minpoly.aeval _ _) }, end lemma alg_equiv.transfer_normal (f : E ≃ₐ[F] E') : normal F E ↔ normal F E' := ⟨λ h, by exactI normal.of_alg_equiv f, λ h, by exactI normal.of_alg_equiv f.symm⟩ lemma normal.of_is_splitting_field (p : F[X]) [hFEp : is_splitting_field F E p] : normal F E := begin by_cases hp : p = 0, { haveI : is_splitting_field F F p, { rw hp, exact ⟨splits_zero _, subsingleton.elim _ _⟩ }, exactI (alg_equiv.transfer_normal ((is_splitting_field.alg_equiv F p).trans (is_splitting_field.alg_equiv E p).symm)).mp (normal_self F) }, refine normal_iff.2 (λ x, _), haveI hFE : finite_dimensional F E := is_splitting_field.finite_dimensional E p, have Hx : is_integral F x := is_integral_of_noetherian (is_noetherian.iff_fg.2 hFE) x, refine ⟨Hx, or.inr _⟩, rintros q q_irred ⟨r, hr⟩, let D := adjoin_root q, haveI := fact.mk q_irred, let pbED := adjoin_root.power_basis q_irred.ne_zero, haveI : finite_dimensional E D := power_basis.finite_dimensional pbED, have finrankED : finite_dimensional.finrank E D = q.nat_degree := power_basis.finrank pbED, letI : algebra F D := ring_hom.to_algebra ((algebra_map E D).comp (algebra_map F E)), haveI : is_scalar_tower F E D := of_algebra_map_eq (λ _, rfl), haveI : finite_dimensional F D := finite_dimensional.trans F E D, suffices : nonempty (D →ₐ[F] E), { cases this with ϕ, rw [←with_bot.coe_one, degree_eq_iff_nat_degree_eq q_irred.ne_zero, ←finrankED], have nat_lemma : ∀ a b c : ℕ, a * b = c → c ≤ a → 0 < c → b = 1, { intros a b c h1 h2 h3, nlinarith }, exact nat_lemma _ _ _ (finite_dimensional.finrank_mul_finrank F E D) (linear_map.finrank_le_finrank_of_injective (show function.injective ϕ.to_linear_map, from ϕ.to_ring_hom.injective)) finite_dimensional.finrank_pos, }, let C := adjoin_root (minpoly F x), haveI Hx_irred := fact.mk (minpoly.irreducible Hx), letI : algebra C D := ring_hom.to_algebra (adjoin_root.lift (algebra_map F D) (adjoin_root.root q) (by rw [algebra_map_eq F E D, ←eval₂_map, hr, adjoin_root.algebra_map_eq, eval₂_mul, adjoin_root.eval₂_root, zero_mul])), letI : algebra C E := ring_hom.to_algebra (adjoin_root.lift (algebra_map F E) x (minpoly.aeval F x)), haveI : is_scalar_tower F C D := of_algebra_map_eq (λ x, (adjoin_root.lift_of _).symm), haveI : is_scalar_tower F C E := of_algebra_map_eq (λ x, (adjoin_root.lift_of _).symm), suffices : nonempty (D →ₐ[C] E), { exact nonempty.map (alg_hom.restrict_scalars F) this }, let S : set D := ((p.map (algebra_map F E)).roots.map (algebra_map E D)).to_finset, suffices : ⊤ ≤ intermediate_field.adjoin C S, { refine intermediate_field.alg_hom_mk_adjoin_splits' (top_le_iff.mp this) (λ y hy, _), rcases multiset.mem_map.mp (multiset.mem_to_finset.mp hy) with ⟨z, hz1, hz2⟩, have Hz : is_integral F z := is_integral_of_noetherian (is_noetherian.iff_fg.2 hFE) z, use (show is_integral C y, from is_integral_of_noetherian (is_noetherian.iff_fg.2 (finite_dimensional.right F C D)) y), apply splits_of_splits_of_dvd (algebra_map C E) (map_ne_zero (minpoly.ne_zero Hz)), { rw [splits_map_iff, ←algebra_map_eq F C E], exact splits_of_splits_of_dvd _ hp hFEp.splits (minpoly.dvd F z (eq.trans (eval₂_eq_eval_map _) ((mem_roots (map_ne_zero hp)).mp hz1))) }, { apply minpoly.dvd, rw [←hz2, aeval_def, eval₂_map, ←algebra_map_eq F C D, algebra_map_eq F E D, ←hom_eval₂, ←aeval_def, minpoly.aeval F z, ring_hom.map_zero] } }, rw [←intermediate_field.to_subalgebra_le_to_subalgebra, intermediate_field.top_to_subalgebra], apply ge_trans (intermediate_field.algebra_adjoin_le_adjoin C S), suffices : (algebra.adjoin C S).restrict_scalars F = (algebra.adjoin E {adjoin_root.root q}).restrict_scalars F, { rw [adjoin_root.adjoin_root_eq_top, subalgebra.restrict_scalars_top, ←@subalgebra.restrict_scalars_top F C] at this, exact top_le_iff.mpr (subalgebra.restrict_scalars_injective F this) }, dsimp only [S], rw [←finset.image_to_finset, finset.coe_image], apply eq.trans (algebra.adjoin_res_eq_adjoin_res F E C D hFEp.adjoin_roots adjoin_root.adjoin_root_eq_top), rw [set.image_singleton, ring_hom.algebra_map_to_algebra, adjoin_root.lift_root] end instance (p : F[X]) : normal F p.splitting_field := normal.of_is_splitting_field p end normal_tower variables {F} {K} {K₁ K₂ K₃:Type*} [field K₁] [field K₂] [field K₃] [algebra F K₁] [algebra F K₂] [algebra F K₃] (ϕ : K₁ →ₐ[F] K₂) (χ : K₁ ≃ₐ[F] K₂) (ψ : K₂ →ₐ[F] K₃) (ω : K₂ ≃ₐ[F] K₃) section restrict variables (E : Type*) [field E] [algebra F E] [algebra E K₁] [algebra E K₂] [algebra E K₃] [is_scalar_tower F E K₁] [is_scalar_tower F E K₂] [is_scalar_tower F E K₃] /-- Restrict algebra homomorphism to image of normal subfield -/ def alg_hom.restrict_normal_aux [h : normal F E] : (to_alg_hom F E K₁).range →ₐ[F] (to_alg_hom F E K₂).range := { to_fun := λ x, ⟨ϕ x, by { suffices : (to_alg_hom F E K₁).range.map ϕ ≤ _, { exact this ⟨x, subtype.mem x, rfl⟩ }, rintros x ⟨y, ⟨z, hy⟩, hx⟩, rw [←hx, ←hy], apply minpoly.mem_range_of_degree_eq_one E, exact or.resolve_left (h.splits z) (minpoly.ne_zero (h.is_integral z)) (minpoly.irreducible $ is_integral_of_is_scalar_tower _ $ is_integral_alg_hom ϕ $ is_integral_alg_hom _ $ h.is_integral z) (minpoly.dvd E _ $ by rw [aeval_map, aeval_alg_hom, aeval_alg_hom, alg_hom.comp_apply, alg_hom.comp_apply, minpoly.aeval, alg_hom.map_zero, alg_hom.map_zero]) }⟩, map_zero' := subtype.ext ϕ.map_zero, map_one' := subtype.ext ϕ.map_one, map_add' := λ x y, subtype.ext (ϕ.map_add x y), map_mul' := λ x y, subtype.ext (ϕ.map_mul x y), commutes' := λ x, subtype.ext (ϕ.commutes x) } /-- Restrict algebra homomorphism to normal subfield -/ def alg_hom.restrict_normal [normal F E] : E →ₐ[F] E := ((alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K₂)).symm.to_alg_hom.comp (ϕ.restrict_normal_aux E)).comp (alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K₁)).to_alg_hom /-- Restrict algebra homomorphism to normal subfield (`alg_equiv` version) -/ def alg_hom.restrict_normal' [normal F E] : E ≃ₐ[F] E := alg_equiv.of_bijective (alg_hom.restrict_normal ϕ E) (alg_hom.normal_bijective F E E _) @[simp] lemma alg_hom.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K₂ (ϕ.restrict_normal E x) = ϕ (algebra_map E K₁ x) := subtype.ext_iff.mp (alg_equiv.apply_symm_apply (alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K₂)) (ϕ.restrict_normal_aux E ⟨is_scalar_tower.to_alg_hom F E K₁ x, x, rfl⟩)) lemma alg_hom.restrict_normal_comp [normal F E] : (ψ.restrict_normal E).comp (ϕ.restrict_normal E) = (ψ.comp ϕ).restrict_normal E := alg_hom.ext (λ _, (algebra_map E K₃).injective (by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes])) /-- Restrict algebra isomorphism to a normal subfield -/ def alg_equiv.restrict_normal [h : normal F E] : E ≃ₐ[F] E := alg_hom.restrict_normal' χ.to_alg_hom E @[simp] lemma alg_equiv.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K₂ (χ.restrict_normal E x) = χ (algebra_map E K₁ x) := χ.to_alg_hom.restrict_normal_commutes E x lemma alg_equiv.restrict_normal_trans [normal F E] : (χ.trans ω).restrict_normal E = (χ.restrict_normal E).trans (ω.restrict_normal E) := alg_equiv.ext (λ _, (algebra_map E K₃).injective (by simp only [alg_equiv.trans_apply, alg_equiv.restrict_normal_commutes])) /-- Restriction to an normal subfield as a group homomorphism -/ def alg_equiv.restrict_normal_hom [normal F E] : (K₁ ≃ₐ[F] K₁) →* (E ≃ₐ[F] E) := monoid_hom.mk' (λ χ, χ.restrict_normal E) (λ ω χ, (χ.restrict_normal_trans ω E)) variables (F K₁ E) /-- If `K₁/E/F` is a tower of fields with `E/F` normal then `normal.alg_hom_equiv_aut` is an equivalence. -/ @[simps] def normal.alg_hom_equiv_aut [normal F E] : (E →ₐ[F] K₁) ≃ (E ≃ₐ[F] E) := { to_fun := λ σ, alg_hom.restrict_normal' σ E, inv_fun := λ σ, (is_scalar_tower.to_alg_hom F E K₁).comp σ.to_alg_hom, left_inv := λ σ, begin ext, simp[alg_hom.restrict_normal'], end, right_inv := λ σ, begin ext, simp only [alg_hom.restrict_normal', alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_of_bijective], apply no_zero_smul_divisors.algebra_map_injective E K₁, rw alg_hom.restrict_normal_commutes, simp, end } end restrict section lift variables {F} {K₁ K₂} (E : Type*) [field E] [algebra F E] [algebra K₁ E] [algebra K₂ E] [is_scalar_tower F K₁ E] [is_scalar_tower F K₂ E] /-- If `E/Kᵢ/F` are towers of fields with `E/F` normal then we can lift an algebra homomorphism `ϕ : K₁ →ₐ[F] K₂` to `ϕ.lift_normal E : E →ₐ[F] E`. -/ noncomputable def alg_hom.lift_normal [h : normal F E] : E →ₐ[F] E := @alg_hom.restrict_scalars F K₁ E E _ _ _ _ _ _ ((is_scalar_tower.to_alg_hom F K₂ E).comp ϕ).to_ring_hom.to_algebra _ _ _ _ $ nonempty.some $ @intermediate_field.alg_hom_mk_adjoin_splits' _ _ _ _ _ _ _ ((is_scalar_tower.to_alg_hom F K₂ E).comp ϕ).to_ring_hom.to_algebra _ (intermediate_field.adjoin_univ _ _) (λ x hx, ⟨is_integral_of_is_scalar_tower x (h.out x).1, splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero (h.out x).1)) (by { rw [splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact (h.out x).2 }) (minpoly.dvd_map_of_is_scalar_tower F K₁ x)⟩) @[simp] lemma alg_hom.lift_normal_commutes [normal F E] (x : K₁) : ϕ.lift_normal E (algebra_map K₁ E x) = algebra_map K₂ E (ϕ x) := by apply @alg_hom.commutes K₁ E E _ _ _ _ @[simp] lemma alg_hom.restrict_lift_normal (ϕ : K₁ →ₐ[F] K₁) [normal F K₁] [normal F E] : (ϕ.lift_normal E).restrict_normal K₁ = ϕ := alg_hom.ext (λ x, (algebra_map K₁ E).injective (eq.trans (alg_hom.restrict_normal_commutes _ K₁ x) (ϕ.lift_normal_commutes E x))) /-- If `E/Kᵢ/F` are towers of fields with `E/F` normal then we can lift an algebra isomorphism `ϕ : K₁ ≃ₐ[F] K₂` to `ϕ.lift_normal E : E ≃ₐ[F] E`. -/ noncomputable def alg_equiv.lift_normal [normal F E] : E ≃ₐ[F] E := alg_equiv.of_bijective (χ.to_alg_hom.lift_normal E) (alg_hom.normal_bijective F E E _) @[simp] lemma alg_equiv.lift_normal_commutes [normal F E] (x : K₁) : χ.lift_normal E (algebra_map K₁ E x) = algebra_map K₂ E (χ x) := χ.to_alg_hom.lift_normal_commutes E x @[simp] lemma alg_equiv.restrict_lift_normal (χ : K₁ ≃ₐ[F] K₁) [normal F K₁] [normal F E] : (χ.lift_normal E).restrict_normal K₁ = χ := alg_equiv.ext (λ x, (algebra_map K₁ E).injective (eq.trans (alg_equiv.restrict_normal_commutes _ K₁ x) (χ.lift_normal_commutes E x))) lemma alg_equiv.restrict_normal_hom_surjective [normal F K₁] [normal F E] : function.surjective (alg_equiv.restrict_normal_hom K₁ : (E ≃ₐ[F] E) → (K₁ ≃ₐ[F] K₁)) := λ χ, ⟨χ.lift_normal E, χ.restrict_lift_normal E⟩ variables (F) (K₁) (E) lemma is_solvable_of_is_scalar_tower [normal F K₁] [h1 : is_solvable (K₁ ≃ₐ[F] K₁)] [h2 : is_solvable (E ≃ₐ[K₁] E)] : is_solvable (E ≃ₐ[F] E) := begin let f : (E ≃ₐ[K₁] E) →* (E ≃ₐ[F] E) := { to_fun := λ ϕ, alg_equiv.of_alg_hom (ϕ.to_alg_hom.restrict_scalars F) (ϕ.symm.to_alg_hom.restrict_scalars F) (alg_hom.ext (λ x, ϕ.apply_symm_apply x)) (alg_hom.ext (λ x, ϕ.symm_apply_apply x)), map_one' := alg_equiv.ext (λ _, rfl), map_mul' := λ _ _, alg_equiv.ext (λ _, rfl) }, refine solvable_of_ker_le_range f (alg_equiv.restrict_normal_hom K₁) (λ ϕ hϕ, ⟨{commutes' := λ x, _, .. ϕ}, alg_equiv.ext (λ _, rfl)⟩), exact (eq.trans (ϕ.restrict_normal_commutes K₁ x).symm (congr_arg _ (alg_equiv.ext_iff.mp hϕ x))), end end lift
bb768c93fbdf6a2e675a86aac2596487d30d9254
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/coe3.lean
700f0d2513c19d7c4c4426aaf82bf0e33fa9c211
[ "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
319
lean
constants A B₁ B₂ C D : Type constant A_to_B₁ : has_coe A B₁ constant A_to_B₂ : has_coe A B₂ constant B₁_to_C : has_coe B₁ C constant B₂_to_D : has_coe B₂ D attribute [instance] A_to_B₁ A_to_B₂ B₁_to_C B₂_to_D constant a : A constant f : C → C constant g : D → D check f a check g a
927d2739f0562c428b94fe3f1478d5801332b9ef
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/ctor_layout.lean
c2c9250bf6e7995242b2e7f772edf1d3929aab60
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
639
lean
import Lean.Compiler.IR open Lean open Lean.IR unsafe def main : IO Unit := withImportModules [{module := `Lean.Compiler.IR.Basic}] 0 fun env => do ctorLayout ← IO.ofExcept $ getCtorLayout env `Lean.IR.Expr.reuse; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); IO.println "---"; ctorLayout ← IO.ofExcept $ getCtorLayout env `Lean.EnvironmentHeader.mk; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); IO.println "---"; ctorLayout ← IO.ofExcept $ getCtorLayout env `Subtype.mk; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); pure () #eval main
1d135e80c676dfbb501c5456feb3c76da8bf803c
649957717d58c43b5d8d200da34bf374293fe739
/src/data/equiv/algebra.lean
cdf5e28c0ce7d1066cfda806691ba7f638ee475f
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
11,286
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl The role of this file is twofold. In the first part there are theorems of the following form: if α has a group structure and α ≃ β then β has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. In the second part there are extensions of equiv called add_equiv, mul_equiv, and ring_equiv, which are datatypes representing isomorphisms of monoids, groups and rings. -/ import data.equiv.basic algebra.field universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} namespace equiv section group variables [group α] protected def mul_left (a : α) : α ≃ α := { to_fun := λx, a * x, inv_fun := λx, a⁻¹ * x, left_inv := assume x, show a⁻¹ * (a * x) = x, from inv_mul_cancel_left a x, right_inv := assume x, show a * (a⁻¹ * x) = x, from mul_inv_cancel_left a x } attribute [to_additive equiv.add_left._proof_1] equiv.mul_left._proof_1 attribute [to_additive equiv.add_left._proof_2] equiv.mul_left._proof_2 attribute [to_additive equiv.add_left] equiv.mul_left protected def mul_right (a : α) : α ≃ α := { to_fun := λx, x * a, inv_fun := λx, x * a⁻¹, left_inv := assume x, show (x * a) * a⁻¹ = x, from mul_inv_cancel_right x a, right_inv := assume x, show (x * a⁻¹) * a = x, from inv_mul_cancel_right x a } attribute [to_additive equiv.add_right._proof_1] equiv.mul_right._proof_1 attribute [to_additive equiv.add_right._proof_2] equiv.mul_right._proof_2 attribute [to_additive equiv.add_right] equiv.mul_right protected def inv (α) [group α] : α ≃ α := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } attribute [to_additive equiv.neg._proof_1] equiv.inv._proof_1 attribute [to_additive equiv.neg._proof_2] equiv.inv._proof_2 attribute [to_additive equiv.neg] equiv.inv def units_equiv_ne_zero (α : Type*) [field α] : units α ≃ {a : α | a ≠ 0} := ⟨λ a, ⟨a.1, units.ne_zero _⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ @[simp] lemma coe_units_equiv_ne_zero [field α] (a : units α) : ((units_equiv_ne_zero α a) : α) = a := rfl end group section instances variables (e : α ≃ β) protected def has_zero [has_zero β] : has_zero α := ⟨e.symm 0⟩ lemma zero_def [has_zero β] : @has_zero.zero _ (equiv.has_zero e) = e.symm 0 := rfl protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl protected def has_add [has_add β] : has_add α := ⟨λ x y, e.symm (e x + e y)⟩ lemma add_def [has_add β] (x y : α) : @has_add.add _ (equiv.has_add e) x y = e.symm (e x + e y) := rfl protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl protected def has_neg [has_neg β] : has_neg α := ⟨λ x, e.symm (-e x)⟩ lemma neg_def [has_neg β] (x : α) : @has_neg.neg _ (equiv.has_neg e) x = e.symm (-e x) := rfl protected def semigroup [semigroup β] : semigroup α := { mul_assoc := by simp [mul_def, mul_assoc], ..equiv.has_mul e } protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := { mul_comm := by simp [mul_def, mul_comm], ..equiv.semigroup e } protected def monoid [monoid β] : monoid α := { one_mul := by simp [mul_def, one_def], mul_one := by simp [mul_def, one_def], ..equiv.semigroup e, ..equiv.has_one e } protected def comm_monoid [comm_monoid β] : comm_monoid α := { ..equiv.comm_semigroup e, ..equiv.monoid e } protected def group [group β] : group α := { mul_left_inv := by simp [mul_def, inv_def, one_def], ..equiv.monoid e, ..equiv.has_inv e } protected def comm_group [comm_group β] : comm_group α := { ..equiv.group e, ..equiv.comm_semigroup e } protected def add_semigroup [add_semigroup β] : add_semigroup α := @additive.add_semigroup _ (@equiv.semigroup _ _ e multiplicative.semigroup) protected def add_comm_semigroup [add_comm_semigroup β] : add_comm_semigroup α := @additive.add_comm_semigroup _ (@equiv.comm_semigroup _ _ e multiplicative.comm_semigroup) protected def add_monoid [add_monoid β] : add_monoid α := @additive.add_monoid _ (@equiv.monoid _ _ e multiplicative.monoid) protected def add_comm_monoid [add_comm_monoid β] : add_comm_monoid α := @additive.add_comm_monoid _ (@equiv.comm_monoid _ _ e multiplicative.comm_monoid) protected def add_group [add_group β] : add_group α := @additive.add_group _ (@equiv.group _ _ e multiplicative.group) protected def add_comm_group [add_comm_group β] : add_comm_group α := @additive.add_comm_group _ (@equiv.comm_group _ _ e multiplicative.comm_group) protected def semiring [semiring β] : semiring α := { right_distrib := by simp [mul_def, add_def, add_mul], left_distrib := by simp [mul_def, add_def, mul_add], zero_mul := by simp [mul_def, zero_def], mul_zero := by simp [mul_def, zero_def], ..equiv.has_zero e, ..equiv.has_mul e, ..equiv.has_add e, ..equiv.monoid e, ..equiv.add_comm_monoid e } protected def comm_semiring [comm_semiring β] : comm_semiring α := { ..equiv.semiring e, ..equiv.comm_monoid e } protected def ring [ring β] : ring α := { ..equiv.semiring e, ..equiv.add_comm_group e } protected def comm_ring [comm_ring β] : comm_ring α := { ..equiv.comm_monoid e, ..equiv.ring e } protected def zero_ne_one_class [zero_ne_one_class β] : zero_ne_one_class α := { zero_ne_one := by simp [zero_def, one_def], ..equiv.has_zero e, ..equiv.has_one e } protected def nonzero_comm_ring [nonzero_comm_ring β] : nonzero_comm_ring α := { ..equiv.zero_ne_one_class e, ..equiv.comm_ring e } protected def domain [domain β] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.eq_symm_apply], ..equiv.has_zero e, ..equiv.zero_ne_one_class e, ..equiv.has_mul e, ..equiv.ring e } protected def integral_domain [integral_domain β] : integral_domain α := { ..equiv.domain e, ..equiv.nonzero_comm_ring e } protected def division_ring [division_ring β] : division_ring α := { inv_mul_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact inv_mul_cancel, mul_inv_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact mul_inv_cancel, ..equiv.has_zero e, ..equiv.has_one e, ..equiv.domain e, ..equiv.has_inv e } protected def field [field β] : field α := { ..equiv.integral_domain e, ..equiv.division_ring e } protected def discrete_field [discrete_field β] : discrete_field α := { has_decidable_eq := equiv.decidable_eq e, inv_zero := by simp [mul_def, inv_def, zero_def], ..equiv.has_mul e, ..equiv.has_inv e, ..equiv.has_zero e, ..equiv.field e } end instances end equiv structure mul_equiv (α β : Type*) [has_mul α] [has_mul β] extends α ≃ β := (hom : is_mul_hom to_fun) structure add_equiv (α β : Type*) [has_add α] [has_add β] extends α ≃ β := (hom : is_add_hom to_fun) attribute [to_additive add_equiv] mul_equiv attribute [to_additive add_equiv.mk] mul_equiv.mk attribute [to_additive add_equiv.to_equiv] mul_equiv.to_equiv attribute [to_additive add_equiv.hom] mul_equiv.hom infix ` ≃* `:50 := mul_equiv infix ` ≃+ `:50 := add_equiv namespace mul_equiv variables [has_mul α] [has_mul β] [has_mul γ] @[to_additive add_mul.is_add_hom] instance (h : α ≃* β) : is_mul_hom h.to_equiv := h.hom @[refl] def refl (α : Type*) [has_mul α] : α ≃* α := { hom := ⟨λ _ _,rfl⟩, ..equiv.refl _} attribute [to_additive add_equiv.refl._proof_3] mul_equiv.refl._proof_3 attribute [to_additive add_equiv.refl] mul_equiv.refl @[symm] def symm (h : α ≃* β) : β ≃* α := { hom := ⟨λ n₁ n₂, function.injective_of_left_inverse h.left_inv begin rw h.hom.map_mul, unfold equiv.symm, rw [h.right_inv, h.right_inv, h.right_inv], end⟩ ..h.to_equiv.symm} attribute [to_additive add_equiv.symm._proof_1] mul_equiv.symm._proof_1 attribute [to_additive add_equiv.symm._proof_2] mul_equiv.symm._proof_2 attribute [to_additive add_equiv.symm._proof_3] mul_equiv.symm._proof_3 attribute [to_additive add_equiv.symm] mul_equiv.symm @[trans] def trans (h1 : α ≃* β) (h2 : β ≃* γ) : (α ≃* γ) := { hom := is_mul_hom.comp h1.hom h2.hom, ..equiv.trans h1.to_equiv h2.to_equiv } attribute [to_additive add_equiv.trans._proof_1] mul_equiv.trans._proof_1 attribute [to_additive add_equiv.trans._proof_2] mul_equiv.trans._proof_2 attribute [to_additive add_equiv.trans._proof_3] mul_equiv.trans._proof_3 attribute [to_additive add_equiv.trans] mul_equiv.trans end mul_equiv -- equiv of monoids @[to_additive add_equiv.is_add_monoid_hom] instance mul_equiv.is_monoid_hom [monoid α] [monoid β] (h : α ≃* β) : is_monoid_hom h.to_equiv := { map_one := by rw [← mul_one (h.to_equiv 1), ← h.to_equiv.apply_symm_apply 1, ← is_mul_hom.map_mul h.to_equiv, one_mul] } -- equiv of groups @[to_additive add_equiv.is_add_group_hom] instance mul_equiv.is_group_hom [group α] [group β] (h : α ≃* β) : is_group_hom h.to_equiv := { ..h.hom } namespace units variables [monoid α] [monoid β] [monoid γ] (f : α → β) (g : β → γ) [is_monoid_hom f] [is_monoid_hom g] def map_equiv (h : α ≃* β) : units α ≃* units β := { to_fun := map h.to_equiv, inv_fun := map h.symm.to_equiv, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, hom := ⟨λ a b, units.ext $ is_mul_hom.map_mul h.to_equiv⟩} end units structure ring_equiv (α β : Type*) [ring α] [ring β] extends α ≃ β := (hom : is_ring_hom to_fun) infix ` ≃r `:50 := ring_equiv namespace ring_equiv variables [ring α] [ring β] [ring γ] instance (h : α ≃r β) : is_ring_hom h.to_equiv := h.hom protected def refl (α : Type*) [ring α] : α ≃r α := { hom := is_ring_hom.id, .. equiv.refl α } protected def symm {α β : Type*} [ring α] [ring β] (e : α ≃r β) : β ≃r α := { hom := ⟨(equiv.symm_apply_eq _).2 e.hom.1.symm, λ x y, (equiv.symm_apply_eq _).2 $ show _ = e.to_equiv.to_fun _, by rw [e.2.2, e.1.4, e.1.4], λ x y, (equiv.symm_apply_eq _).2 $ show _ = e.to_equiv.to_fun _, by rw [e.2.3, e.1.4, e.1.4]⟩, .. e.to_equiv.symm } protected def trans {α β γ : Type*} [ring α] [ring β] [ring γ] (e₁ : α ≃r β) (e₂ : β ≃r γ) : α ≃r γ := { hom := is_ring_hom.comp _ _, .. e₁.1.trans e₂.1 } instance symm.is_ring_hom {e : α ≃r β} : is_ring_hom e.to_equiv.symm := hom e.symm @[simp] lemma to_equiv_symm (e : α ≃r β) : e.symm.to_equiv = e.to_equiv.symm := rfl @[simp] lemma to_equiv_symm_apply (e : α ≃r β) (x : β) : e.symm.to_equiv x = e.to_equiv.symm x := rfl end ring_equiv
42c1e0504e957ec29c9954b98ce1e24a003c47fc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1841.lean
94a898f27af243b6df2f69d5f25112b05f43db18
[ "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
846
lean
variable {α : Type} {r : α → α → Prop} {b : α} inductive ReflTransGen (r : α → α → Prop) (a : α) : α → Prop | refl : ReflTransGen r a a | tail {b c} : ReflTransGen r a b → r b c → ReflTransGen r a c namespace ReflTransGen theorem head (hab : r a b) (hbc : ReflTransGen r b c) : ReflTransGen r a c := by induction hbc case refl => exact refl.tail hab case tail c d _ hcd hac => exact hac.tail hcd @[elab_as_elim] theorem head_induction_on {P : ∀ a : α, ReflTransGen r a b → Prop} {a : α} (h : ReflTransGen r a b) (refl : P b refl) (head : ∀ {a c} (h' : r a c) (h : ReflTransGen r c b), P c h → P a (h.head h')) : P a h := by induction h case refl => exact refl case tail b c _ hbc ih => apply ih { exact head hbc _ refl } { exact fun h1 h2 => head h1 (h2.tail hbc) } end ReflTransGen
9328d9df9410640d3ec44fe84de2de687022d55c
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/meta/expr.lean
3bac692e77c8964d195f5da5be2091dcaa227f4d
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
33,671
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs import tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`. -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ meta def app_symbol_in (e : expr) (l : list name) : bool := match e.get_app_fn with | (expr.const n _) := n ∈ l | _ := ff end /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the retulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic /-- `declaration.update_with_fun f tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names of all `expr.const`s which appear in the value or type of `decl`. -/ protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
ef886d819076f90f4e8702590b1f8d48558a4409
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/determinant.lean
2d4b4870ca51d9aa865f21a76594a73f43b6b3d1
[ "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
23,812
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.multilinear.basis import linear_algebra.matrix.reindex import ring_theory.algebra_tower import tactic.field_simp import linear_algebra.matrix.nonsingular_inverse import linear_algebra.matrix.basis /-! # 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) * `linear_equiv.det`: the determinant of an isomorphism `f : M ≃ₗ[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 set function 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] [nontrivial 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 [nontrivial 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' [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) := begin nontriviality A, -- 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, rw [← det_submatrix_equiv_self e, ← submatrix_mul_equiv _ _ _ (equiv.refl n) _, det_comm, submatrix_mul_equiv, equiv.coe_refl, submatrix_id_id] end /-- If `M'` is a two-sided inverse for `M` (indexed differently), `det (M ⬝ N ⬝ M') = det N`. See `matrix.det_conj` and `matrix.det_conj'` for the case when `M' = M⁻¹` or vice versa. -/ lemma det_conj_of_mul_eq_one [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] [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_of_mul_eq_one]; 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'] @[simp] lemma det_to_lin (b : basis ι R M) (f : matrix ι ι R) : linear_map.det (matrix.to_lin b b f) = f.det := by rw [← linear_map.det_to_matrix b, linear_map.to_matrix_to_lin] /-- 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_fintype_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*} [finite ι] [nonempty ι] (b : basis ι A M) : linear_map.det (0 : M →ₗ[A] M) = 0 := by { haveI := classical.dec_eq ι, casesI nonempty_fintype ι, rwa [← det_to_matrix b, linear_equiv.map_zero, det_zero] } /-- In a finite-dimensional vector space, the zero map has determinant `1` in dimension `0`, and `0` otherwise. We give a formula that also works in infinite dimension, where we define the determinant to be `1`. -/ @[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_of_mul_eq_one], { rw [← to_matrix_comp, linear_equiv.comp_coe, e.symm_trans_self, linear_equiv.refl_to_linear_map, to_matrix_id] }, { rw [← to_matrix_comp, linear_equiv.comp_coe, e.self_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 /-- If a linear map is invertible, so is its determinant. -/ lemma is_unit_det {A : Type*} [comm_ring A] [module A M] (f : M →ₗ[A] M) (hf : is_unit f) : is_unit f.det := begin obtain ⟨g, hg⟩ : ∃ g, f.comp g = 1 := hf.exists_right_inv, have : linear_map.det f * linear_map.det g = 1, by simp only [← linear_map.det_comp, hg, monoid_hom.map_one], exact is_unit_of_mul_eq_one _ _ this, end /-- If a linear map has determinant different from `1`, then the space is finite-dimensional. -/ lemma finite_dimensional_of_det_ne_one {𝕜 : Type*} [field 𝕜] [module 𝕜 M] (f : M →ₗ[𝕜] M) (hf : f.det ≠ 1) : finite_dimensional 𝕜 M := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_fintype_basis hs }, { classical, simp [linear_map.coe_det, H] at hf, exact hf.elim } end /-- If the determinant of a map vanishes, then the map is not onto. -/ lemma range_lt_top_of_det_eq_zero {𝕜 : Type*} [field 𝕜] [module 𝕜 M] {f : M →ₗ[𝕜] M} (hf : f.det = 0) : f.range < ⊤ := begin haveI : finite_dimensional 𝕜 M, by simp [f.finite_dimensional_of_det_ne_one, hf], contrapose hf, simp only [lt_top_iff_ne_top, not_not, ← is_unit_iff_range_eq_top] at hf, exact is_unit_iff_ne_zero.1 (f.is_unit_det hf) end /-- If the determinant of a map vanishes, then the map is not injective. -/ lemma bot_lt_ker_of_det_eq_zero {𝕜 : Type*} [field 𝕜] [module 𝕜 M] {f : M →ₗ[𝕜] M} (hf : f.det = 0) : ⊥ < f.ker := begin haveI : finite_dimensional 𝕜 M, by simp [f.finite_dimensional_of_det_ne_one, hf], contrapose hf, simp only [bot_lt_iff_ne_bot, not_not, ← is_unit_iff_ker_eq_bot] at hf, exact is_unit_iff_ne_zero.1 (f.is_unit_det hf) end end linear_map namespace linear_equiv /-- On a `linear_equiv`, the domain of `linear_map.det` can be promoted to `Rˣ`. -/ protected def det : (M ≃ₗ[R] M) →* Rˣ := (units.map (linear_map.det : (M →ₗ[R] M) →* R)).comp (linear_map.general_linear_group.general_linear_equiv R M).symm.to_monoid_hom @[simp] lemma coe_det (f : M ≃ₗ[R] M) : ↑f.det = linear_map.det (f : M →ₗ[R] M) := rfl @[simp] lemma coe_inv_det (f : M ≃ₗ[R] M) : ↑(f.det⁻¹) = linear_map.det (f.symm : M →ₗ[R] M) := rfl @[simp] lemma det_refl : (linear_equiv.refl R M).det = 1 := units.ext $ linear_map.det_id @[simp] lemma det_trans (f g : M ≃ₗ[R] M) : (f.trans g).det = g.det * f.det := map_mul _ g f @[simp] lemma det_symm (f : M ≃ₗ[R] M) : f.symm.det = f.det⁻¹ := map_inv _ f /-- Conjugating a linear equiv by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj (f : M ≃ₗ[R] M) (e : M ≃ₗ[R] M') : ((e.symm.trans f).trans e).det = f.det := by rw [←units.eq_iff, coe_det, coe_det, ←comp_coe, ←comp_coe, linear_map.det_conj] end linear_equiv /-- The determinants of a `linear_equiv` and its inverse multiply to 1. -/ @[simp] lemma linear_equiv.det_mul_det_symm {A : Type*} [comm_ring A] [module A M] (f : M ≃ₗ[A] M) : (f : M →ₗ[A] M).det * (f.symm : M →ₗ[A] M).det = 1 := by simp [←linear_map.det_comp] /-- The determinants of a `linear_equiv` and its inverse multiply to 1. -/ @[simp] lemma linear_equiv.det_symm_mul_det {A : Type*} [comm_ring A] [module A M] (f : M ≃ₗ[A] M) : (f.symm : M →ₗ[A] M).det * (f : M →ₗ[A] M).det = 1 := by simp [←linear_map.det_comp] -- 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] [module A M] (f : M ≃ₗ[A] M) : is_unit (linear_map.det (f : M →ₗ[A] M)) := is_unit_of_mul_eq_one _ _ f.det_mul_det_symm /-- The determinant of `f.symm` is the inverse of that of `f` when `f` is a linear equiv. -/ lemma linear_equiv.det_coe_symm {𝕜 : Type*} [field 𝕜] [module 𝕜 M] (f : M ≃ₗ[𝕜] M) : (f.symm : M →ₗ[𝕜] M).det = (f : M →ₗ[𝕜] M).det ⁻¹ := by field_simp [is_unit.ne_zero f.is_unit_det'] /-- 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] } @[simp] lemma linear_equiv.coe_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) : (linear_equiv.of_is_unit_det h : M →ₗ[R] M') = f := by { ext x, refl } /-- 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 lemma linear_map.associated_det_of_eq_comp (e : M ≃ₗ[R] M) (f f' : M →ₗ[R] M) (h : ∀ x, f x = f' (e x)) : associated f.det f'.det := begin suffices : associated (f' ∘ₗ ↑e).det f'.det, { convert this using 2, ext x, exact h x }, rw [← mul_one f'.det, linear_map.det_comp], exact associated.mul_left _ (associated_one_iff_is_unit.mpr e.is_unit_det') end lemma linear_map.associated_det_comp_equiv {N : Type*} [add_comm_group N] [module R N] (f : N →ₗ[R] M) (e e' : M ≃ₗ[R] N) : associated (f ∘ₗ ↑e).det (f ∘ₗ ↑e').det := begin refine linear_map.associated_det_of_eq_comp (e.trans e'.symm) _ _ _, intro x, simp only [linear_map.comp_apply, linear_equiv.coe_coe, linear_equiv.trans_apply, linear_equiv.apply_symm_apply], end /-- 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] /-- `basis.det` is not the zero map. -/ lemma basis.det_ne_zero [nontrivial R] : e.det ≠ 0 := λ h, by simpa [h] using e.det_self 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.ge 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⟩ /-- Any alternating map to `R` where `ι` has the cardinality of a basis equals the determinant map with respect to that basis, multiplied by the value of that alternating map on that basis. -/ lemma alternating_map.eq_smul_basis_det (f : alternating_map R M R ι) : f = f e • e.det := begin refine basis.ext_alternating e (λ i h, _), let σ : equiv.perm ι := equiv.of_bijective i (finite.injective_iff_bijective.1 h), change f (e ∘ σ) = (f e • e.det) (e ∘ σ), simp [alternating_map.map_perm, basis.det_self] end @[simp] lemma alternating_map.map_basis_eq_zero_iff {ι : Type*} [decidable_eq ι] [finite ι] (e : basis ι R M) (f : alternating_map R M R ι) : f e = 0 ↔ f = 0 := ⟨λ h, by { casesI nonempty_fintype ι, simpa [h] using f.eq_smul_basis_det e }, λ h, h.symm ▸ alternating_map.zero_apply _⟩ lemma alternating_map.map_basis_ne_zero_iff {ι : Type*} [decidable_eq ι] [finite ι] (e : basis ι R M) (f : alternating_map R M R ι) : f e ≠ 0 ↔ f ≠ 0 := not_congr $ f.map_basis_eq_zero_iff e variables {A : Type*} [comm_ring 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] } lemma basis.det_map' (b : basis ι R M) (f : M ≃ₗ[R] M') : (b.map f).det = b.det.comp_linear_map f.symm := alternating_map.ext $ b.det_map f @[simp] lemma pi.basis_fun_det : (pi.basis_fun R ι).det = matrix.det_row_alternating := begin ext M, rw [basis.det_apply, basis.coe_pi_basis_fun.to_matrix_eq_transpose, det_transpose], end /-- If we fix a background basis `e`, then for any other basis `v`, we can characterise the coordinates provided by `v` in terms of determinants relative to `e`. -/ lemma basis.det_smul_mk_coord_eq_det_update {v : ι → M} (hli : linear_independent R v) (hsp : ⊤ ≤ span R (range v)) (i : ι) : (e.det v) • (basis.mk hli hsp).coord i = e.det.to_multilinear_map.to_linear_map v i := begin apply (basis.mk hli hsp).ext, intros k, rcases eq_or_ne k i with rfl | hik; simp only [algebra.id.smul_eq_mul, basis.coe_mk, linear_map.smul_apply, linear_map.coe_mk, multilinear_map.to_linear_map_apply], { rw [basis.mk_coord_apply_eq, mul_one, update_eq_self], congr, }, { rw [basis.mk_coord_apply_ne hik, mul_zero, eq_comm], exact e.det.map_eq_zero_of_eq _ (by simp [hik, function.update_apply]) hik, }, end /-- The determinant of a basis constructed by `units_smul` is the product of the given units. -/ @[simp] lemma basis.det_units_smul (w : ι → Rˣ) : e.det (e.units_smul w) = ∏ i, w i := by simp [basis.det_apply] /-- The determinant of a basis constructed by `is_unit_smul` is the product of the given units. -/ @[simp] lemma basis.det_is_unit_smul {w : ι → R} (hw : ∀ i, is_unit (w i)) : e.det (e.is_unit_smul hw) = ∏ i, w i := e.det_units_smul _
92653497851c5072e1c21837ce10cf247908f318
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/matrix_exponential.lean
678d4710a310b0dd12ec5653a204d16a8e1473fd
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,590
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import analysis.normed_space.exponential import analysis.matrix import linear_algebra.matrix.zpow import linear_algebra.matrix.hermitian import linear_algebra.matrix.symmetric import topology.uniform_space.matrix /-! # Lemmas about the matrix exponential > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we provide results about `exp` on `matrix`s over a topological or normed algebra. Note that generic results over all topological spaces such as `exp_zero` can be used on matrices without issue, so are not repeated here. The topological results specific to matrices are: * `matrix.exp_transpose` * `matrix.exp_conj_transpose` * `matrix.exp_diagonal` * `matrix.exp_block_diagonal` * `matrix.exp_block_diagonal'` Lemmas like `exp_add_of_commute` require a canonical norm on the type; while there are multiple sensible choices for the norm of a `matrix` (`matrix.normed_add_comm_group`, `matrix.frobenius_normed_add_comm_group`, `matrix.linfty_op_normed_add_comm_group`), none of them are canonical. In an application where a particular norm is chosen using `local attribute [instance]`, then the usual lemmas about `exp` are fine. When choosing a norm is undesirable, the results in this file can be used. In this file, we copy across the lemmas about `exp`, but hide the requirement for a norm inside the proof. * `matrix.exp_add_of_commute` * `matrix.exp_sum_of_commute` * `matrix.exp_nsmul` * `matrix.is_unit_exp` * `matrix.exp_units_conj` * `matrix.exp_units_conj'` Additionally, we prove some results about `matrix.has_inv` and `matrix.div_inv_monoid`, as the results for general rings are instead stated about `ring.inverse`: * `matrix.exp_neg` * `matrix.exp_zsmul` * `matrix.exp_conj` * `matrix.exp_conj'` ## Implementation notes This file runs into some sharp edges on typeclass search in lean 3, especially regarding pi types. To work around this, we copy a handful of instances for when lean can't find them by itself. Hopefully we will be able to remove these in Lean 4. ## TODO * Show that `matrix.det (exp 𝕂 A) = exp 𝕂 (matrix.trace A)` ## References * https://en.wikipedia.org/wiki/Matrix_exponential -/ open_locale matrix big_operators section hacks_for_pi_instance_search /-- A special case of `pi.topological_ring` for when `R` is not dependently typed. -/ instance function.topological_ring (I : Type*) (R : Type*) [non_unital_ring R] [topological_space R] [topological_ring R] : topological_ring (I → R) := pi.topological_ring /-- A special case of `function.algebra` for when A is a `ring` not a `semiring` -/ instance function.algebra_ring (I : Type*) {R : Type*} (A : Type*) [comm_semiring R] [ring A] [algebra R A] : algebra R (I → A) := pi.algebra _ _ /-- A special case of `pi.algebra` for when `f = λ i, matrix (m i) (m i) A`. -/ instance pi.matrix_algebra (I R A : Type*) (m : I → Type*) [comm_semiring R] [semiring A] [algebra R A] [Π i, fintype (m i)] [Π i, decidable_eq (m i)] : algebra R (Π i, matrix (m i) (m i) A) := @pi.algebra I R (λ i, matrix (m i) (m i) A) _ _ (λ i, matrix.algebra) /-- A special case of `pi.topological_ring` for when `f = λ i, matrix (m i) (m i) A`. -/ instance pi.matrix_topological_ring (I A : Type*) (m : I → Type*) [ring A] [topological_space A] [topological_ring A] [Π i, fintype (m i)] : topological_ring (Π i, matrix (m i) (m i) A) := @pi.topological_ring _ (λ i, matrix (m i) (m i) A) _ _ (λ i, matrix.topological_ring) end hacks_for_pi_instance_search variables (𝕂 : Type*) {m n p : Type*} {n' : m → Type*} {𝔸 : Type*} namespace matrix section topological section ring variables [fintype m] [decidable_eq m] [fintype n] [decidable_eq n] [Π i, fintype (n' i)] [Π i, decidable_eq (n' i)] [field 𝕂] [ring 𝔸] [topological_space 𝔸] [topological_ring 𝔸] [algebra 𝕂 𝔸] [t2_space 𝔸] lemma exp_diagonal (v : m → 𝔸) : exp 𝕂 (diagonal v) = diagonal (exp 𝕂 v) := by simp_rw [exp_eq_tsum, diagonal_pow, ←diagonal_smul, ←diagonal_tsum] lemma exp_block_diagonal (v : m → matrix n n 𝔸) : exp 𝕂 (block_diagonal v) = block_diagonal (exp 𝕂 v) := by simp_rw [exp_eq_tsum, ←block_diagonal_pow, ←block_diagonal_smul, ←block_diagonal_tsum] lemma exp_block_diagonal' (v : Π i, matrix (n' i) (n' i) 𝔸) : exp 𝕂 (block_diagonal' v) = block_diagonal' (exp 𝕂 v) := by simp_rw [exp_eq_tsum, ←block_diagonal'_pow, ←block_diagonal'_smul, ←block_diagonal'_tsum] lemma exp_conj_transpose [star_ring 𝔸] [has_continuous_star 𝔸] (A : matrix m m 𝔸) : exp 𝕂 Aᴴ = (exp 𝕂 A)ᴴ := (star_exp A).symm lemma is_hermitian.exp [star_ring 𝔸] [has_continuous_star 𝔸] {A : matrix m m 𝔸} (h : A.is_hermitian) : (exp 𝕂 A).is_hermitian := (exp_conj_transpose _ _).symm.trans $ congr_arg _ h end ring section comm_ring variables [fintype m] [decidable_eq m] [field 𝕂] [comm_ring 𝔸] [topological_space 𝔸] [topological_ring 𝔸] [algebra 𝕂 𝔸] [t2_space 𝔸] lemma exp_transpose (A : matrix m m 𝔸) : exp 𝕂 Aᵀ = (exp 𝕂 A)ᵀ := by simp_rw [exp_eq_tsum, transpose_tsum, transpose_smul, transpose_pow] lemma is_symm.exp {A : matrix m m 𝔸} (h : A.is_symm) : (exp 𝕂 A).is_symm := (exp_transpose _ _).symm.trans $ congr_arg _ h end comm_ring end topological section normed variables [is_R_or_C 𝕂] [fintype m] [decidable_eq m] [fintype n] [decidable_eq n] [Π i, fintype (n' i)] [Π i, decidable_eq (n' i)] [normed_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸] lemma exp_add_of_commute (A B : matrix m m 𝔸) (h : commute A B) : exp 𝕂 (A + B) = exp 𝕂 A ⬝ exp 𝕂 B := begin letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring, letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring, letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra, exact exp_add_of_commute h, end lemma exp_sum_of_commute {ι} (s : finset ι) (f : ι → matrix m m 𝔸) (h : (s : set ι).pairwise $ λ i j, commute (f i) (f j)) : exp 𝕂 (∑ i in s, f i) = s.noncomm_prod (λ i, exp 𝕂 (f i)) (λ i hi j hj _, (h.of_refl hi hj).exp 𝕂) := begin letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring, letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring, letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra, exact exp_sum_of_commute s f h, end lemma exp_nsmul (n : ℕ) (A : matrix m m 𝔸) : exp 𝕂 (n • A) = exp 𝕂 A ^ n := begin letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring, letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring, letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra, exact exp_nsmul n A, end lemma is_unit_exp (A : matrix m m 𝔸) : is_unit (exp 𝕂 A) := begin letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring, letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring, letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra, exact is_unit_exp _ A, end lemma exp_units_conj (U : (matrix m m 𝔸)ˣ) (A : matrix m m 𝔸) : exp 𝕂 (↑U ⬝ A ⬝ ↑(U⁻¹) : matrix m m 𝔸) = ↑U ⬝ exp 𝕂 A ⬝ ↑(U⁻¹) := begin letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring, letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring, letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra, exact exp_units_conj _ U A, end lemma exp_units_conj' (U : (matrix m m 𝔸)ˣ) (A : matrix m m 𝔸) : exp 𝕂 (↑(U⁻¹) ⬝ A ⬝ U : matrix m m 𝔸) = ↑(U⁻¹) ⬝ exp 𝕂 A ⬝ U := exp_units_conj 𝕂 U⁻¹ A end normed section normed_comm variables [is_R_or_C 𝕂] [fintype m] [decidable_eq m] [fintype n] [decidable_eq n] [Π i, fintype (n' i)] [Π i, decidable_eq (n' i)] [normed_comm_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸] lemma exp_neg (A : matrix m m 𝔸) : exp 𝕂 (-A) = (exp 𝕂 A)⁻¹ := begin rw nonsing_inv_eq_ring_inverse, letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring, letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring, letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra, exact (ring.inverse_exp _ A).symm, end lemma exp_zsmul (z : ℤ) (A : matrix m m 𝔸) : exp 𝕂 (z • A) = exp 𝕂 A ^ z := begin obtain ⟨n, rfl | rfl⟩ := z.eq_coe_or_neg, { rw [zpow_coe_nat, coe_nat_zsmul, exp_nsmul] }, { have : is_unit (exp 𝕂 A).det := (matrix.is_unit_iff_is_unit_det _).mp (is_unit_exp _ _), rw [matrix.zpow_neg this, zpow_coe_nat, neg_smul, exp_neg, coe_nat_zsmul, exp_nsmul] }, end lemma exp_conj (U : matrix m m 𝔸) (A : matrix m m 𝔸) (hy : is_unit U) : exp 𝕂 (U ⬝ A ⬝ U⁻¹) = U ⬝ exp 𝕂 A ⬝ U⁻¹ := let ⟨u, hu⟩ := hy in hu ▸ by simpa only [matrix.coe_units_inv] using exp_units_conj 𝕂 u A lemma exp_conj' (U : matrix m m 𝔸) (A : matrix m m 𝔸) (hy : is_unit U) : exp 𝕂 (U⁻¹ ⬝ A ⬝ U) = U⁻¹ ⬝ exp 𝕂 A ⬝ U := let ⟨u, hu⟩ := hy in hu ▸ by simpa only [matrix.coe_units_inv] using exp_units_conj' 𝕂 u A end normed_comm end matrix
43743bfb493e14b581edaa5bd7d376c7f1dda69e
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/def14.lean
a774be56ce890e79e6ea020ac9021c3faeb7f676
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
395
lean
new_frontend inductive Formula | eqf : Nat → Nat → Formula | impf : Formula → Formula → Formula def Formula.denote : Formula → Prop | eqf n1 n2 => n1 = n2 | impf f1 f2 => denote f1 → denote f2 theorem Formula.denote_eqf (n1 n2 : Nat) : denote (eqf n1 n2) = (n1 = n2) := rfl theorem Formula.denote_impf (f1 f2 : Formula) : denote (impf f1 f2) = (denote f1 → denote f2) := rfl
e29d2624dba350835597d82db8e892911e58b99a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/set_theory/ordinal/natural_ops.lean
38f6a566ec06e29394eb84ea0f8c28a2dd8ce9d4
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
26,219
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import set_theory.ordinal.arithmetic import tactic.abel /-! # Natural operations on ordinals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The goal of this file is to define natural addition and multiplication on ordinals, also known as the Hessenberg sum and product, and provide a basic API. The natural addition of two ordinals `a ♯ b` is recursively defined as the least ordinal greater than `a' ♯ b` and `a ♯ b'` for `a' < a` and `b' < b`. The natural multiplication `a ⨳ b` is likewise recursively defined as the least ordinal such that `a ⨳ b ♯ a' ⨳ b'` is greater than `a' ⨳ b ♯ a ⨳ b'` for any `a' < a` and `b' < b`. These operations form a rich algebraic structure: they're commutative, associative, preserve order, have the usual `0` and `1` from ordinals, and distribute over one another. Moreover, these operations are the addition and multiplication of ordinals when viewed as combinatorial `game`s. This makes them particularly useful for game theory. Finally, both operations admit simple, intuitive descriptions in terms of the Cantor normal form. The natural addition of two ordinals corresponds to adding their Cantor normal forms as if they were polynomials in `ω`. Likewise, their natural multiplication corresponds to multiplying the Cantor normal forms as polynomials. # Implementation notes Given the rich algebraic structure of these two operations, we choose to create a type synonym `nat_ordinal`, where we provide the appropriate instances. However, to avoid casting back and forth between both types, we attempt to prove and state most results on `ordinal`. # Todo - Prove the characterizations of natural addition and multiplication in terms of the Cantor normal form. -/ universes u v open function order noncomputable theory /-! ### Basic casts between `ordinal` and `nat_ordinal` -/ /-- A type synonym for ordinals with natural addition and multiplication. -/ @[derive [has_zero, inhabited, has_one, linear_order, succ_order, has_well_founded]] def nat_ordinal : Type* := ordinal /-- The identity function between `ordinal` and `nat_ordinal`. -/ @[pattern] def ordinal.to_nat_ordinal : ordinal ≃o nat_ordinal := order_iso.refl _ /-- The identity function between `nat_ordinal` and `ordinal`. -/ @[pattern] def nat_ordinal.to_ordinal : nat_ordinal ≃o ordinal := order_iso.refl _ namespace nat_ordinal open ordinal variables {a b c : nat_ordinal.{u}} @[simp] theorem to_ordinal_symm_eq : nat_ordinal.to_ordinal.symm = ordinal.to_nat_ordinal := rfl @[simp] theorem to_ordinal_to_nat_ordinal (a : nat_ordinal) : a.to_ordinal.to_nat_ordinal = a := rfl theorem lt_wf : @well_founded nat_ordinal (<) := ordinal.lt_wf instance : well_founded_lt nat_ordinal := ordinal.well_founded_lt instance : is_well_order nat_ordinal (<) := ordinal.has_lt.lt.is_well_order @[simp] theorem to_ordinal_zero : to_ordinal 0 = 0 := rfl @[simp] theorem to_ordinal_one : to_ordinal 1 = 1 := rfl @[simp] theorem to_ordinal_eq_zero (a) : to_ordinal a = 0 ↔ a = 0 := iff.rfl @[simp] theorem to_ordinal_eq_one (a) : to_ordinal a = 1 ↔ a = 1 := iff.rfl @[simp] theorem to_ordinal_max : (max a b).to_ordinal = max a.to_ordinal b.to_ordinal := rfl @[simp] theorem to_ordinal_min : (min a b).to_ordinal = min a.to_ordinal b.to_ordinal := rfl theorem succ_def (a : nat_ordinal) : succ a = (a.to_ordinal + 1).to_nat_ordinal := rfl /-- A recursor for `nat_ordinal`. Use as `induction x using nat_ordinal.rec`. -/ protected def rec {β : nat_ordinal → Sort*} (h : Π a, β (to_nat_ordinal a)) : Π a, β a := λ a, h a.to_ordinal /-- `ordinal.induction` but for `nat_ordinal`. -/ theorem induction {p : nat_ordinal → Prop} : ∀ i (h : ∀ j, (∀ k, k < j → p k) → p j), p i := ordinal.induction end nat_ordinal namespace ordinal @[simp] theorem to_nat_ordinal_symm_eq : to_nat_ordinal.symm = nat_ordinal.to_ordinal := rfl @[simp] theorem to_nat_ordinal_to_ordinal (a : ordinal) : a.to_nat_ordinal.to_ordinal = a := rfl @[simp] theorem to_nat_ordinal_zero : to_nat_ordinal 0 = 0 := rfl @[simp] theorem to_nat_ordinal_one : to_nat_ordinal 1 = 1 := rfl @[simp] theorem to_nat_ordinal_eq_zero (a) : to_nat_ordinal a = 0 ↔ a = 0 := iff.rfl @[simp] theorem to_nat_ordinal_eq_one (a) : to_nat_ordinal a = 1 ↔ a = 1 := iff.rfl @[simp] theorem to_nat_ordinal_max (a b : ordinal) : to_nat_ordinal (max a b) = max a.to_nat_ordinal b.to_nat_ordinal := rfl @[simp] theorem to_nat_ordinal_min (a b : ordinal) : (linear_order.min a b).to_nat_ordinal = linear_order.min a.to_nat_ordinal b.to_nat_ordinal := rfl /-! We place the definitions of `nadd` and `nmul` before actually developing their API, as this guarantees we only need to open the `natural_ops` locale once. -/ /-- Natural addition on ordinals `a ♯ b`, also known as the Hessenberg sum, is recursively defined as the least ordinal greater than `a' ♯ b` and `a ♯ b'` for all `a' < a` and `b' < b`. In contrast to normal ordinal addition, it is commutative. Natural addition can equivalently be characterized as the ordinal resulting from adding up corresponding coefficients in the Cantor normal forms of `a` and `b`. -/ noncomputable def nadd : ordinal → ordinal → ordinal | a b := max (blsub.{u u} a $ λ a' h, nadd a' b) (blsub.{u u} b $ λ b' h, nadd a b') using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } localized "infix (name := ordinal.nadd) ` ♯ `:65 := ordinal.nadd" in natural_ops /-- Natural multiplication on ordinals `a ⨳ b`, also known as the Hessenberg product, is recursively defined as the least ordinal such that `a ⨳ b + a' ⨳ b'` is greater than `a' ⨳ b + a ⨳ b'` for all `a' < a` and `b < b'`. In contrast to normal ordinal multiplication, it is commutative and distributive (over natural addition). Natural multiplication can equivalently be characterized as the ordinal resulting from multiplying the Cantor normal forms of `a` and `b` as if they were polynomials in `ω`. Addition of exponents is done via natural addition. -/ noncomputable def nmul : ordinal.{u} → ordinal.{u} → ordinal.{u} | a b := Inf {c | ∀ (a' < a) (b' < b), nmul a' b ♯ nmul a b' < c ♯ nmul a' b'} using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } localized "infix ` ⨳ `:70 := ordinal.nmul" in natural_ops end ordinal open_locale natural_ops /-! ### Natural addition -/ namespace ordinal variables {a b c : ordinal.{u}} theorem nadd_def (a b : ordinal) : a ♯ b = max (blsub.{u u} a $ λ a' h, a' ♯ b) (blsub.{u u} b $ λ b' h, a ♯ b') := by rw nadd theorem lt_nadd_iff : a < b ♯ c ↔ (∃ b' < b, a ≤ b' ♯ c) ∨ ∃ c' < c, a ≤ b ♯ c' := by { rw nadd_def, simp [lt_blsub_iff] } theorem nadd_le_iff : b ♯ c ≤ a ↔ (∀ b' < b, b' ♯ c < a) ∧ ∀ c' < c, b ♯ c' < a := by { rw nadd_def, simp [blsub_le_iff] } theorem nadd_lt_nadd_left (h : b < c) (a) : a ♯ b < a ♯ c := lt_nadd_iff.2 (or.inr ⟨b, h, le_rfl⟩) theorem nadd_lt_nadd_right (h : b < c) (a) : b ♯ a < c ♯ a := lt_nadd_iff.2 (or.inl ⟨b, h, le_rfl⟩) theorem nadd_le_nadd_left (h : b ≤ c) (a) : a ♯ b ≤ a ♯ c := begin rcases lt_or_eq_of_le h with h | rfl, { exact (nadd_lt_nadd_left h a).le }, { exact le_rfl } end theorem nadd_le_nadd_right (h : b ≤ c) (a) : b ♯ a ≤ c ♯ a := begin rcases lt_or_eq_of_le h with h | rfl, { exact (nadd_lt_nadd_right h a).le }, { exact le_rfl } end variables (a b) theorem nadd_comm : ∀ a b, a ♯ b = b ♯ a | a b := begin rw [nadd_def, nadd_def, max_comm], congr; ext c hc; apply nadd_comm end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } theorem blsub_nadd_of_mono {f : Π c < a ♯ b, ordinal.{max u v}} (hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : blsub _ f = max (blsub.{u v} a (λ a' ha', f (a' ♯ b) $ nadd_lt_nadd_right ha' b)) (blsub.{u v} b (λ b' hb', f (a ♯ b') $ nadd_lt_nadd_left hb' a)) := begin apply (blsub_le_iff.2 (λ i h, _)).antisymm (max_le _ _), { rcases lt_nadd_iff.1 h with ⟨a', ha', hi⟩ | ⟨b', hb', hi⟩, { exact lt_max_of_lt_left ((hf h (nadd_lt_nadd_right ha' b) hi).trans_lt (lt_blsub _ _ _)) }, { exact lt_max_of_lt_right ((hf h (nadd_lt_nadd_left hb' a) hi).trans_lt (lt_blsub _ _ _)) } }, all_goals { apply blsub_le_of_brange_subset.{u u v}, rintro c ⟨d, hd, rfl⟩, apply mem_brange_self } end theorem nadd_assoc : ∀ a b c, a ♯ b ♯ c = a ♯ (b ♯ c) | a b c := begin rw [nadd_def a (b ♯ c), nadd_def, blsub_nadd_of_mono, blsub_nadd_of_mono, max_assoc], { congr; ext d hd; apply nadd_assoc }, { exact λ i j _ _ h, nadd_le_nadd_left h a }, { exact λ i j _ _ h, nadd_le_nadd_right h c } end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } @[simp] theorem nadd_zero : a ♯ 0 = a := begin induction a using ordinal.induction with a IH, rw [nadd_def, blsub_zero, max_zero_right], convert blsub_id a, ext b hb, exact IH _ hb end @[simp] theorem zero_nadd : 0 ♯ a = a := by rw [nadd_comm, nadd_zero] @[simp] theorem nadd_one : a ♯ 1 = succ a := begin induction a using ordinal.induction with a IH, rw [nadd_def, blsub_one, nadd_zero, max_eq_right_iff, blsub_le_iff], intros i hi, rwa [IH i hi, succ_lt_succ_iff] end @[simp] theorem one_nadd : 1 ♯ a = succ a := by rw [nadd_comm, nadd_one] theorem nadd_succ : a ♯ succ b = succ (a ♯ b) := by rw [←nadd_one (a ♯ b), nadd_assoc, nadd_one] theorem succ_nadd : succ a ♯ b = succ (a ♯ b) := by rw [←one_nadd (a ♯ b), ←nadd_assoc, one_nadd] @[simp] theorem nadd_nat (n : ℕ) : a ♯ n = a + n := begin induction n with n hn, { simp }, { rw [nat.cast_succ, add_one_eq_succ, nadd_succ, add_succ, hn] } end @[simp] theorem nat_nadd (n : ℕ) : ↑n ♯ a = a + n := by rw [nadd_comm, nadd_nat] theorem add_le_nadd : a + b ≤ a ♯ b := begin apply b.limit_rec_on, { simp }, { intros c h, rwa [add_succ, nadd_succ, succ_le_succ_iff] }, { intros c hc H, rw [←is_normal.blsub_eq.{u u} (add_is_normal a) hc, blsub_le_iff], exact λ i hi, (H i hi).trans_lt (nadd_lt_nadd_left hi a) } end end ordinal namespace nat_ordinal open ordinal instance : has_add nat_ordinal := ⟨nadd⟩ instance add_covariant_class_lt : covariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (<) := ⟨λ a b c h, nadd_lt_nadd_left h a⟩ instance add_covariant_class_le : covariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (≤) := ⟨λ a b c h, nadd_le_nadd_left h a⟩ instance add_contravariant_class_le : contravariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (≤) := ⟨λ a b c h, by { by_contra' h', exact h.not_lt (add_lt_add_left h' a) }⟩ instance : ordered_cancel_add_comm_monoid nat_ordinal := { add := (+), add_assoc := nadd_assoc, add_le_add_left := λ a b, add_le_add_left, le_of_add_le_add_left := λ a b c, le_of_add_le_add_left, zero := 0, zero_add := zero_nadd, add_zero := nadd_zero, add_comm := nadd_comm, ..nat_ordinal.linear_order } instance : add_monoid_with_one nat_ordinal := add_monoid_with_one.unary @[simp] theorem add_one_eq_succ : ∀ a : nat_ordinal, a + 1 = succ a := nadd_one @[simp] theorem to_ordinal_cast_nat (n : ℕ) : to_ordinal n = n := begin induction n with n hn, { refl }, { change to_ordinal n ♯ 1 = n + 1, rw hn, exact nadd_one n } end end nat_ordinal namespace ordinal theorem nadd_eq_add (a b : ordinal) : a ♯ b = (a.to_nat_ordinal + b.to_nat_ordinal).to_ordinal := rfl @[simp] theorem to_nat_ordinal_cast_nat (n : ℕ) : to_nat_ordinal n = n := by { rw ←nat_ordinal.to_ordinal_cast_nat n, refl } theorem lt_of_nadd_lt_nadd_left : ∀ {a b c}, a ♯ b < a ♯ c → b < c := @lt_of_add_lt_add_left nat_ordinal _ _ _ theorem lt_of_nadd_lt_nadd_right : ∀ {a b c}, b ♯ a < c ♯ a → b < c := @_root_.lt_of_add_lt_add_right nat_ordinal _ _ _ theorem le_of_nadd_le_nadd_left : ∀ {a b c}, a ♯ b ≤ a ♯ c → b ≤ c := @le_of_add_le_add_left nat_ordinal _ _ _ theorem le_of_nadd_le_nadd_right : ∀ {a b c}, b ♯ a ≤ c ♯ a → b ≤ c := @le_of_add_le_add_right nat_ordinal _ _ _ theorem nadd_lt_nadd_iff_left : ∀ a {b c}, a ♯ b < a ♯ c ↔ b < c := @add_lt_add_iff_left nat_ordinal _ _ _ _ theorem nadd_lt_nadd_iff_right : ∀ a {b c}, b ♯ a < c ♯ a ↔ b < c := @add_lt_add_iff_right nat_ordinal _ _ _ _ theorem nadd_le_nadd_iff_left : ∀ a {b c}, a ♯ b ≤ a ♯ c ↔ b ≤ c := @add_le_add_iff_left nat_ordinal _ _ _ _ theorem nadd_le_nadd_iff_right : ∀ a {b c}, b ♯ a ≤ c ♯ a ↔ b ≤ c := @_root_.add_le_add_iff_right nat_ordinal _ _ _ _ theorem nadd_le_nadd : ∀ {a b c d}, a ≤ b → c ≤ d → a ♯ c ≤ b ♯ d := @add_le_add nat_ordinal _ _ _ _ theorem nadd_lt_nadd : ∀ {a b c d}, a < b → c < d → a ♯ c < b ♯ d := @add_lt_add nat_ordinal _ _ _ _ theorem nadd_lt_nadd_of_lt_of_le : ∀ {a b c d}, a < b → c ≤ d → a ♯ c < b ♯ d := @add_lt_add_of_lt_of_le nat_ordinal _ _ _ _ theorem nadd_lt_nadd_of_le_of_lt : ∀ {a b c d}, a ≤ b → c < d → a ♯ c < b ♯ d := @add_lt_add_of_le_of_lt nat_ordinal _ _ _ _ theorem nadd_left_cancel : ∀ {a b c}, a ♯ b = a ♯ c → b = c := @_root_.add_left_cancel nat_ordinal _ _ theorem nadd_right_cancel : ∀ {a b c}, a ♯ b = c ♯ b → a = c := @_root_.add_right_cancel nat_ordinal _ _ theorem nadd_left_cancel_iff : ∀ {a b c}, a ♯ b = a ♯ c ↔ b = c := @add_left_cancel_iff nat_ordinal _ _ theorem nadd_right_cancel_iff : ∀ {a b c}, b ♯ a = c ♯ a ↔ b = c := @add_right_cancel_iff nat_ordinal _ _ theorem le_nadd_self {a b} : a ≤ b ♯ a := by simpa using nadd_le_nadd_right (ordinal.zero_le b) a theorem le_nadd_left {a b c} (h : a ≤ c) : a ≤ b ♯ c := le_nadd_self.trans (nadd_le_nadd_left h b) theorem le_self_nadd {a b} : a ≤ a ♯ b := by simpa using nadd_le_nadd_left (ordinal.zero_le b) a theorem le_nadd_right {a b c} (h : a ≤ b) : a ≤ b ♯ c := le_self_nadd.trans (nadd_le_nadd_right h c) theorem nadd_left_comm : ∀ a b c, a ♯ (b ♯ c) = b ♯ (a ♯ c) := @add_left_comm nat_ordinal _ theorem nadd_right_comm : ∀ a b c, a ♯ b ♯ c = a ♯ c ♯ b := @add_right_comm nat_ordinal _ /-! ### Natural multiplication -/ variables {a b c d : ordinal.{u}} theorem nmul_def (a b : ordinal) : a ⨳ b = Inf {c | ∀ (a' < a) (b' < b), a' ⨳ b ♯ a ⨳ b' < c ♯ a' ⨳ b'} := by rw nmul /-- The set in the definition of `nmul` is nonempty. -/ theorem nmul_nonempty (a b : ordinal.{u}) : {c : ordinal.{u} | ∀ (a' < a) (b' < b), a' ⨳ b ♯ a ⨳ b' < c ♯ a' ⨳ b'}.nonempty := ⟨_, λ a' ha b' hb, (lt_blsub₂.{u u u} _ ha hb).trans_le le_self_nadd⟩ theorem nmul_nadd_lt {a' b' : ordinal} (ha : a' < a) (hb : b' < b) : a' ⨳ b ♯ a ⨳ b' < a ⨳ b ♯ a' ⨳ b' := by { rw nmul_def a b, exact Inf_mem (nmul_nonempty a b) a' ha b' hb } theorem nmul_nadd_le {a' b' : ordinal} (ha : a' ≤ a) (hb : b' ≤ b) : a' ⨳ b ♯ a ⨳ b' ≤ a ⨳ b ♯ a' ⨳ b' := begin rcases lt_or_eq_of_le ha with ha | rfl, { rcases lt_or_eq_of_le hb with hb | rfl, { exact (nmul_nadd_lt ha hb).le }, { rw nadd_comm } }, { exact le_rfl } end theorem lt_nmul_iff : c < a ⨳ b ↔ ∃ (a' < a) (b' < b), c ♯ a' ⨳ b' ≤ a' ⨳ b ♯ a ⨳ b' := begin refine ⟨λ h, _, _⟩, { rw nmul at h, simpa using not_mem_of_lt_cInf h ⟨0, λ _ _, bot_le⟩ }, { rintros ⟨a', ha, b', hb, h⟩, have := h.trans_lt (nmul_nadd_lt ha hb), rwa nadd_lt_nadd_iff_right at this } end theorem nmul_le_iff : a ⨳ b ≤ c ↔ ∀ (a' < a) (b' < b), a' ⨳ b ♯ a ⨳ b' < c ♯ a' ⨳ b' := by { rw ←not_iff_not, simp [lt_nmul_iff] } theorem nmul_comm : ∀ (a b), a ⨳ b = b ⨳ a | a b := begin rw [nmul, nmul], congr, ext x, split; intros H c hc d hd, { rw [nadd_comm, ←nmul_comm, ←nmul_comm a, ←nmul_comm d], exact H _ hd _ hc }, { rw [nadd_comm, nmul_comm, nmul_comm c, nmul_comm c], exact H _ hd _ hc } end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } @[simp] theorem nmul_zero (a) : a ⨳ 0 = 0 := by { rw [←ordinal.le_zero, nmul_le_iff], exact λ _ _ a ha, (ordinal.not_lt_zero a ha).elim } @[simp] theorem zero_nmul (a) : 0 ⨳ a = 0 := by rw [nmul_comm, nmul_zero] @[simp] theorem nmul_one : ∀ a, a ⨳ 1 = a | a := begin rw nmul, simp only [lt_one_iff_zero, forall_eq, nmul_zero, nadd_zero], convert cInf_Ici, ext b, refine ⟨λ H, le_of_forall_lt (λ c hc, _), λ ha c hc, _⟩, { simpa only [nmul_one] using H c hc }, { simpa only [nmul_one] using hc.trans_le ha } end using_well_founded { dec_tac := `[assumption] } @[simp] theorem one_nmul (a) : 1 ⨳ a = a := by rw [nmul_comm, nmul_one] theorem nmul_lt_nmul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c ⨳ a < c ⨳ b := lt_nmul_iff.2 ⟨0, h₂, a, h₁, by simp⟩ theorem nmul_lt_nmul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a ⨳ c < b ⨳ c := lt_nmul_iff.2 ⟨a, h₁, 0, h₂, by simp⟩ theorem nmul_le_nmul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c ⨳ a ≤ c ⨳ b := begin rcases lt_or_eq_of_le h₁ with h₁|rfl; rcases lt_or_eq_of_le h₂ with h₂|rfl, { exact (nmul_lt_nmul_of_pos_left h₁ h₂).le }, all_goals { simp } end theorem nmul_le_nmul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a ⨳ c ≤ b ⨳ c := begin rw [nmul_comm, nmul_comm b], exact nmul_le_nmul_of_nonneg_left h₁ h₂ end theorem nmul_nadd : ∀ (a b c), a ⨳ (b ♯ c) = a ⨳ b ♯ a ⨳ c | a b c := begin apply le_antisymm (nmul_le_iff.2 $ λ a' ha d hd, _) (nadd_le_iff.2 ⟨λ d hd, _, λ d hd, _⟩), { rw nmul_nadd, rcases lt_nadd_iff.1 hd with ⟨b', hb, hd⟩ | ⟨c', hc, hd⟩, { have := nadd_lt_nadd_of_lt_of_le (nmul_nadd_lt ha hb) (nmul_nadd_le ha.le hd), rw [nmul_nadd, nmul_nadd] at this, simp only [nadd_assoc] at this, rwa [nadd_left_comm, nadd_left_comm _ (a ⨳ b'), nadd_left_comm (a ⨳ b), nadd_lt_nadd_iff_left, nadd_left_comm (a' ⨳ b), nadd_left_comm (a ⨳ b), nadd_lt_nadd_iff_left, ←nadd_assoc, ←nadd_assoc] at this }, { have := nadd_lt_nadd_of_le_of_lt (nmul_nadd_le ha.le hd) (nmul_nadd_lt ha hc), rw [nmul_nadd, nmul_nadd] at this, simp only [nadd_assoc] at this, rwa [nadd_left_comm, nadd_comm (a ⨳ c), nadd_left_comm (a' ⨳ d), nadd_left_comm (a ⨳ c'), nadd_left_comm (a ⨳ b), nadd_lt_nadd_iff_left, nadd_comm (a' ⨳ c), nadd_left_comm (a ⨳ d), nadd_left_comm (a' ⨳ b), nadd_left_comm (a ⨳ b), nadd_lt_nadd_iff_left, nadd_comm (a ⨳ d), nadd_comm (a' ⨳ d), ←nadd_assoc, ←nadd_assoc] at this } }, { rcases lt_nmul_iff.1 hd with ⟨a', ha, b', hb, hd⟩, have := nadd_lt_nadd_of_le_of_lt hd (nmul_nadd_lt ha (nadd_lt_nadd_right hb c)), rw [nmul_nadd, nmul_nadd, nmul_nadd a'] at this, simp only [nadd_assoc] at this, rwa [nadd_left_comm (a' ⨳ b'), nadd_left_comm, nadd_lt_nadd_iff_left, nadd_left_comm, nadd_left_comm _ (a' ⨳ b'), nadd_left_comm (a ⨳ b'), nadd_lt_nadd_iff_left, nadd_left_comm (a' ⨳ c), nadd_left_comm, nadd_lt_nadd_iff_left, nadd_left_comm, nadd_comm _ (a' ⨳ c), nadd_lt_nadd_iff_left] at this }, { rcases lt_nmul_iff.1 hd with ⟨a', ha, c', hc, hd⟩, have := nadd_lt_nadd_of_lt_of_le (nmul_nadd_lt ha (nadd_lt_nadd_left hc b)) hd, rw [nmul_nadd, nmul_nadd, nmul_nadd a'] at this, simp only [nadd_assoc] at this, rwa [nadd_left_comm _ (a' ⨳ b), nadd_lt_nadd_iff_left, nadd_left_comm (a' ⨳ c'), nadd_left_comm _ (a' ⨳ c), nadd_lt_nadd_iff_left, nadd_left_comm, nadd_comm (a' ⨳ c'), nadd_left_comm _ (a ⨳ c'), nadd_lt_nadd_iff_left, nadd_comm _ (a' ⨳ c'), nadd_comm _ (a' ⨳ c'), nadd_left_comm, nadd_lt_nadd_iff_left] at this } end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } theorem nadd_nmul (a b c) : (a ♯ b) ⨳ c = a ⨳ c ♯ b ⨳ c := by rw [nmul_comm, nmul_nadd, nmul_comm, nmul_comm c] theorem nmul_nadd_lt₃ {a' b' c' : ordinal} (ha : a' < a) (hb : b' < b) (hc : c' < c) : a' ⨳ b ⨳ c ♯ a ⨳ b' ⨳ c ♯ a ⨳ b ⨳ c' ♯ a' ⨳ b' ⨳ c' < a ⨳ b ⨳ c ♯ a' ⨳ b' ⨳ c ♯ a' ⨳ b ⨳ c' ♯ a ⨳ b' ⨳ c' := by simpa only [nadd_nmul, ←nadd_assoc] using nmul_nadd_lt (nmul_nadd_lt ha hb) hc theorem nmul_nadd_le₃ {a' b' c' : ordinal} (ha : a' ≤ a) (hb : b' ≤ b) (hc : c' ≤ c) : a' ⨳ b ⨳ c ♯ a ⨳ b' ⨳ c ♯ a ⨳ b ⨳ c' ♯ a' ⨳ b' ⨳ c' ≤ a ⨳ b ⨳ c ♯ a' ⨳ b' ⨳ c ♯ a' ⨳ b ⨳ c' ♯ a ⨳ b' ⨳ c' := by simpa only [nadd_nmul, ←nadd_assoc] using nmul_nadd_le (nmul_nadd_le ha hb) hc theorem nmul_nadd_lt₃' {a' b' c' : ordinal} (ha : a' < a) (hb : b' < b) (hc : c' < c) : a' ⨳ (b ⨳ c) ♯ a ⨳ (b' ⨳ c) ♯ a ⨳ (b ⨳ c') ♯ a' ⨳ (b' ⨳ c') < a ⨳ (b ⨳ c) ♯ a' ⨳ (b' ⨳ c) ♯ a' ⨳ (b ⨳ c') ♯ a ⨳ (b' ⨳ c') := begin simp only [nmul_comm _ (_ ⨳ _)], convert nmul_nadd_lt₃ hb hc ha using 1; { simp only [nadd_eq_add, nat_ordinal.to_ordinal_to_nat_ordinal], abel } end theorem nmul_nadd_le₃' {a' b' c' : ordinal} (ha : a' ≤ a) (hb : b' ≤ b) (hc : c' ≤ c) : a' ⨳ (b ⨳ c) ♯ a ⨳ (b' ⨳ c) ♯ a ⨳ (b ⨳ c') ♯ a' ⨳ (b' ⨳ c') ≤ a ⨳ (b ⨳ c) ♯ a' ⨳ (b' ⨳ c) ♯ a' ⨳ (b ⨳ c') ♯ a ⨳ (b' ⨳ c') := begin simp only [nmul_comm _ (_ ⨳ _)], convert nmul_nadd_le₃ hb hc ha using 1; { simp only [nadd_eq_add, nat_ordinal.to_ordinal_to_nat_ordinal], abel } end theorem lt_nmul_iff₃ : d < a ⨳ b ⨳ c ↔ ∃ (a' < a) (b' < b) (c' < c), d ♯ a' ⨳ b' ⨳ c ♯ a' ⨳ b ⨳ c' ♯ a ⨳ b' ⨳ c' ≤ a' ⨳ b ⨳ c ♯ a ⨳ b' ⨳ c ♯ a ⨳ b ⨳ c' ♯ a' ⨳ b' ⨳ c' := begin refine ⟨λ h, _, _⟩, { rcases lt_nmul_iff.1 h with ⟨e, he, c', hc, H₁⟩, rcases lt_nmul_iff.1 he with ⟨a', ha, b', hb, H₂⟩, refine ⟨a', ha, b', hb, c', hc, _⟩, have := nadd_le_nadd H₁ (nmul_nadd_le H₂ hc.le), simp only [nadd_nmul, nadd_assoc] at this, rw [nadd_left_comm, nadd_left_comm d, nadd_left_comm, nadd_le_nadd_iff_left, nadd_left_comm (a ⨳ b' ⨳ c), nadd_left_comm (a' ⨳ b ⨳ c), nadd_left_comm (a ⨳ b ⨳ c'), nadd_le_nadd_iff_left, nadd_left_comm (a ⨳ b ⨳ c'), nadd_left_comm (a ⨳ b ⨳ c')] at this, simpa only [nadd_assoc] }, { rintro ⟨a', ha, b', hb, c', hc, h⟩, have := h.trans_lt (nmul_nadd_lt₃ ha hb hc), repeat { rwa nadd_lt_nadd_iff_right at this } } end theorem nmul_le_iff₃ : a ⨳ b ⨳ c ≤ d ↔ ∀ (a' < a) (b' < b) (c' < c), a' ⨳ b ⨳ c ♯ a ⨳ b' ⨳ c ♯ a ⨳ b ⨳ c' ♯ a' ⨳ b' ⨳ c' < d ♯ a' ⨳ b' ⨳ c ♯ a' ⨳ b ⨳ c' ♯ a ⨳ b' ⨳ c' := by { rw ←not_iff_not, simp [lt_nmul_iff₃] } theorem lt_nmul_iff₃' : d < a ⨳ (b ⨳ c) ↔ ∃ (a' < a) (b' < b) (c' < c), d ♯ a' ⨳ (b' ⨳ c) ♯ a' ⨳ (b ⨳ c') ♯ a ⨳ (b' ⨳ c') ≤ a' ⨳ (b ⨳ c) ♯ a ⨳ (b' ⨳ c) ♯ a ⨳ (b ⨳ c') ♯ a' ⨳ (b' ⨳ c') := begin simp only [nmul_comm _ (_ ⨳ _), lt_nmul_iff₃, nadd_eq_add, nat_ordinal.to_ordinal_to_nat_ordinal], split; rintro ⟨b', hb, c', hc, a', ha, h⟩, { use [a', ha, b', hb, c', hc], convert h using 1; abel }, { use [c', hc, a', ha, b', hb], convert h using 1; abel } end theorem nmul_le_iff₃' : a ⨳ (b ⨳ c) ≤ d ↔ ∀ (a' < a) (b' < b) (c' < c), a' ⨳ (b ⨳ c) ♯ a ⨳ (b' ⨳ c) ♯ a ⨳ (b ⨳ c') ♯ a' ⨳ (b' ⨳ c') < d ♯ a' ⨳ (b' ⨳ c) ♯ a' ⨳ (b ⨳ c') ♯ a ⨳ (b' ⨳ c') := by { rw ←not_iff_not, simp [lt_nmul_iff₃'] } theorem nmul_assoc : ∀ a b c, a ⨳ b ⨳ c = a ⨳ (b ⨳ c) | a b c := begin apply le_antisymm, { rw nmul_le_iff₃, intros a' ha b' hb c' hc, repeat { rw nmul_assoc }, exact nmul_nadd_lt₃' ha hb hc }, { rw nmul_le_iff₃', intros a' ha b' hb c' hc, repeat { rw ←nmul_assoc }, exact nmul_nadd_lt₃ ha hb hc }, end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } end ordinal open ordinal instance : has_mul nat_ordinal := ⟨nmul⟩ instance : ordered_comm_semiring nat_ordinal := { mul := (*), left_distrib := nmul_nadd, right_distrib := nadd_nmul, zero_mul := zero_nmul, mul_zero := nmul_zero, mul_assoc := nmul_assoc, one := 1, one_mul := one_nmul, mul_one := nmul_one, mul_comm := nmul_comm, zero_le_one := @zero_le_one ordinal _ _ _ _, mul_le_mul_of_nonneg_left := λ a b c, nmul_le_nmul_of_nonneg_left, mul_le_mul_of_nonneg_right := λ a b c, nmul_le_nmul_of_nonneg_right, ..nat_ordinal.ordered_cancel_add_comm_monoid, ..nat_ordinal.linear_order } namespace ordinal theorem nmul_eq_mul (a b) : a ⨳ b = (a.to_nat_ordinal * b.to_nat_ordinal).to_ordinal := rfl theorem nmul_nadd_one : ∀ a b, a ⨳ (b ♯ 1) = a ⨳ b ♯ a := @mul_add_one nat_ordinal _ _ _ theorem nadd_one_nmul : ∀ a b, (a ♯ 1) ⨳ b = a ⨳ b ♯ b := @add_one_mul nat_ordinal _ _ _ theorem nmul_succ (a b) : a ⨳ succ b = a ⨳ b ♯ a := by rw [←nadd_one, nmul_nadd_one] theorem succ_nmul (a b) : succ a ⨳ b = a ⨳ b ♯ b := by rw [←nadd_one, nadd_one_nmul] theorem nmul_add_one : ∀ a b, a ⨳ (b + 1) = a ⨳ b ♯ a := nmul_succ theorem add_one_nmul : ∀ a b, (a + 1) ⨳ b = a ⨳ b ♯ b := succ_nmul end ordinal namespace nat_ordinal open ordinal theorem mul_le_nmul (a b : ordinal.{u}) : a * b ≤ a ⨳ b := begin apply b.limit_rec_on, { simp }, { intros c h, rw [mul_succ, nmul_succ], exact (add_le_nadd _ a).trans (nadd_le_nadd_right h a) }, { intros c hc H, rcases eq_zero_or_pos a with rfl | ha, { simp }, { rw [←is_normal.blsub_eq.{u u} (mul_is_normal ha) hc, blsub_le_iff], exact λ i hi, (H i hi).trans_lt (nmul_lt_nmul_of_pos_left hi ha) } } end end nat_ordinal
436c40f93ef3c3cb338be66e3906c4b78e851130
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/nat/cast.lean
65d9a50f747a60474b5abde839fa911147d3d72c
[ "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
12,250
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.order.field import data.nat.basic /-! # Cast of naturals This file defines the *canonical* homomorphism from the natural numbers into a type `α` with `0`, `1` and `+` (typically an `add_monoid` with one). ## Main declarations * `cast`: Canonical homomorphism `ℕ → α` where `α` has a `0`, `1` and `+`. * `bin_cast`: Binary representation version of `cast`. * `cast_add_monoid_hom`: `cast` bundled as an `add_monoid_hom`. * `cast_ring_hom`: `cast` bundled as a `ring_hom`. ## Implementation note Setting up the coercions priorities is tricky. See Note [coercion into rings]. -/ namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 /-- Computationally friendlier cast than `nat.cast`, using binary representation. -/ protected def bin_cast (n : ℕ) : α := @nat.binary_rec (λ _, α) 0 (λ odd k a, cond odd (a + a + 1) (a + a)) n /-- Coercions such as `nat.cast_coe` that go from a concrete structure such as `ℕ` to an arbitrary ring `α` should be set up as follows: ```lean @[priority 900] instance : has_coe_t ℕ α := ⟨...⟩ ``` It needs to be `has_coe_t` instead of `has_coe` because otherwise type-class inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`. The reduced priority is necessary so that it doesn't conflict with instances such as `has_coe_t α (option α)`. For this to work, we reduce the priority of the `coe_base` and `coe_trans` instances because we want the instances for `has_coe_t` to be tried in the following order: 1. `has_coe_t` instances declared in mathlib (such as `has_coe_t α (with_top α)`, etc.) 2. `coe_base`, which contains instances such as `has_coe (fin n) n` 3. `nat.cast_coe : has_coe_t ℕ α` etc. 4. `coe_trans` If `coe_trans` is tried first, then `nat.cast_coe` doesn't get a chance to apply. -/ library_note "coercion into rings" attribute [instance, priority 950] coe_base attribute [instance, priority 500] coe_trans -- see note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℕ α := ⟨nat.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp, norm_cast, priority 500] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl @[simp, norm_cast] theorem cast_ite (P : Prop) [decidable P] (m n : ℕ) : (((ite P m n) : ℕ) : α) = ite P (m : α) (n : α) := by { split_ifs; refl, } end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] @[simp] lemma bin_cast_eq [add_monoid α] [has_one α] (n : ℕ) : (nat.bin_cast n : α) = ((n : ℕ) : α) := begin rw nat.bin_cast, apply binary_rec _ _ n, { rw [binary_rec_zero, cast_zero] }, { intros b k h, rw [binary_rec_eq, h], { cases b; simp [bit, bit0, bit1] }, { simp } }, end /-- `coe : ℕ → α` as an `add_monoid_hom`. -/ def cast_add_monoid_hom (α : Type*) [add_monoid α] [has_one α] : ℕ →+ α := { to_fun := coe, map_add' := cast_add, map_zero' := cast_zero } @[simp] lemma coe_cast_add_monoid_hom [add_monoid α] [has_one α] : (cast_add_monoid_hom α : ℕ → α) = coe := rfl @[simp, norm_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [add_monoid α] [has_one α] : ((2 : ℕ) : α) = 2 := by simp @[simp, norm_cast] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, 0 < n → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp, norm_cast] theorem cast_mul [non_assoc_semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] @[simp] theorem cast_dvd {α : Type*} [field α] {m n : ℕ} (n_dvd : n ∣ m) (n_nonzero : (n:α) ≠ 0) : ((m / n : ℕ) : α) = m / n := begin rcases n_dvd with ⟨k, rfl⟩, have : n ≠ 0, {rintro rfl, simpa using n_nonzero}, rw nat.mul_div_cancel_left _ (pos_iff_ne_zero.2 this), rw [nat.cast_mul, mul_div_cancel_left _ n_nonzero], end /-- `coe : ℕ → α` as a `ring_hom` -/ def cast_ring_hom (α : Type*) [non_assoc_semiring α] : ℕ →+* α := { to_fun := coe, map_one' := cast_one, map_mul' := cast_mul, .. cast_add_monoid_hom α } @[simp] lemma coe_cast_ring_hom [non_assoc_semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl lemma cast_commute [non_assoc_semiring α] (n : ℕ) (x : α) : commute ↑n x := nat.rec_on n (commute.zero_left x) $ λ n ihn, ihn.add_left $ commute.one_left x lemma cast_comm [non_assoc_semiring α] (n : ℕ) (x : α) : (n : α) * x = x * n := (cast_commute n x).eq lemma commute_cast [semiring α] (x : α) (n : ℕ) : commute x n := (n.cast_commute x).symm section variables [ordered_semiring α] @[simp] theorem cast_nonneg : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[mono] theorem mono_cast : monotone (coe : ℕ → α) := λ m n h, let ⟨k, hk⟩ := le_iff_exists_add.1 h in by simp [hk] variable [nontrivial α] theorem strict_mono_cast : strict_mono (coe : ℕ → α) := λ m n h, nat.le_induction (lt_add_of_pos_right _ zero_lt_one) (λ n _ h, lt_add_of_lt_of_pos h zero_lt_one) _ h @[simp, norm_cast] theorem cast_le {m n : ℕ} : (m : α) ≤ n ↔ m ≤ n := strict_mono_cast.le_iff_le @[simp, norm_cast, mono] theorem cast_lt {m n : ℕ} : (m : α) < n ↔ m < n := strict_mono_cast.lt_iff_lt @[simp] theorem cast_pos {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] lemma cast_add_one_pos (n : ℕ) : 0 < (n : α) + 1 := add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one @[simp, norm_cast] theorem one_lt_cast {n : ℕ} : 1 < (n : α) ↔ 1 < n := by rw [← cast_one, cast_lt] @[simp, norm_cast] theorem one_le_cast {n : ℕ} : 1 ≤ (n : α) ↔ 1 ≤ n := by rw [← cast_one, cast_le] @[simp, norm_cast] theorem cast_lt_one {n : ℕ} : (n : α) < 1 ↔ n = 0 := by rw [← cast_one, cast_lt, lt_succ_iff, le_zero_iff] @[simp, norm_cast] theorem cast_le_one {n : ℕ} : (n : α) ≤ 1 ↔ n ≤ 1 := by rw [← cast_one, cast_le] end @[simp, norm_cast] theorem cast_min [linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := (@mono_cast α _).map_min @[simp, norm_cast] theorem cast_max [linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := (@mono_cast α _).map_max @[simp, norm_cast] theorem abs_cast [linear_ordered_ring α] (a : ℕ) : |(a : α)| = a := abs_of_nonneg (cast_nonneg a) lemma coe_nat_dvd [comm_semiring α] {m n : ℕ} (h : m ∣ n) : (m : α) ∣ (n : α) := ring_hom.map_dvd (nat.cast_ring_hom α) h alias coe_nat_dvd ← has_dvd.dvd.nat_cast section linear_ordered_field variables [linear_ordered_field α] lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ := inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) := by { rw one_div, exact inv_pos_of_nat } lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) := by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa } lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) := by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa } end linear_ordered_field end nat namespace prod variables {α : Type*} {β : Type*} [has_zero α] [has_one α] [has_add α] [has_zero β] [has_one β] [has_add β] @[simp] lemma fst_nat_cast (n : ℕ) : (n : α × β).fst = n := by induction n; simp * @[simp] lemma snd_nat_cast (n : ℕ) : (n : α × β).snd = n := by induction n; simp * end prod namespace add_monoid_hom variables {A B : Type*} [add_monoid A] @[ext] lemma ext_nat {f g : ℕ →+ A} (h : f 1 = g 1) : f = g := ext $ λ n, nat.rec_on n (f.map_zero.trans g.map_zero.symm) $ λ n ihn, by simp only [nat.succ_eq_add_one, *, map_add] variables [has_one A] [add_monoid B] [has_one B] lemma eq_nat_cast (f : ℕ →+ A) (h1 : f 1 = 1) : ∀ n : ℕ, f n = n := congr_fun $ show f = nat.cast_add_monoid_hom A, from ext_nat (h1.trans nat.cast_one.symm) lemma map_nat_cast (f : A →+ B) (h1 : f 1 = 1) (n : ℕ) : f n = n := (f.comp (nat.cast_add_monoid_hom A)).eq_nat_cast (by simp [h1]) _ end add_monoid_hom namespace monoid_with_zero_hom variables {A : Type*} [monoid_with_zero A] /-- If two `monoid_with_zero_hom`s agree on the positive naturals they are equal. -/ @[ext] theorem ext_nat {f g : monoid_with_zero_hom ℕ A} (h_pos : ∀ {n : ℕ}, 0 < n → f n = g n) : f = g := begin ext (_ | n), { rw [f.map_zero, g.map_zero] }, { exact h_pos n.zero_lt_succ, }, end end monoid_with_zero_hom namespace ring_hom variables {R : Type*} {S : Type*} [non_assoc_semiring R] [non_assoc_semiring S] @[simp] lemma eq_nat_cast (f : ℕ →+* R) (n : ℕ) : f n = n := f.to_add_monoid_hom.eq_nat_cast f.map_one n @[simp] lemma map_nat_cast (f : R →+* S) (n : ℕ) : f n = n := (f.comp (nat.cast_ring_hom R)).eq_nat_cast n lemma ext_nat (f g : ℕ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_nat $ f.map_one.trans g.map_one.symm end ring_hom @[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n := ((ring_hom.id ℕ).eq_nat_cast n).symm @[simp] theorem nat.cast_with_bot : ∀ (n : ℕ), @coe ℕ (with_bot ℕ) (@coe_to_lift _ _ nat.cast_coe) n = n | 0 := rfl | (n+1) := by rw [with_bot.coe_add, nat.cast_add, nat.cast_with_bot n]; refl instance nat.subsingleton_ring_hom {R : Type*} [non_assoc_semiring R] : subsingleton (ℕ →+* R) := ⟨ring_hom.ext_nat⟩ namespace with_top variables {α : Type*} variables [has_zero α] [has_one α] [has_add α] @[simp, norm_cast] lemma coe_nat : ∀(n : nat), ((n : α) : with_top α) = n | 0 := rfl | (n+1) := by { push_cast, rw [coe_nat n] } @[simp] lemma nat_ne_top (n : nat) : (n : with_top α) ≠ ⊤ := by { rw [←coe_nat n], apply coe_ne_top } @[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n := by { rw [←coe_nat n], apply top_ne_coe } lemma add_one_le_of_lt {i n : with_top ℕ} (h : i < n) : i + 1 ≤ n := begin cases n, { exact le_top }, cases i, { exact (not_le_of_lt h le_top).elim }, exact with_top.coe_le_coe.2 (with_top.coe_lt_coe.1 h) end lemma one_le_iff_pos {n : with_top ℕ} : 1 ≤ n ↔ 0 < n := ⟨λ h, (coe_lt_coe.2 zero_lt_one).trans_le h, λ h, by simpa only [zero_add] using add_one_le_of_lt h⟩ @[elab_as_eliminator] lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ) (h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a := begin have A : ∀n:ℕ, P n := λ n, nat.rec_on n h0 hsuc, cases a, { exact htop A }, { exact A a } end end with_top namespace pi variables {α β : Type*} lemma nat_apply [has_zero β] [has_one β] [has_add β] : ∀ (n : ℕ) (a : α), (n : α → β) a = n | 0 a := rfl | (n+1) a := by rw [nat.cast_succ, nat.cast_succ, add_apply, nat_apply, one_apply] @[simp] lemma coe_nat [has_zero β] [has_one β] [has_add β] (n : ℕ) : (n : α → β) = λ _, n := by { ext, rw pi.nat_apply } end pi
b856fd1c16a06e4edb9b82ec3b24b3168c0ca1bd
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Util.lean
cb67fb422d202f479256ad7a8a3a883c6f1bb7e0
[ "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
762
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.FindLevelMVar import Lean.Util.MonadCache import Lean.Util.PPExt import Lean.Util.Path import Lean.Util.Profile import Lean.Util.RecDepth import Lean.Util.ShareCommon 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.SCC import Lean.Util.OccursCheck import Lean.Util.Paths import Lean.Util.HasConstCache
5a23e24ae0480b19882d1dcc3ff5e472ec12f7ff
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Group/equivalence_Group_AddGroup.lean
036c5d21709929330cc160d890d213a36794662d
[ "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
2,786
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebra.category.Group.basic import algebra.hom.equiv.type_tags /-! # Equivalence between `Group` and `AddGroup` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains two equivalences: * `Group_AddGroup_equivalence` : the equivalence between `Group` and `AddGroup` by sending `X : Group` to `additive X` and `Y : AddGroup` to `multiplicative Y`. * `CommGroup_AddCommGroup_equivalence` : the equivalence between `CommGroup` and `AddCommGroup` by sending `X : CommGroup` to `additive X` and `Y : AddCommGroup` to `multiplicative Y`. -/ open category_theory namespace Group /-- The functor `Group ⥤ AddGroup` by sending `X ↦ additive X` and `f ↦ f`. -/ @[simps] def to_AddGroup : Group ⥤ AddGroup := { obj := λ X, AddGroup.of (additive X), map := λ X Y, monoid_hom.to_additive } end Group namespace CommGroup /-- The functor `CommGroup ⥤ AddCommGroup` by sending `X ↦ additive X` and `f ↦ f`. -/ @[simps] def to_AddCommGroup : CommGroup ⥤ AddCommGroup := { obj := λ X, AddCommGroup.of (additive X), map := λ X Y, monoid_hom.to_additive } end CommGroup namespace AddGroup /-- The functor `AddGroup ⥤ Group` by sending `X ↦ multiplicative Y` and `f ↦ f`. -/ @[simps] def to_Group : AddGroup ⥤ Group := { obj := λ X, Group.of (multiplicative X), map := λ X Y, add_monoid_hom.to_multiplicative } end AddGroup namespace AddCommGroup /-- The functor `AddCommGroup ⥤ CommGroup` by sending `X ↦ multiplicative Y` and `f ↦ f`. -/ @[simps] def to_CommGroup : AddCommGroup ⥤ CommGroup := { obj := λ X, CommGroup.of (multiplicative X), map := λ X Y, add_monoid_hom.to_multiplicative } end AddCommGroup /-- The equivalence of categories between `Group` and `AddGroup` -/ @[simps] def Group_AddGroup_equivalence : Group ≌ AddGroup := equivalence.mk Group.to_AddGroup AddGroup.to_Group (nat_iso.of_components (λ X, mul_equiv.to_Group_iso (mul_equiv.multiplicative_additive X)) (λ X Y f, rfl)) (nat_iso.of_components (λ X, add_equiv.to_AddGroup_iso (add_equiv.additive_multiplicative X)) (λ X Y f, rfl)) /-- The equivalence of categories between `CommGroup` and `AddCommGroup`. -/ @[simps] def CommGroup_AddCommGroup_equivalence : CommGroup ≌ AddCommGroup := equivalence.mk CommGroup.to_AddCommGroup AddCommGroup.to_CommGroup (nat_iso.of_components (λ X, mul_equiv.to_CommGroup_iso (mul_equiv.multiplicative_additive X)) (λ X Y f, rfl)) (nat_iso.of_components (λ X, add_equiv.to_AddCommGroup_iso (add_equiv.additive_multiplicative X)) (λ X Y f, rfl))
3289b64f13ac0731868ad403252f19060a63d303
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/linear_algebra/linear_pmap.lean
a871763ff770f9e64fb339cb06d793f3e4035c26
[ "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
15,693
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import linear_algebra.basic /-! # Partially defined linear maps A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. We define a `semilattice_inf_bot` instance on this this, and define three operations: * `mk_span_singleton` defines a partial linear map defined on the span of a singleton. * `sup` takes two partial linear maps `f`, `g` that agree on the intersection of their domains, and returns the unique partial linear map on `f.domain ⊔ g.domain` that extends both `f` and `g`. * `Sup` takes a `directed_on (≤)` set of partial linear maps, and returns the unique partial linear map on the `Sup` of their domains that extends all these maps. Partially defined maps are currently used in `mathlib` to prove Hahn-Banach theorem and its variations. Namely, `linear_pmap.Sup` implies that every chain of `linear_pmap`s is bounded above. Another possible use (not yet in `mathlib`) would be the theory of unbounded linear operators. -/ lemma subtype.coe_prop {α : Type*} {p : α → Prop} (x : subtype p) : p x := x.2 open set universes u v w /-- A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. -/ structure linear_pmap (R : Type u) [ring R] (E : Type v) [add_comm_group E] [module R E] (F : Type w) [add_comm_group F] [module R F] := (domain : submodule R E) (to_fun : domain →ₗ[R] F) variables {R : Type*} [ring R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] {G : Type*} [add_comm_group G] [module R G] namespace linear_pmap open submodule instance : has_coe_to_fun (linear_pmap R E F) := ⟨λ f : linear_pmap R E F, f.domain → F, λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : linear_pmap R E F) (x : f.domain) : f.to_fun x = f x := rfl @[simp] lemma map_zero (f : linear_pmap R E F) : f 0 = 0 := f.to_fun.map_zero lemma map_add (f : linear_pmap R E F) (x y : f.domain) : f (x + y) = f x + f y := f.to_fun.map_add x y lemma map_neg (f : linear_pmap R E F) (x : f.domain) : f (-x) = -f x := f.to_fun.map_neg x lemma map_sub (f : linear_pmap R E F) (x y : f.domain) : f (x - y) = f x - f y := f.to_fun.map_sub x y lemma map_smul (f : linear_pmap R E F) (c : R) (x : f.domain) : f (c • x) = c • f x := f.to_fun.map_smul c x @[simp] lemma mk_apply (p : submodule R E) (f : p →ₗ[R] F) (x : p) : mk p f x = f x := rfl /-- The unique `linear_pmap` on `span R {x}` that sends `x` to `y`. This version works for modules over rings, and requires a proof of `∀ c, c • x = 0 → c • y = 0`. -/ noncomputable def mk_span_singleton' (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) : linear_pmap R E F := begin replace H : ∀ c₁ c₂ : R, c₁ • x = c₂ • x → c₁ • y = c₂ • y, { intros c₁ c₂ h, rw [← sub_eq_zero, ← sub_smul] at h ⊢, exact H _ h }, refine ⟨span R {x}, λ z, _, _, _⟩, { exact (classical.some (mem_span_singleton.1 z.coe_prop) • y) }, { intros z₁ z₂, rw [← add_smul], apply H, simp only [add_smul, sub_smul, classical.some_spec (mem_span_singleton.1 _)], apply coe_add }, { intros c z, rw [smul_smul], apply H, simp only [mul_smul, classical.some_spec (mem_span_singleton.1 _)], apply coe_smul } end @[simp] lemma domain_mk_span_singleton (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) : (mk_span_singleton' x y H).domain = span R {x} := rfl @[simp] lemma mk_span_singleton_apply (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) (c : R) (h) : mk_span_singleton' x y H ⟨c • x, h⟩ = c • y := begin dsimp [mk_span_singleton'], rw [← sub_eq_zero, ← sub_smul], apply H, simp only [sub_smul, one_smul, sub_eq_zero], apply classical.some_spec (mem_span_singleton.1 h), end /-- The unique `linear_pmap` on `span R {x}` that sends a non-zero vector `x` to `y`. This version works for modules over division rings. -/ @[reducible] noncomputable def mk_span_singleton {K E F : Type*} [division_ring K] [add_comm_group E] [module K E] [add_comm_group F] [module K F] (x : E) (y : F) (hx : x ≠ 0) : linear_pmap K E F := mk_span_singleton' x y $ λ c hc, (smul_eq_zero.1 hc).elim (λ hc, by rw [hc, zero_smul]) (λ hx', absurd hx' hx) /-- Projection to the first coordinate as a `linear_pmap` -/ protected def fst (p : submodule R E) (p' : submodule R F) : linear_pmap R (E × F) E := { domain := p.prod p', to_fun := (linear_map.fst R E F).comp (p.prod p').subtype } @[simp] lemma fst_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') : linear_pmap.fst p p' x = (x : E × F).1 := rfl /-- Projection to the second coordinate as a `linear_pmap` -/ protected def snd (p : submodule R E) (p' : submodule R F) : linear_pmap R (E × F) F := { domain := p.prod p', to_fun := (linear_map.snd R E F).comp (p.prod p').subtype } @[simp] lemma snd_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') : linear_pmap.snd p p' x = (x : E × F).2 := rfl instance : has_neg (linear_pmap R E F) := ⟨λ f, ⟨f.domain, -f.to_fun⟩⟩ @[simp] lemma neg_apply (f : linear_pmap R E F) (x) : (-f) x = -(f x) := rfl instance : has_le (linear_pmap R E F) := ⟨λ f g, f.domain ≤ g.domain ∧ ∀ ⦃x : f.domain⦄ ⦃y : g.domain⦄ (h : (x:E) = y), f x = g y⟩ lemma eq_of_le_of_domain_eq {f g : linear_pmap R E F} (hle : f ≤ g) (heq : f.domain = g.domain) : f = g := begin rcases f with ⟨f_dom, f⟩, rcases g with ⟨g_dom, g⟩, change f_dom = g_dom at heq, subst g_dom, have : f = g, from linear_map.ext (λ x, hle.2 rfl), subst g end /-- Given two partial linear maps `f`, `g`, the set of points `x` such that both `f` and `g` are defined at `x` and `f x = g x` form a submodule. -/ def eq_locus (f g : linear_pmap R E F) : submodule R E := { carrier := {x | ∃ (hf : x ∈ f.domain) (hg : x ∈ g.domain), f ⟨x, hf⟩ = g ⟨x, hg⟩}, zero := ⟨zero_mem _, zero_mem _, f.map_zero.trans g.map_zero.symm⟩, add := λ x y ⟨hfx, hgx, hx⟩ ⟨hfy, hgy, hy⟩, ⟨add_mem _ hfx hfy, add_mem _ hgx hgy, by erw [f.map_add ⟨x, hfx⟩ ⟨y, hfy⟩, g.map_add ⟨x, hgx⟩ ⟨y, hgy⟩, hx, hy]⟩, smul := λ c x ⟨hfx, hgx, hx⟩, ⟨smul_mem _ c hfx, smul_mem _ c hgx, by erw [f.map_smul c ⟨x, hfx⟩, g.map_smul c ⟨x, hgx⟩, hx]⟩ } instance : has_inf (linear_pmap R E F) := ⟨λ f g, ⟨f.eq_locus g, f.to_fun.comp $ of_le $ λ x hx, hx.fst⟩⟩ instance : has_bot (linear_pmap R E F) := ⟨⟨⊥, 0⟩⟩ instance : inhabited (linear_pmap R E F) := ⟨⊥⟩ instance : semilattice_inf_bot (linear_pmap R E F) := { le := (≤), le_refl := λ f, ⟨le_refl f.domain, λ x y h, subtype.eq h ▸ rfl⟩, le_trans := λ f g h ⟨fg_le, fg_eq⟩ ⟨gh_le, gh_eq⟩, ⟨le_trans fg_le gh_le, λ x z hxz, have hxy : (x:E) = of_le fg_le x, from rfl, (fg_eq hxy).trans (gh_eq $ hxy.symm.trans hxz)⟩, le_antisymm := λ f g fg gf, eq_of_le_of_domain_eq fg (le_antisymm fg.1 gf.1), bot := ⊥, bot_le := λ f, ⟨bot_le, λ x y h, have hx : x = 0, from subtype.eq ((mem_bot R).1 x.2), have hy : y = 0, from subtype.eq (h.symm.trans (congr_arg _ hx)), by rw [hx, hy, map_zero, map_zero]⟩, inf := (⊓), le_inf := λ f g h ⟨fg_le, fg_eq⟩ ⟨fh_le, fh_eq⟩, ⟨λ x hx, ⟨fg_le hx, fh_le hx, by refine (fg_eq _).symm.trans (fh_eq _); [exact ⟨x, hx⟩, refl, refl]⟩, λ x ⟨y, yg, hy⟩ h, by { apply fg_eq, exact h }⟩, inf_le_left := λ f g, ⟨λ x hx, hx.fst, λ x y h, congr_arg f $ subtype.eq $ by exact h⟩, inf_le_right := λ f g, ⟨λ x hx, hx.snd.fst, λ ⟨x, xf, xg, hx⟩ y h, hx.trans $ congr_arg g $ subtype.eq $ by exact h⟩ } lemma le_of_eq_locus_ge {f g : linear_pmap R E F} (H : f.domain ≤ f.eq_locus g) : f ≤ g := suffices f ≤ f ⊓ g, from le_trans this inf_le_right, ⟨H, λ x y hxy, ((inf_le_left : f ⊓ g ≤ f).2 hxy.symm).symm⟩ lemma domain_mono : strict_mono (@domain R _ E _ _ F _ _) := λ f g hlt, lt_of_le_of_ne hlt.1.1 $ λ heq, ne_of_lt hlt $ eq_of_le_of_domain_eq (le_of_lt hlt) heq private lemma sup_aux (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : ∃ fg : ↥(f.domain ⊔ g.domain) →ₗ[R] F, ∀ (x : f.domain) (y : g.domain) (z), (x:E) + y = ↑z → fg z = f x + g y := begin choose x hx y hy hxy using λ z : f.domain ⊔ g.domain, mem_sup.1 z.coe_prop, set fg := λ z, f ⟨x z, hx z⟩ + g ⟨y z, hy z⟩, have fg_eq : ∀ (x' : f.domain) (y' : g.domain) (z' : f.domain ⊔ g.domain) (H : (x':E) + y' = z'), fg z' = f x' + g y', { intros x' y' z' H, dsimp [fg], rw [add_comm, ← sub_eq_sub_iff_add_eq_add, eq_comm, ← map_sub, ← map_sub], apply h, simp only [← eq_sub_iff_add_eq] at hxy, simp only [coe_sub, coe_mk, coe_mk, hxy, ← sub_add, ← sub_sub, sub_self, zero_sub, ← H], apply neg_add_eq_sub }, refine ⟨⟨fg, _, _⟩, fg_eq⟩, { rintros ⟨z₁, hz₁⟩ ⟨z₂, hz₂⟩, rw [← add_assoc, add_right_comm (f _), ← map_add, add_assoc, ← map_add], apply fg_eq, simp only [coe_add, coe_mk, ← add_assoc], rw [add_right_comm (x _), hxy, add_assoc, hxy] }, { intros c z, rw [smul_add, ← map_smul, ← map_smul], apply fg_eq, simp only [coe_smul, coe_mk, ← smul_add, hxy] }, end /-- Given two partial linear maps that agree on the intersection of their domains, `f.sup g h` is the unique partial linear map on `f.domain ⊔ g.domain` that agrees with `f` and `g`. -/ protected noncomputable def sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : linear_pmap R E F := ⟨_, classical.some (sup_aux f g h)⟩ @[simp] lemma domain_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : (f.sup g h).domain = f.domain ⊔ g.domain := rfl lemma sup_apply {f g : linear_pmap R E F} (H : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) (x y z) (hz : (↑x:E) + ↑y = ↑z) : f.sup g H z = f x + g y := classical.some_spec (sup_aux f g H) x y z hz protected lemma left_le_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : f ≤ f.sup g h := begin refine ⟨le_sup_left, λ z₁ z₂ hz, _⟩, rw [← add_zero (f _), ← g.map_zero], refine (sup_apply h _ _ _ _).symm, simpa end protected lemma right_le_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : g ≤ f.sup g h := begin refine ⟨le_sup_right, λ z₁ z₂ hz, _⟩, rw [← zero_add (g _), ← f.map_zero], refine (sup_apply h _ _ _ _).symm, simpa end protected lemma sup_le {f g h : linear_pmap R E F} (H : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) (fh : f ≤ h) (gh : g ≤ h) : f.sup g H ≤ h := have Hf : f ≤ (f.sup g H) ⊓ h, from le_inf (f.left_le_sup g H) fh, have Hg : g ≤ (f.sup g H) ⊓ h, from le_inf (f.right_le_sup g H) gh, le_of_eq_locus_ge $ sup_le Hf.1 Hg.1 /-- Hypothesis for `linear_pmap.sup` holds, if `f.domain` is disjoint with `g.domain`. -/ lemma sup_h_of_disjoint (f g : linear_pmap R E F) (h : disjoint f.domain g.domain) (x : f.domain) (y : g.domain) (hxy : (x:E) = y) : f x = g y := begin rw [disjoint_def] at h, have hy : y = 0, from subtype.eq (h y (hxy ▸ x.2) y.2), have hx : x = 0, from subtype.eq (hxy.trans $ congr_arg _ hy), simp [*] end private lemma Sup_aux (c : set (linear_pmap R E F)) (hc : directed_on (≤) c) : ∃ f : ↥(Sup (domain '' c)) →ₗ[R] F, (⟨_, f⟩ : linear_pmap R E F) ∈ upper_bounds c := begin cases c.eq_empty_or_nonempty with ceq cne, { subst c, simp }, have hdir : directed_on (≤) (domain '' c), from (directed_on_image _).2 (hc.mono _ domain_mono.monotone), have P : Π x : Sup (domain '' c), {p : c // (x : E) ∈ p.val.domain }, { rintros x, apply classical.indefinite_description, have := (mem_Sup_of_directed (cne.image _) hdir).1 x.2, rwa [bex_image_iff, set_coe.exists'] at this }, set f : Sup (domain '' c) → F := λ x, (P x).val.val ⟨x, (P x).property⟩, have f_eq : ∀ (p : c) (x : Sup (domain '' c)) (y : p.1.1) (hxy : (x : E) = y), f x = p.1 y, { intros p x y hxy, rcases hc (P x).1.1 (P x).1.2 p.1 p.2 with ⟨q, hqc, hxq, hpq⟩, refine (hxq.2 _).trans (hpq.2 _).symm, exacts [of_le hpq.1 y, hxy, rfl] }, refine ⟨⟨f, _, _⟩, _⟩, { intros x y, rcases hc (P x).1.1 (P x).1.2 (P y).1.1 (P y).1.2 with ⟨p, hpc, hpx, hpy⟩, set x' := of_le hpx.1 ⟨x, (P x).2⟩, set y' := of_le hpy.1 ⟨y, (P y).2⟩, rw [f_eq ⟨p, hpc⟩ x x' rfl, f_eq ⟨p, hpc⟩ y y' rfl, f_eq ⟨p, hpc⟩ (x + y) (x' + y') rfl, map_add] }, { intros c x, rw [f_eq (P x).1 (c • x) (c • ⟨x, (P x).2⟩) rfl, ← map_smul] }, { intros p hpc, refine ⟨le_Sup $ mem_image_of_mem domain hpc, λ x y hxy, eq.symm _⟩, exact f_eq ⟨p, hpc⟩ _ _ hxy.symm } end /-- Glue a collection of partially defined linear maps to a linear map defined on `Sup` of these submodules. -/ protected noncomputable def Sup (c : set (linear_pmap R E F)) (hc : directed_on (≤) c) : linear_pmap R E F := ⟨_, classical.some $ Sup_aux c hc⟩ protected lemma le_Sup {c : set (linear_pmap R E F)} (hc : directed_on (≤) c) {f : linear_pmap R E F} (hf : f ∈ c) : f ≤ linear_pmap.Sup c hc := classical.some_spec (Sup_aux c hc) hf protected lemma Sup_le {c : set (linear_pmap R E F)} (hc : directed_on (≤) c) {g : linear_pmap R E F} (hg : ∀ f ∈ c, f ≤ g) : linear_pmap.Sup c hc ≤ g := le_of_eq_locus_ge $ Sup_le $ λ _ ⟨f, hf, eq⟩, eq ▸ have f ≤ (linear_pmap.Sup c hc) ⊓ g, from le_inf (linear_pmap.le_Sup _ hf) (hg f hf), this.1 end linear_pmap namespace linear_map /-- Restrict a linear map to a submodule, reinterpreting the result as a `linear_pmap`. -/ def to_pmap (f : E →ₗ[R] F) (p : submodule R E) : linear_pmap R E F := ⟨p, f.comp p.subtype⟩ @[simp] lemma to_pmap_apply (f : E →ₗ[R] F) (p : submodule R E) (x : p) : f.to_pmap p x = f x := rfl /-- Compose a linear map with a `linear_pmap` -/ def comp_pmap (g : F →ₗ[R] G) (f : linear_pmap R E F) : linear_pmap R E G := { domain := f.domain, to_fun := g.comp f.to_fun } @[simp] lemma comp_pmap_apply (g : F →ₗ[R] G) (f : linear_pmap R E F) (x) : g.comp_pmap f x = g (f x) := rfl end linear_map namespace linear_pmap /-- Restrict codomain of a `linear_pmap` -/ def cod_restrict (f : linear_pmap R E F) (p : submodule R F) (H : ∀ x, f x ∈ p) : linear_pmap R E p := { domain := f.domain, to_fun := f.to_fun.cod_restrict p H } /-- Compose two `linear_pmap`s -/ def comp (g : linear_pmap R F G) (f : linear_pmap R E F) (H : ∀ x : f.domain, f x ∈ g.domain) : linear_pmap R E G := g.to_fun.comp_pmap $ f.cod_restrict _ H /-- `f.coprod g` is the partially defined linear map defined on `f.domain × g.domain`, and sending `p` to `f p.1 + g p.2`. -/ def coprod (f : linear_pmap R E G) (g : linear_pmap R F G) : linear_pmap R (E × F) G := { domain := f.domain.prod g.domain, to_fun := (f.comp (linear_pmap.fst f.domain g.domain) (λ x, x.2.1)).to_fun + (g.comp (linear_pmap.snd f.domain g.domain) (λ x, x.2.2)).to_fun } @[simp] lemma coprod_apply (f : linear_pmap R E G) (g : linear_pmap R F G) (x) : f.coprod g x = f ⟨(x : E × F).1, x.2.1⟩ + g ⟨(x : E × F).2, x.2.2⟩ := rfl end linear_pmap
2bad5d40bb3257b2e69813a4bfd754d82f950bea
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/finset/fold.lean
4c76ff85c76e232db02f7eac045c86b5d3aea175
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
8,675
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.finset.basic import data.multiset.fold /-! # The fold operation for a commutative associative operation over a finset. -/ namespace finset open multiset variables {α β γ : Type*} /-! ### fold -/ section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b 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_cons (h : a ∉ s) : (cons a s h).fold op b f = f a * s.fold op b f := by { dunfold fold, rw [cons_val, multiset.map_cons, fold_cons_left], } @[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, multiset.map_cons, fold_cons_left] @[simp] theorem fold_singleton : ({a} : finset α).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 rfl 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] lemma fold_const [decidable (s = ∅)] (c : β) (h : op c (op b c) = op b c) : finset.fold op b (λ _, c) s = if s = ∅ then b else op b c := begin classical, unfreezingI { induction s using finset.induction_on with x s hx IH }, { simp }, { simp only [finset.fold_insert hx, IH, if_false, finset.insert_ne_empty], split_ifs, { rw hc.comm }, { exact h } } end 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_disj_union {s₁ s₂ : finset α} {b₁ b₂ : β} (h) : (s₁.disj_union s₂ h).fold op (b₁ * b₂) f = s₁.fold op b₁ f * s₂.fold op b₂ f := (congr_arg _ $ multiset.map_add _ _ _).trans (multiset.fold_add _ _ _ _ _) 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, ← multiset.map_add, union_val, inter_val, union_add_inter, multiset.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 := begin by_cases (a ∈ s), { rw [← insert_erase h], simp [← ha.assoc, hi.idempotent] }, { apply fold_insert h }, end theorem fold_image_idem [decidable_eq α] {g : γ → α} {s : finset γ} [hi : is_idempotent β op] : (image g s).fold op b f = s.fold op b (f ∘ g) := begin induction s using finset.cons_induction with x xs hx ih, { rw [fold_empty, image_empty, fold_empty] }, { haveI := classical.dec_eq γ, rw [fold_cons, cons_eq_insert, image_insert, fold_insert_idem, ih], } end /-- A stronger version of `finset.fold_ite`, but relies on an explicit proof of idempotency on the seed element, rather than relying on typeclass idempotency over the whole type. -/ lemma fold_ite' {g : α → β} (hb : op b b = b) (p : α → Prop) [decidable_pred p] : finset.fold op b (λ i, ite (p i) (f i) (g i)) s = op (finset.fold op b f (s.filter p)) (finset.fold op b g (s.filter (λ i, ¬ p i))) := begin classical, induction s using finset.induction_on with x s hx IH, { simp [hb] }, { simp only [finset.filter_congr_decidable, finset.fold_insert hx], split_ifs with h h, { have : x ∉ finset.filter p s, { simp [hx] }, simp [finset.filter_insert, h, finset.fold_insert this, ha.assoc, IH] }, { have : x ∉ finset.filter (λ i, ¬ p i) s, { simp [hx] }, simp [finset.filter_insert, h, finset.fold_insert this, IH, ←ha.assoc, hc.comm] } } end /-- A weaker version of `finset.fold_ite'`, relying on typeclass idempotency over the whole type, instead of solely on the seed element. However, this is easier to use because it does not generate side goals. -/ lemma fold_ite [is_idempotent β op] {g : α → β} (p : α → Prop) [decidable_pred p] : finset.fold op b (λ i, ite (p i) (f i) (g i)) s = op (finset.fold op b f (s.filter p)) (finset.fold op b g (s.filter (λ i, ¬ p i))) := fold_ite' (is_idempotent.idempotent _) _ lemma fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc], apply and_congr iff.rfl, split, { rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb, rcases hb with rfl|hb; solve_by_elim }, { intro h, split, { exact h a (finset.mem_insert_self _ _), }, { intros b hb, apply h b, rw finset.mem_insert, right, exact hb } } end lemma fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc], apply or_congr iff.rfl, split, { rintro (h₁|⟨x, hx, h₂⟩), { use a, simp [h₁] }, { refine ⟨x, by simp [hx], h₂⟩ } }, { rintro ⟨x, hx, h⟩, rw mem_insert at hx, cases hx, { left, rwa hx at h }, { right, exact ⟨x, hx, h⟩ } } end omit hc ha @[simp] lemma fold_union_empty_singleton [decidable_eq α] (s : finset α) : finset.fold (∪) ∅ singleton s = s := begin apply finset.induction_on s, { simp only [fold_empty], }, { intros a s has ih, rw [fold_insert has, ih, insert_eq], } end lemma fold_sup_bot_singleton [decidable_eq α] (s : finset α) : finset.fold (⊔) ⊥ singleton s = s := fold_union_empty_singleton s section order variables [linear_order β] (c : β) lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) := fold_op_rel_iff_and $ λ x y z, le_min_iff lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ ≤ _ ↔ _, exact min_le_iff end lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) := fold_op_rel_iff_and $ λ x y z, lt_min_iff lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ < _ ↔ _, exact min_lt_iff end lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ ≤ _ ↔ _, exact max_le_iff end lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) := fold_op_rel_iff_or $ λ x y z, le_max_iff lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ < _ ↔ _, exact max_lt_iff end lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) := fold_op_rel_iff_or $ λ x y z, lt_max_iff lemma fold_max_add [has_add β] [covariant_class β β (function.swap (+)) (≤)] (n : with_bot β) (s : finset α) : s.fold max ⊥ (λ (x : α), ↑(f x) + n) = s.fold max ⊥ (coe ∘ f) + n := by { classical, apply s.induction_on; simp [max_add_add_right] {contextual := tt} } end order end fold end finset
fec457dcb2995948b78daba81818f75f21c3f3ef
b561a44b48979a98df50ade0789a21c79ee31288
/src/Lean/Meta/Tactic/Util.lean
006b9c5f62f22a59e61595d2a2f1f78309967c37
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,120
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Meta.Basic import Lean.Meta.AppBuilder import Lean.Meta.LevelDefEq import Lean.Meta.PPGoal namespace Lean.Meta /-- Aka user name -/ def getMVarTag (mvarId : MVarId) : MetaM Name := return (← getMVarDecl mvarId).userName def setMVarTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do modify fun s => { s with mctx := s.mctx.renameMVar mvarId tag } def appendTag (tag : Name) (suffix : Name) : Name := tag.modifyBase (. ++ suffix.eraseMacroScopes) def appendTagSuffix (mvarId : MVarId) (suffix : Name) : MetaM Unit := do let tag ← getMVarTag mvarId setMVarTag mvarId (appendTag tag suffix) def mkFreshExprSyntheticOpaqueMVar (type : Expr) (tag : Name := Name.anonymous) : MetaM Expr := mkFreshExprMVar type MetavarKind.syntheticOpaque tag def throwTacticEx {α} (tacticName : Name) (mvarId : MVarId) (msg : MessageData) (ref := Syntax.missing) : MetaM α := throwError "tactic '{tacticName}' failed, {msg}\n{MessageData.ofGoal mvarId}" def checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do if (← isExprMVarAssigned mvarId) then throwTacticEx tacticName mvarId "metavariable has already been assigned" def getMVarType (mvarId : MVarId) : MetaM Expr := return (← getMVarDecl mvarId).type def getMVarType' (mvarId : MVarId) : MetaM Expr := do whnf (← instantiateMVars (← getMVarDecl mvarId).type) builtin_initialize registerTraceClass `Meta.Tactic /-- Assign `mvarId` to `sorryAx` -/ def admit (mvarId : MVarId) (synthetic := true) : MetaM Unit := withMVarContext mvarId do checkNotAssigned mvarId `admit let mvarType ← getMVarType mvarId let val ← mkSorry mvarType synthetic assignExprMVar mvarId val /-- Beta reduce the metavariable type head -/ def headBetaMVarType (mvarId : MVarId) : MetaM Unit := do setMVarType mvarId (← getMVarType mvarId).headBeta /-- Collect nondependent hypotheses that are propositions. -/ def getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) := withMVarContext mvarId do let mut candidates : FVarIdHashSet := {} for localDecl in (← getLCtx) do unless localDecl.isAuxDecl do candidates ← removeDeps localDecl.type candidates match localDecl.value? with | none => pure () | some value => candidates ← removeDeps value candidates if (← isProp localDecl.type) && !localDecl.hasValue then candidates := candidates.insert localDecl.fvarId candidates ← removeDeps (← getMVarType mvarId) candidates if candidates.isEmpty then return #[] else let mut result := #[] for localDecl in (← getLCtx) do if candidates.contains localDecl.fvarId then result := result.push localDecl.fvarId return result where removeDeps (e : Expr) (candidates : FVarIdHashSet) : MetaM FVarIdHashSet := do let e ← instantiateMVars e let visit : StateRefT FVarIdHashSet MetaM FVarIdHashSet := do e.forEach fun | Expr.fvar fvarId _ => modify fun s => s.erase fvarId | _ => pure () get visit |>.run' candidates partial def saturate (mvarId : MVarId) (x : MVarId → MetaM (Option (List MVarId))) : MetaM (List MVarId) := do let (_, r) ← go mvarId |>.run #[] return r.toList where go (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := withIncRecDepth do match (← x mvarId) with | none => modify fun s => s.push mvarId | some mvarIds => mvarIds.forM go def exactlyOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM MVarId := match mvarIds with | [mvarId] => return mvarId | _ => throwError msg def ensureAtMostOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM (Option MVarId) := match mvarIds with | [] => return none | [mvarId] => return some mvarId | _ => throwError msg end Lean.Meta
5b5957a3ab5151ae32404debd4ac1bf6531c5106
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/measure/stieltjes.lean
d8e43bc743a1cb54550e6c8e2741710182c33dc7
[ "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,630
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov, Sébastien Gouëzel -/ import measure_theory.constructions.borel_space /-! # Stieltjes measures on the real line Consider a function `f : ℝ → ℝ` which is monotone and right-continuous. Then one can define a corrresponding measure, giving mass `f b - f a` to the interval `(a, b]`. ## Main definitions * `stieltjes_function` is a structure containing a function from `ℝ → ℝ`, together with the assertions that it is monotone and right-continuous. To `f : stieltjes_function`, one associates a Borel measure `f.measure`. * `f.left_lim x` is the limit of `f` to the left of `x`. * `f.measure_Ioc` asserts that `f.measure (Ioc a b) = of_real (f b - f a)` * `f.measure_Ioo` asserts that `f.measure (Ioo a b) = of_real (f.left_lim b - f a)`. * `f.measure_Icc` and `f.measure_Ico` are analogous. -/ noncomputable theory open classical set filter open ennreal (of_real) open_locale big_operators ennreal nnreal topological_space measure_theory /-! ### Basic properties of Stieltjes functions -/ /-- Bundled monotone right-continuous real functions, used to construct Stieltjes measures. -/ structure stieltjes_function := (to_fun : ℝ → ℝ) (mono' : monotone to_fun) (right_continuous' : ∀ x, continuous_within_at to_fun (Ici x) x) namespace stieltjes_function instance : has_coe_to_fun stieltjes_function (λ _, ℝ → ℝ) := ⟨to_fun⟩ initialize_simps_projections stieltjes_function (to_fun → apply) variable (f : stieltjes_function) lemma mono : monotone f := f.mono' lemma right_continuous (x : ℝ) : continuous_within_at f (Ici x) x := f.right_continuous' x /-- The limit of a Stieltjes function to the left of `x` (it exists by monotonicity). The fact that it is indeed a left limit is asserted in `tendsto_left_lim` -/ @[irreducible] def left_lim (x : ℝ) := Sup (f '' (Iio x)) lemma tendsto_left_lim (x : ℝ) : tendsto f (𝓝[<] x) (𝓝 (f.left_lim x)) := by { rw left_lim, exact f.mono.tendsto_nhds_within_Iio x } lemma left_lim_le {x y : ℝ} (h : x ≤ y) : f.left_lim x ≤ f y := begin apply le_of_tendsto (f.tendsto_left_lim x), filter_upwards [self_mem_nhds_within] with _ hz using (f.mono (le_of_lt hz)).trans (f.mono h), end lemma le_left_lim {x y : ℝ} (h : x < y) : f x ≤ f.left_lim y := begin apply ge_of_tendsto (f.tendsto_left_lim y), apply mem_nhds_within_Iio_iff_exists_Ioo_subset.2 ⟨x, h, _⟩, assume z hz, exact f.mono hz.1.le, end lemma left_lim_le_left_lim {x y : ℝ} (h : x ≤ y) : f.left_lim x ≤ f.left_lim y := begin rcases eq_or_lt_of_le h with rfl|hxy, { exact le_rfl }, { exact (f.left_lim_le le_rfl).trans (f.le_left_lim hxy) } end /-- The identity of `ℝ` as a Stieltjes function, used to construct Lebesgue measure. -/ @[simps] protected def id : stieltjes_function := { to_fun := id, mono' := λ x y, id, right_continuous' := λ x, continuous_within_at_id } @[simp] lemma id_left_lim (x : ℝ) : stieltjes_function.id.left_lim x = x := tendsto_nhds_unique (stieltjes_function.id.tendsto_left_lim x) $ (continuous_at_id).tendsto.mono_left nhds_within_le_nhds instance : inhabited stieltjes_function := ⟨stieltjes_function.id⟩ /-! ### The outer measure associated to a Stieltjes function -/ /-- Length of an interval. This is the largest monotone function which correctly measures all intervals. -/ def length (s : set ℝ) : ℝ≥0∞ := ⨅a b (h : s ⊆ Ioc a b), of_real (f b - f a) @[simp] lemma length_empty : f.length ∅ = 0 := nonpos_iff_eq_zero.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma length_Ioc (a b : ℝ) : f.length (Ioc a b) = of_real (f b - f a) := begin refine le_antisymm (infi_le_of_le a $ infi₂_le b subset.rfl) (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _), cases le_or_lt b a with ab ab, { rw real.to_nnreal_of_nonpos (sub_nonpos.2 (f.mono ab)), apply zero_le, }, cases (Ioc_subset_Ioc_iff ab).1 h with h₁ h₂, exact real.to_nnreal_le_to_nnreal (sub_le_sub (f.mono h₁) (f.mono h₂)) end lemma length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : f.length s₁ ≤ f.length s₂ := infi_mono $ λ a, binfi_mono $ λ b, h.trans open measure_theory /-- The Stieltjes outer measure associated to a Stieltjes function. -/ protected def outer : outer_measure ℝ := outer_measure.of_function f.length f.length_empty lemma outer_le_length (s : set ℝ) : f.outer s ≤ f.length s := outer_measure.of_function_le _ /-- If a compact interval `[a, b]` is covered by a union of open interval `(c i, d i)`, then `f b - f a ≤ ∑ f (d i) - f (c i)`. This is an auxiliary technical statement to prove the same statement for half-open intervals, the point of the current statement being that one can use compactness to reduce it to a finite sum, and argue by induction on the size of the covering set. -/ lemma length_subadditive_Icc_Ioo {a b : ℝ} {c d : ℕ → ℝ} (ss : Icc a b ⊆ ⋃ i, Ioo (c i) (d i)) : of_real (f b - f a) ≤ ∑' i, of_real (f (d i) - f (c i)) := begin suffices : ∀ (s:finset ℕ) b (cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)), (of_real (f b - f a) : ℝ≥0∞) ≤ ∑ i in s, of_real (f (d i) - f (c i)), { rcases is_compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ), @is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), by simp only [ext_iff, exists_prop, finset.set_bUnion_coe, mem_Union, forall_const, iff_self, finite.mem_to_finset], rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa only [e]) }, clear ss b, refine λ s, finset.strong_induction_on s (λ s IH b cv, _), cases le_total b a with ab ab, { rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 (f.mono ab)), exact zero_le _, }, have := cv ⟨ab, le_rfl⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊢, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _), { refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (f.mono bd.le) _ }, { rintro x ⟨h₁, h₂⟩, refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le h₂)) } end @[simp] lemma outer_Ioc (a b : ℝ) : f.outer (Ioc a b) = of_real (f b - f a) := begin /- It suffices to show that, if `(a, b]` is covered by sets `s i`, then `f b - f a` is bounded by `∑ f.length (s i) + ε`. The difficulty is that `f.length` is expressed in terms of half-open intervals, while we would like to have a compact interval covered by open intervals to use compactness and finite sums, as provided by `length_subadditive_Icc_Ioo`. The trick is to use the right-continuity of `f`. If `a'` is close enough to `a` on its right, then `[a', b]` is still covered by the sets `s i` and moreover `f b - f a'` is very close to `f b - f a` (up to `ε/2`). Also, by definition one can cover `s i` by a half-closed interval `(p i, q i]` with `f`-length very close to that of `s i` (within a suitably small `ε' i`, say). If one moves `q i` very slightly to the right, then the `f`-length will change very little by right continuity, and we will get an open interval `(p i, q' i)` covering `s i` with `f (q' i) - f (p i)` within `ε' i` of the `f`-length of `s i`. -/ refine le_antisymm (by { rw ← f.length_Ioc, apply outer_le_length }) (le_infi₂ $ λ s hs, ennreal.le_of_forall_pos_le_add $ λ ε εpos h, _), let δ := ε / 2, have δpos : 0 < (δ : ℝ≥0∞), by simpa using εpos.ne', rcases ennreal.exists_pos_sum_of_encodable δpos.ne' ℕ with ⟨ε', ε'0, hε⟩, obtain ⟨a', ha', aa'⟩ : ∃ a', f a' - f a < δ ∧ a < a', { have A : continuous_within_at (λ r, f r - f a) (Ioi a) a, { refine continuous_within_at.sub _ continuous_within_at_const, exact (f.right_continuous a).mono Ioi_subset_Ici_self }, have B : f a - f a < δ, by rwa [sub_self, nnreal.coe_pos, ← ennreal.coe_pos], exact (((tendsto_order.1 A).2 _ B).and self_mem_nhds_within).exists }, have : ∀ i, ∃ p:ℝ×ℝ, s i ⊆ Ioo p.1 p.2 ∧ (of_real (f p.2 - f p.1) : ℝ≥0∞) < f.length (s i) + ε' i, { intro i, have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne (ennreal.coe_ne_zero.2 (ε'0 i).ne')), conv at this { to_lhs, rw length }, simp only [infi_lt_iff, exists_prop] at this, rcases this with ⟨p, q', spq, hq'⟩, have : continuous_within_at (λ r, of_real (f r - f p)) (Ioi q') q', { apply ennreal.continuous_of_real.continuous_at.comp_continuous_within_at, refine continuous_within_at.sub _ continuous_within_at_const, exact (f.right_continuous q').mono Ioi_subset_Ici_self }, rcases (((tendsto_order.1 this).2 _ hq').and self_mem_nhds_within).exists with ⟨q, hq, q'q⟩, exact ⟨⟨p, q⟩, spq.trans (Ioc_subset_Ioo_right q'q), hq⟩ }, choose g hg using this, have I_subset : Icc a' b ⊆ ⋃ i, Ioo (g i).1 (g i).2 := calc Icc a' b ⊆ Ioc a b : λ x hx, ⟨aa'.trans_le hx.1, hx.2⟩ ... ⊆ ⋃ i, s i : hs ... ⊆ ⋃ i, Ioo (g i).1 (g i).2 : Union_mono (λ i, (hg i).1), calc of_real (f b - f a) = of_real ((f b - f a') + (f a' - f a)) : by rw sub_add_sub_cancel ... ≤ of_real (f b - f a') + of_real (f a' - f a) : ennreal.of_real_add_le ... ≤ (∑' i, of_real (f (g i).2 - f (g i).1)) + of_real δ : add_le_add (f.length_subadditive_Icc_Ioo I_subset) (ennreal.of_real_le_of_real ha'.le) ... ≤ (∑' i, (f.length (s i) + ε' i)) + δ : add_le_add (ennreal.tsum_le_tsum (λ i, (hg i).2.le)) (by simp only [ennreal.of_real_coe_nnreal, le_rfl]) ... = (∑' i, f.length (s i)) + (∑' i, ε' i) + δ : by rw [ennreal.tsum_add] ... ≤ (∑' i, f.length (s i)) + δ + δ : add_le_add (add_le_add le_rfl hε.le) le_rfl ... = ∑' (i : ℕ), f.length (s i) + ε : by simp [add_assoc, ennreal.add_halves] end lemma measurable_set_Ioi {c : ℝ} : measurable_set[f.outer.caratheodory] (Ioi c) := begin apply outer_measure.of_function_caratheodory (λ t, _), refine le_infi (λ a, le_infi (λ b, le_infi (λ h, _))), refine le_trans (add_le_add (f.length_mono $ inter_subset_inter_left _ h) (f.length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hac; cases le_total b c with hbc hbc, { simp only [Ioc_inter_Ioi, f.length_Ioc, hac, sup_eq_max, hbc, le_refl, Ioc_eq_empty, max_eq_right, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, not_lt] }, { simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right, sup_eq_max, ←ennreal.of_real_add, f.mono hac, f.mono hbc, sub_nonneg, sub_add_sub_cancel, le_refl, max_eq_right] }, { simp only [hbc, le_refl, Ioc_eq_empty, Ioc_inter_Ioi, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, or_true, le_sup_iff, f.length_Ioc, not_lt] }, { simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right, sup_eq_max, le_refl, Ioc_eq_empty, add_zero, max_eq_left, f.length_empty, not_lt] } end theorem outer_trim : f.outer.trim = f.outer := begin refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, refine le_infi (λ t, le_infi $ λ ht, ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_pos.2 ε0).ne' ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left (le_of_lt hε) _), rw ← ennreal.tsum_add, choose g hg using show ∀ i, ∃ s, t i ⊆ s ∧ measurable_set s ∧ f.outer s ≤ f.length (t i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne (ennreal.coe_pos.2 (ε'0 i)).ne'), conv at this {to_lhs, rw length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, h₂⟩, rw ← f.outer_Ioc at h₂, exact ⟨_, h₁, measurable_set_Ioc, le_of_lt $ by simpa using h₂⟩ }, simp at hg, apply infi_le_of_le (Union g) _, apply infi_le_of_le (ht.trans $ Union_mono (λ i, (hg i).1)) _, apply infi_le_of_le (measurable_set.Union (λ i, (hg i).2.1)) _, exact le_trans (f.outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2) end lemma borel_le_measurable : borel ℝ ≤ f.outer.caratheodory := begin rw borel_eq_generate_from_Ioi, refine measurable_space.generate_from_le _, simp [f.measurable_set_Ioi] { contextual := tt } end /-! ### The measure associated to a Stieltjes function -/ /-- The measure associated to a Stieltjes function, giving mass `f b - f a` to the interval `(a, b]`. -/ @[irreducible] protected def measure : measure ℝ := { to_outer_measure := f.outer, m_Union := λ s hs, f.outer.Union_eq_of_caratheodory $ λ i, f.borel_le_measurable _ (hs i), trimmed := f.outer_trim } @[simp] lemma measure_Ioc (a b : ℝ) : f.measure (Ioc a b) = of_real (f b - f a) := by { rw stieltjes_function.measure, exact f.outer_Ioc a b } @[simp] lemma measure_singleton (a : ℝ) : f.measure {a} = of_real (f a - f.left_lim a) := begin obtain ⟨u, u_mono, u_lt_a, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_mono u ∧ (∀ (n : ℕ), u n < a) ∧ tendsto u at_top (𝓝 a) := exists_seq_strict_mono_tendsto a, have A : {a} = ⋂ n, Ioc (u n) a, { refine subset.antisymm (λ x hx, by simp [mem_singleton_iff.1 hx, u_lt_a]) (λ x hx, _), simp at hx, have : a ≤ x := le_of_tendsto' u_lim (λ n, (hx n).1.le), simp [le_antisymm this (hx 0).2] }, have L1 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (f.measure {a})), { rw A, refine tendsto_measure_Inter (λ n, measurable_set_Ioc) (λ m n hmn, _) _, { exact Ioc_subset_Ioc (u_mono.monotone hmn) le_rfl }, { exact ⟨0, by simpa only [measure_Ioc] using ennreal.of_real_ne_top⟩ } }, have L2 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (of_real (f a - f.left_lim a))), { simp only [measure_Ioc], have : tendsto (λ n, f (u n)) at_top (𝓝 (f.left_lim a)), { apply (f.tendsto_left_lim a).comp, exact tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ u_lim (eventually_of_forall (λ n, u_lt_a n)) }, exact ennreal.continuous_of_real.continuous_at.tendsto.comp (tendsto_const_nhds.sub this) }, exact tendsto_nhds_unique L1 L2 end @[simp] lemma measure_Icc (a b : ℝ) : f.measure (Icc a b) = of_real (f b - f.left_lim a) := begin rcases le_or_lt a b with hab|hab, { have A : disjoint {a} (Ioc a b), by simp, simp [← Icc_union_Ioc_eq_Icc le_rfl hab, -singleton_union, ← ennreal.of_real_add, f.left_lim_le, measure_union A measurable_set_Ioc, f.mono hab] }, { simp only [hab, measure_empty, Icc_eq_empty, not_le], symmetry, simp [ennreal.of_real_eq_zero, f.le_left_lim hab] } end @[simp] lemma measure_Ioo {a b : ℝ} : f.measure (Ioo a b) = of_real (f.left_lim b - f a) := begin rcases le_or_lt b a with hab|hab, { simp only [hab, measure_empty, Ioo_eq_empty, not_lt], symmetry, simp [ennreal.of_real_eq_zero, f.left_lim_le hab] }, { have A : disjoint (Ioo a b) {b}, by simp, have D : f b - f a = (f b - f.left_lim b) + (f.left_lim b - f a), by abel, have := f.measure_Ioc a b, simp only [←Ioo_union_Icc_eq_Ioc hab le_rfl, measure_singleton, measure_union A (measurable_set_singleton b), Icc_self] at this, rw [D, ennreal.of_real_add, add_comm] at this, { simpa only [ennreal.add_right_inj ennreal.of_real_ne_top] }, { simp only [f.left_lim_le, sub_nonneg] }, { simp only [f.le_left_lim hab, sub_nonneg] } }, end @[simp] lemma measure_Ico (a b : ℝ) : f.measure (Ico a b) = of_real (f.left_lim b - f.left_lim a) := begin rcases le_or_lt b a with hab|hab, { simp only [hab, measure_empty, Ico_eq_empty, not_lt], symmetry, simp [ennreal.of_real_eq_zero, f.left_lim_le_left_lim hab] }, { have A : disjoint {a} (Ioo a b) := by simp, simp [← Icc_union_Ioo_eq_Ico le_rfl hab, -singleton_union, hab.ne, f.left_lim_le, measure_union A measurable_set_Ioo, f.le_left_lim hab, ← ennreal.of_real_add] } end end stieltjes_function
cc29924c6a46e82835402ea9d7d88b4e6609e460
670b1582ba4780d3b4a49063d5afea44a337bc24
/src/problem_translation.lean
3752bbb10921b762edfa5c941671ae9309899f0b
[]
no_license
robertylewis/Lean_hammer
9bd8a75cb6fc76b3387c84f0678ccfd69fa10c88
7c8b6235c064fac164cbd389c8d459bd106e09b1
refs/heads/master
1,587,608,490,192
1,550,228,670,000
1,550,228,670,000
170,843,813
0
0
null
1,550,225,214,000
1,550,225,213,000
null
UTF-8
Lean
false
false
5,570
lean
import .tptp.tptp import .tptp.translation_tptp import .tptp.simplification_tptp --################################## --## 5.3 Translating declarations ## --################################## meta def translate_axiom_expression: expr → hammer_tactic unit -- | `() | `(%%l = %%r) := -- c = t : τ do (τ, _) ← using_hammer $ tactic.infer_type r, -- Get type of right side -- tactic.trace l, -- tactic.trace r, lip <- lives_in_prop_p τ, -- Check whether τ is from type prop (and therefore right side a proof) or not if lip then -- If yes, add new axiom of F(τ) (TODO: and name c) do fe1 ← (hammer_f τ), Cn ← mk_fresh_name, add_axiom Cn fe1 else -- Otherwise, add type checker G(c,τ) as new axiom do (c,_) <- using_hammer (hammer_c l), g_axiom <- hammer_g c τ, Cn ← mk_fresh_name, add_axiom Cn g_axiom, lit <- lives_in_prop_p r, -- Check if τ=Prop (or rather t : Prop) if lit then -- If yes, add new axiom c ↔ F(t) do (fe1,_) <- using_hammer (hammer_f l), (fe2,_) <- using_hammer (hammer_f r), Cn ← mk_fresh_name, add_axiom Cn (folform.iff fe1 fe2) else -- Otherwise, check whether τ is from type Set or Type, or another type do lis <- lives_in_type r, -- WRONG IMPLEMENTATION! TODO: Implement check of τ for Set and Type! if lis then do xn ← mk_fresh_name, let f := folterm.lconst xn xn, -- a <- wrap_quantifier folform.all [(xn, xn)] (folform.iff (hammer_c $ folterm.app c f) (hammer_g f r)), -- TODO: Implement the correct formula let a := folform.top, Cn <- mk_fresh_name, add_axiom Cn a else do Cn <- mk_fresh_name, (Cc,_) <- using_hammer (hammer_c r), (Ct,_) <- using_hammer (hammer_c l), add_axiom Cn (folform.eq Cc Ct) -- Inductive declarations are handled in advance. Thus we don't have to check for them anymore | `(%%c : _) := -- c : τ do (τ, _) ← using_hammer $ tactic.infer_type c, -- Get type of right side -- tactic.trace c, lip <- lives_in_prop_p τ, -- Check whether τ is from type prop (and therefore right side a proof) or not -- tactic.trace τ, -- Note that if τ is Prop itself, then the type checker G ... will take care of it. if lip then do Cn <- mk_fresh_name, (Fτ,_) <- using_hammer (hammer_f τ), add_axiom Cn Fτ else -- Additional check which is not in the paper. If the axiom is of type Prop, we want to add it as statement which must be true. -- Thus, declarations like (Π(x:ℕ) x+x=2*x) are translated by applying F. do lip <- lives_in_prop_p c, if lip then do Cn <- mk_fresh_name, (Fc,_) <- using_hammer (hammer_f c), add_axiom Cn Fc else do Cn <- mk_fresh_name, (Cc,_) <- using_hammer (hammer_c c), (Gcτ,_) <- using_hammer (hammer_g Cc τ), add_axiom Cn Gcτ meta def lambda_expr_to_pi : expr → expr → tactic expr | s e@(expr.lam n b a c) := do tactic.trace n, tactic.trace a, tactic.trace c, match c with | cexp@(expr.lam n0 b0 a0 c0) := do conv_exp ← lambda_expr_to_pi s cexp, return $ expr.pi n b a conv_exp | cexp := do f ← lambda_expr_to_pi s cexp, let pi_e := expr.pi n b a `(f = s), return pi_e end | s e := return e -- All other forms are ignored meta def process_declarations : list name → hammer_tactic unit | [] := tactic.skip | (x :: xs) := do d ← tactic.get_decl x, translate_axiom_expression d.value, process_declarations xs -- TODO: inductive declarations work, but not simple declarations! We get lambda expressions but need pi expression with equality meta def expr_in_parts : expr → tactic expr | e@(expr.lam n b a c) := do tactic.trace n, tactic.trace a, tactic.trace a, tactic.trace c, return $ expr.pi n b a c | e@(expr.pi n b a c) := do tactic.trace n, tactic.trace a, tactic.trace a, tactic.trace c, return $ expr.lam n b a c | e := return e --############################### --## Final problem translation ## --############################### meta def translate_declaration (e : name) : hammer_tactic unit := do env <- tactic.get_env, d <- tactic.get_decl e, l ← tactic.get_eqn_lemmas_for tt e, process_declarations (l.append [e]) meta def translate_problem: list name → list expr → hammer_tactic unit | [] [] := tactic.skip | [] (x::xs) := do translate_axiom_expression x, translate_problem [] xs | (y::ys) xs := do translate_declaration y, translate_problem ys xs meta def problem_to_format (declr: list name) (clauses: list expr) (conjecture: expr) : hammer_tactic format := do ⟨cl,cl_state⟩ <- using_hammer (translate_problem declr clauses), ⟨conj,conj_state⟩ <- using_hammer (hammer_f conjecture), let ⟨cl_list,conj⟩ := simplify_terms (hammer_state.axiomas cl_state) conj, -- ⟨cl_list,conj⟩ <- simplify_terms cl_list conj, -- TODO: Fix problem of not getting all simplifications in the first run (see function comments) return $ to_tptp cl_list conj
f568ff861c0faf55ec414f484f0b6524972f370b
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Compiler/IR/CtorLayout.lean
f36921e78b98a430f0702527a5c45d23659a0d5b
[ "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
960
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 import Lean.Compiler.IR.Format namespace Lean namespace IR inductive CtorFieldInfo := | irrelevant | object (i : Nat) | usize (i : Nat) | scalar (sz : Nat) (offset : Nat) (type : IRType) namespace CtorFieldInfo def format : CtorFieldInfo → Format | irrelevant => "◾" | object i => f!"obj@{i}" | usize i => f!"usize@{i}" | scalar sz offset type => f!"scalar#{sz}@{offset}:{type}" instance : ToFormat CtorFieldInfo := ⟨format⟩ end CtorFieldInfo structure CtorLayout := (cidx : Nat) (fieldInfo : List CtorFieldInfo) (numObjs : Nat) (numUSize : Nat) (scalarSize : Nat) @[extern "lean_ir_get_ctor_layout"] constant getCtorLayout (env : @& Environment) (ctorName : @& Name) : Except String CtorLayout end IR end Lean
48dae2d654d5218126481f1114c0b7ae80bc1497
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/assoc_simp.lean
f0d5b7d6742c23754f9c873b5620a1cd0c0e1ed9
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
2,315
lean
import data.matrix tactic.ring open tactic declaration expr binder_info #print binder_fin local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := matrix.transpose #print matrix.mul --set_option trace.class_instances true set_option eqn_compiler.max_steps 100000 set_option trace.app_builder true meta def mk_new_theorem : expr → tactic (expr) | (pi n b dom cod) := do cod ← mk_new_theorem cod, return (pi n b dom cod) | `(@matrix.mul %%l %%m %%n %%fl %%fm %%fn ℚ _ _ %%A %%B = %%C) := do k ← mk_fresh_name, k' ← mk_local' k implicit `(ℕ), fintype_k ← mk_app `fin.fintype [k'], D ← mk_fresh_name, D_type ← mk_mapp `matrix [n, `(fin %%k'), fn, fintype_k, `(ℚ)], B' ← mk_local_def `B B, D' ← mk_local' D default D_type, B_mul_D ← mk_mapp `matrix.mul [some m, some n, some k', fm, fn, fintype_k, `(rat), `(rat.has_mul), `(rat.add_comm_monoid), B', D'], trace "x", return`(ℕ) -- A_mul_B_mul_D ← mk_app `matrix.mul [A, B_mul_D], -- C_mul_D ← mk_app `matrix.mul [C, (var (v + 1))], -- eeq ← mk_app `eq [A_mul_B_mul_D, C_mul_D], -- return (pi k implicit `(nat) (pi D implicit `(matrix (fin %%m) (fin %%(var v)) ℚ) eeq)) -- let e : expr := `(%%A ⬝ (%%B ⬝ D) = %%C ⬝ D) in -- return `(∀ {k : ℕ} (D : matrix (fin %%n) (fin k) ℚ), %%A ⬝ (%%B ⬝ D) = %%C ⬝ D) | _ := do trace "y", failure run_cmd do t ← mk_local_pis `(∀ A B : matrix (fin 1) (fin 1) ℚ, A ⬝ B = 1), trace (t.1.map to_raw_fmt) meta def codomain (e : expr) : expr := if e.is_pi then codomain e.binding_body else e #print tactic.interactive.ring meta def m_assoc_simp_attr : user_attribute := { name := `m_assoc_simp, descr := "given a proof A ⬝ B = C, generate the lemma A ⬝ (B ⬝ D) = C ⬝ D, and mark it with a simp attribute", after_set := some $ λ n _ _, do env ← get_env, dec ← get_decl n, match dec with | thm n _ t _ := let target := codomain t in match target with | `(@matrix.mul (fin %%l) (fin %%m) (fin %%n) %%_x %%__x %%___x ℚ _ _ %%A %%B = %%C) := sorry | _ := trace "declaration has wrong type", fail | _ := trace "declaratin is not a theorem", fail end } #reduce user_attribute_cache_cfg unit
4b3a7c15e0cfd2e9fa91c0d363aeaeb781a6f132
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/class_group.lean
5906c8ca465f754baf3f091b6833465b3370c68a
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,459
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import group_theory.quotient_group import ring_theory.dedekind_domain /-! # The ideal class group This file defines the ideal class group `class_group R K` of fractional ideals of `R` inside `A`'s field of fractions `K`. ## Main definitions - `to_principal_ideal` sends an invertible `x : K` to an invertible fractional ideal - `class_group` is the quotient of invertible fractional ideals modulo `to_principal_ideal.range` - `class_group.mk0` sends a nonzero integral ideal in a Dedekind domain to its class ## Main results - `class_group.mk0_eq_mk0_iff` shows the equivalence with the "classical" definition, where `I ~ J` iff `x I = y J` for `x y ≠ (0 : R)` -/ variables {R K L : Type*} [comm_ring R] variables [field K] [field L] [decidable_eq L] variables [algebra R K] [is_fraction_ring R K] variables [algebra K L] [finite_dimensional K L] variables [algebra R L] [is_scalar_tower R K L] open_locale non_zero_divisors open is_localization is_fraction_ring fractional_ideal units section variables (R K) /-- `to_principal_ideal R K x` sends `x ≠ 0 : K` to the fractional `R`-ideal generated by `x` -/ @[irreducible] def to_principal_ideal : units K →* units (fractional_ideal R⁰ K) := { to_fun := λ x, ⟨span_singleton _ x, span_singleton _ x⁻¹, by simp only [span_singleton_one, units.mul_inv', span_singleton_mul_span_singleton], by simp only [span_singleton_one, units.inv_mul', span_singleton_mul_span_singleton]⟩, map_mul' := λ x y, ext (by simp only [units.coe_mk, units.coe_mul, span_singleton_mul_span_singleton]), map_one' := ext (by simp only [span_singleton_one, units.coe_mk, units.coe_one]) } local attribute [semireducible] to_principal_ideal variables {R K} @[simp] lemma coe_to_principal_ideal (x : units K) : (to_principal_ideal R K x : fractional_ideal R⁰ K) = span_singleton _ x := rfl @[simp] lemma to_principal_ideal_eq_iff {I : units (fractional_ideal R⁰ K)} {x : units K} : to_principal_ideal R K x = I ↔ span_singleton R⁰ (x : K) = I := units.ext_iff end instance principal_ideals.normal : (to_principal_ideal R K).range.normal := subgroup.normal_of_comm _ section variables (R K) /-- The ideal class group of `R` in a field of fractions `K` is the group of invertible fractional ideals modulo the principal ideals. -/ @[derive(comm_group)] def class_group := quotient_group.quotient (to_principal_ideal R K).range instance : inhabited (class_group R K) := ⟨1⟩ variables {R} [is_domain R] /-- Send a nonzero integral ideal to an invertible fractional ideal. -/ @[simps] noncomputable def fractional_ideal.mk0 [is_dedekind_domain R] : (ideal R)⁰ →* units (fractional_ideal R⁰ K) := { to_fun := λ I, units.mk0 I ((fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl R⁰)).mpr (mem_non_zero_divisors_iff_ne_zero.mp I.2)), map_one' := by simp, map_mul' := λ x y, by simp } /-- Send a nonzero ideal to the corresponding class in the class group. -/ @[simps] noncomputable def class_group.mk0 [is_dedekind_domain R] : (ideal R)⁰ →* class_group R K := (quotient_group.mk' _).comp (fractional_ideal.mk0 K) variables {K} lemma quotient_group.mk'_eq_mk' {G : Type*} [group G] {N : subgroup G} [hN : N.normal] {x y : G} : quotient_group.mk' N x = quotient_group.mk' N y ↔ ∃ z ∈ N, x * z = y := (@quotient.eq _ (quotient_group.left_rel _) _ _).trans ⟨λ (h : x⁻¹ * y ∈ N), ⟨_, h, by rw [← mul_assoc, mul_right_inv, one_mul]⟩, λ ⟨z, z_mem, eq_y⟩, by { rw ← eq_y, show x⁻¹ * (x * z) ∈ N, rwa [← mul_assoc, mul_left_inv, one_mul] }⟩ lemma class_group.mk0_eq_mk0_iff_exists_fraction_ring [is_dedekind_domain R] {I J : (ideal R)⁰} : class_group.mk0 K I = class_group.mk0 K J ↔ ∃ (x ≠ (0 : K)), span_singleton R⁰ x * I = J := begin simp only [class_group.mk0, monoid_hom.comp_apply, quotient_group.mk'_eq_mk'], split, { rintros ⟨_, ⟨x, rfl⟩, hx⟩, refine ⟨x, x.ne_zero, _⟩, simpa only [mul_comm, coe_mk0, monoid_hom.to_fun_eq_coe, coe_to_principal_ideal, units.coe_mul] using congr_arg (coe : _ → fractional_ideal R⁰ K) hx }, { rintros ⟨x, hx, eq_J⟩, refine ⟨_, ⟨units.mk0 x hx, rfl⟩, units.ext _⟩, simpa only [fractional_ideal.mk0_apply, units.coe_mk0, mul_comm, coe_to_principal_ideal, coe_coe, units.coe_mul] using eq_J } end lemma class_group.mk0_eq_mk0_iff [is_dedekind_domain R] {I J : (ideal R)⁰} : class_group.mk0 K I = class_group.mk0 K J ↔ ∃ (x y : R) (hx : x ≠ 0) (hy : y ≠ 0), ideal.span {x} * (I : ideal R) = ideal.span {y} * J := begin refine class_group.mk0_eq_mk0_iff_exists_fraction_ring.trans ⟨_, _⟩, { rintros ⟨z, hz, h⟩, obtain ⟨x, ⟨y, hy⟩, rfl⟩ := is_localization.mk'_surjective R⁰ z, refine ⟨x, y, _, mem_non_zero_divisors_iff_ne_zero.mp hy, _⟩, { rintro hx, apply hz, rw [hx, is_fraction_ring.mk'_eq_div, (algebra_map R K).map_zero, zero_div] }, { exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy).mp h } }, { rintros ⟨x, y, hx, hy, h⟩, have hy' : y ∈ R⁰ := mem_non_zero_divisors_iff_ne_zero.mpr hy, refine ⟨is_localization.mk' K x ⟨y, hy'⟩, _, _⟩, { contrapose! hx, rwa [is_localization.mk'_eq_iff_eq_mul, zero_mul, ← (algebra_map R K).map_zero, (is_fraction_ring.injective R K).eq_iff] at hx }, { exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy').mpr h } }, end lemma class_group.mk0_surjective [is_dedekind_domain R] : function.surjective (class_group.mk0 K : (ideal R)⁰ → class_group R K) := begin rintros ⟨I⟩, obtain ⟨a, a_ne_zero', ha⟩ := I.1.2, have a_ne_zero := mem_non_zero_divisors_iff_ne_zero.mp a_ne_zero', have fa_ne_zero : (algebra_map R K) a ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors a_ne_zero', refine ⟨⟨{ carrier := { x | (algebra_map R K a)⁻¹ * algebra_map R K x ∈ I.1 }, .. }, _⟩, _⟩, { simp only [ring_hom.map_zero, set.mem_set_of_eq, mul_zero, ring_hom.map_mul], exact submodule.zero_mem I }, { simp only [ring_hom.map_add, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add], exact λ _ _ ha hb, submodule.add_mem I ha hb }, { intros c _ hb, simp only [smul_eq_mul, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add, mul_left_comm ((algebra_map R K) a)⁻¹], rw ← algebra.smul_def c, exact submodule.smul_mem I c hb }, { rw [mem_non_zero_divisors_iff_ne_zero, submodule.zero_eq_bot, submodule.ne_bot_iff], obtain ⟨x, x_ne, x_mem⟩ := exists_ne_zero_mem_is_integer I.ne_zero, refine ⟨a * x, _, mul_ne_zero a_ne_zero x_ne⟩, change ((algebra_map R K) a)⁻¹ * (algebra_map R K) (a * x) ∈ I.1, rwa [ring_hom.map_mul, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] }, { symmetry, apply quotient.sound, refine ⟨units.mk0 (algebra_map R K a) fa_ne_zero, _⟩, apply @mul_left_cancel _ _ I, rw [← mul_assoc, mul_right_inv, one_mul, eq_comm, mul_comm I], apply units.ext, simp only [monoid_hom.coe_mk, subtype.coe_mk, ring_hom.map_mul, coe_coe, units.coe_mul, coe_to_principal_ideal, coe_mk0, fractional_ideal.eq_span_singleton_mul], split, { intros zJ' hzJ', obtain ⟨zJ, hzJ : (algebra_map R K a)⁻¹ * algebra_map R K zJ ∈ ↑I, rfl⟩ := (mem_coe_ideal R⁰).mp hzJ', refine ⟨_, hzJ, _⟩, rw [← mul_assoc, mul_inv_cancel fa_ne_zero, one_mul] }, { intros zI' hzI', obtain ⟨y, hy⟩ := ha zI' hzI', rw [← algebra.smul_def, fractional_ideal.mk0_apply, coe_mk0, coe_coe, mem_coe_ideal], refine ⟨y, _, hy⟩, show (algebra_map R K a)⁻¹ * algebra_map R K y ∈ (I : fractional_ideal R⁰ K), rwa [hy, algebra.smul_def, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] } } end end lemma class_group.mk_eq_one_iff {I : units (fractional_ideal R⁰ K)} : quotient_group.mk' (to_principal_ideal R K).range I = 1 ↔ (I : submodule R K).is_principal := begin rw [← (quotient_group.mk' _).map_one, eq_comm, quotient_group.mk'_eq_mk'], simp only [exists_prop, one_mul, exists_eq_right, to_principal_ideal_eq_iff, monoid_hom.mem_range, coe_coe], refine ⟨λ ⟨x, hx⟩, ⟨⟨x, by rw [← hx, coe_span_singleton]⟩⟩, _⟩, unfreezingI { intros hI }, obtain ⟨x, hx⟩ := @submodule.is_principal.principal _ _ _ _ _ _ hI, have hx' : (I : fractional_ideal R⁰ K) = span_singleton R⁰ x, { apply subtype.coe_injective, rw [hx, coe_span_singleton] }, refine ⟨units.mk0 x _, _⟩, { intro x_eq, apply units.ne_zero I, simp [hx', x_eq] }, simp [hx'] end variables [is_domain R] lemma class_group.mk0_eq_one_iff [is_dedekind_domain R] {I : ideal R} (hI : I ∈ (ideal R)⁰) : class_group.mk0 K ⟨I, hI⟩ = 1 ↔ I.is_principal := class_group.mk_eq_one_iff.trans (coe_submodule_is_principal R K) /-- The class group of principal ideal domain is finite (in fact a singleton). TODO: generalize to Dedekind domains -/ instance [is_principal_ideal_ring R] : fintype (class_group R K) := { elems := {1}, complete := begin rintros ⟨I⟩, rw [finset.mem_singleton], exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal R⁰ K).is_principal end } /-- The class number of a principal ideal domain is `1`. -/ lemma card_class_group_eq_one [is_principal_ideal_ring R] : fintype.card (class_group R K) = 1 := begin rw fintype.card_eq_one_iff, use 1, rintros ⟨I⟩, exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal R⁰ K).is_principal end /-- The class number is `1` iff the ring of integers is a principal ideal domain. -/ lemma card_class_group_eq_one_iff [is_dedekind_domain R] [fintype (class_group R K)] : fintype.card (class_group R K) = 1 ↔ is_principal_ideal_ring R := begin split, swap, { introsI, convert card_class_group_eq_one, assumption, assumption, }, rw fintype.card_eq_one_iff, rintros ⟨I, hI⟩, have eq_one : ∀ J : class_group R K, J = 1 := λ J, trans (hI J) (hI 1).symm, refine ⟨λ I, _⟩, by_cases hI : I = ⊥, { rw hI, exact bot_is_principal }, exact (class_group.mk0_eq_one_iff (mem_non_zero_divisors_iff_ne_zero.mpr hI)).mp (eq_one _), end
c9bfe63ba1cb1481d20c50dff1a503697ac0369e
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/function/strongly_measurable/basic.lean
be7925460e9af9410f6caa3ebe4ee9bd074d7838
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
87,458
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import analysis.normed_space.bounded_linear_maps import topology.metric_space.metrizable import measure_theory.function.simple_func_dense /-! # Strongly measurable and finitely strongly measurable functions A function `f` is said to be strongly measurable if `f` is the sequential limit of simple functions. It is said to be finitely strongly measurable with respect to a measure `μ` if the supports of those simple functions have finite measure. We also provide almost everywhere versions of these notions. Almost everywhere strongly measurable functions form the largest class of functions that can be integrated using the Bochner integral. If the target space has a second countable topology, strongly measurable and measurable are equivalent. If the measure is sigma-finite, strongly measurable and finitely strongly measurable are equivalent. The main property of finitely strongly measurable functions is `fin_strongly_measurable.exists_set_sigma_finite`: there exists a measurable set `t` such that the function is supported on `t` and `μ.restrict t` is sigma-finite. As a consequence, we can prove some results for those functions as if the measure was sigma-finite. ## Main definitions * `strongly_measurable f`: `f : α → β` is the limit of a sequence `fs : ℕ → simple_func α β`. * `fin_strongly_measurable f μ`: `f : α → β` is the limit of a sequence `fs : ℕ → simple_func α β` such that for all `n ∈ ℕ`, the measure of the support of `fs n` is finite. * `ae_strongly_measurable f μ`: `f` is almost everywhere equal to a `strongly_measurable` function. * `ae_fin_strongly_measurable f μ`: `f` is almost everywhere equal to a `fin_strongly_measurable` function. * `ae_fin_strongly_measurable.sigma_finite_set`: a measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `μ.restrict t` is sigma-finite. ## Main statements * `ae_fin_strongly_measurable.exists_set_sigma_finite`: there exists a measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `μ.restrict t` is sigma-finite. We provide a solid API for strongly measurable functions, and for almost everywhere strongly measurable functions, as a basis for the Bochner integral. ## References * Hytönen, Tuomas, Jan Van Neerven, Mark Veraar, and Lutz Weis. Analysis in Banach spaces. Springer, 2016. -/ open measure_theory filter topological_space function set measure_theory.measure open_locale ennreal topological_space measure_theory nnreal big_operators /-- The typeclass `second_countable_topology_either α β` registers the fact that at least one of the two spaces has second countable topology. This is the right assumption to ensure that continuous maps from `α` to `β` are strongly measurable. -/ class second_countable_topology_either (α β : Type*) [topological_space α] [topological_space β] : Prop := (out : second_countable_topology α ∨ second_countable_topology β) @[priority 100] instance second_countable_topology_either_of_left (α β : Type*) [topological_space α] [topological_space β] [second_countable_topology α] : second_countable_topology_either α β := { out := or.inl (by apply_instance) } @[priority 100] instance second_countable_topology_either_of_right (α β : Type*) [topological_space α] [topological_space β] [second_countable_topology β] : second_countable_topology_either α β := { out := or.inr (by apply_instance) } variables {α β γ ι : Type*} [countable ι] namespace measure_theory local infixr ` →ₛ `:25 := simple_func section definitions variable [topological_space β] /-- A function is `strongly_measurable` if it is the limit of simple functions. -/ def strongly_measurable [measurable_space α] (f : α → β) : Prop := ∃ fs : ℕ → α →ₛ β, ∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x)) localized "notation (name := strongly_measurable_of) `strongly_measurable[` m `]` := @measure_theory.strongly_measurable _ _ _ m" in measure_theory /-- A function is `fin_strongly_measurable` with respect to a measure if it is the limit of simple functions with support with finite measure. -/ def fin_strongly_measurable [has_zero β] {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ fs : ℕ → α →ₛ β, (∀ n, μ (support (fs n)) < ∞) ∧ (∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x))) /-- A function is `ae_strongly_measurable` with respect to a measure `μ` if it is almost everywhere equal to the limit of a sequence of simple functions. -/ def ae_strongly_measurable {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g, strongly_measurable g ∧ f =ᵐ[μ] g /-- A function is `ae_fin_strongly_measurable` with respect to a measure if it is almost everywhere equal to the limit of a sequence of simple functions with support with finite measure. -/ def ae_fin_strongly_measurable [has_zero β] {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g, fin_strongly_measurable g μ ∧ f =ᵐ[μ] g end definitions open_locale measure_theory /-! ## Strongly measurable functions -/ lemma strongly_measurable.ae_strongly_measurable {α β} {m0 : measurable_space α} [topological_space β] {f : α → β} {μ : measure α} (hf : strongly_measurable f) : ae_strongly_measurable f μ := ⟨f, hf, eventually_eq.refl _ _⟩ @[simp] lemma subsingleton.strongly_measurable {α β} [measurable_space α] [topological_space β] [subsingleton β] (f : α → β) : strongly_measurable f := begin let f_sf : α →ₛ β := ⟨f, λ x, _, set.subsingleton.finite set.subsingleton_of_subsingleton⟩, { exact ⟨λ n, f_sf, λ x, tendsto_const_nhds⟩, }, { have h_univ : f ⁻¹' {x} = set.univ, by { ext1 y, simp, }, rw h_univ, exact measurable_set.univ, }, end lemma simple_func.strongly_measurable {α β} {m : measurable_space α} [topological_space β] (f : α →ₛ β) : strongly_measurable f := ⟨λ _, f, λ x, tendsto_const_nhds⟩ lemma strongly_measurable_of_is_empty [is_empty α] {m : measurable_space α} [topological_space β] (f : α → β) : strongly_measurable f := ⟨λ n, simple_func.of_is_empty, is_empty_elim⟩ lemma strongly_measurable_const {α β} {m : measurable_space α} [topological_space β] {b : β} : strongly_measurable (λ a : α, b) := ⟨λ n, simple_func.const α b, λ a, tendsto_const_nhds⟩ @[to_additive] lemma strongly_measurable_one {α β} {m : measurable_space α} [topological_space β] [has_one β] : strongly_measurable (1 : α → β) := @strongly_measurable_const _ _ _ _ 1 /-- A version of `strongly_measurable_const` that assumes `f x = f y` for all `x, y`. This version works for functions between empty types. -/ lemma strongly_measurable_const' {α β} {m : measurable_space α} [topological_space β] {f : α → β} (hf : ∀ x y, f x = f y) : strongly_measurable f := begin casesI is_empty_or_nonempty α, { exact strongly_measurable_of_is_empty f }, { convert strongly_measurable_const, exact funext (λ x, hf x h.some) } end @[simp] lemma subsingleton.strongly_measurable' {α β} [measurable_space α] [topological_space β] [subsingleton α] (f : α → β) : strongly_measurable f := strongly_measurable_const' (λ x y, by rw subsingleton.elim x y) namespace strongly_measurable variables {f g : α → β} section basic_properties_in_any_topological_space variables [topological_space β] /-- A sequence of simple functions such that `∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x))`. That property is given by `strongly_measurable.tendsto_approx`. -/ protected noncomputable def approx {m : measurable_space α} (hf : strongly_measurable f) : ℕ → α →ₛ β := hf.some protected lemma tendsto_approx {m : measurable_space α} (hf : strongly_measurable f) : ∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x)) := hf.some_spec /-- Similar to `strongly_measurable.approx`, but enforces that the norm of every function in the sequence is less than `c` everywhere. If `‖f x‖ ≤ c` this sequence of simple functions verifies `tendsto (λ n, hf.approx_bounded n x) at_top (𝓝 (f x))`. -/ noncomputable def approx_bounded {m : measurable_space α} [has_norm β] [has_smul ℝ β] (hf : strongly_measurable f) (c : ℝ) : ℕ → simple_func α β := λ n, (hf.approx n).map (λ x, (min 1 (c / ‖x‖)) • x) lemma tendsto_approx_bounded_of_norm_le {β} {f : α → β} [normed_add_comm_group β] [normed_space ℝ β] {m : measurable_space α} (hf : strongly_measurable[m] f) {c : ℝ} {x : α} (hfx : ‖f x‖ ≤ c) : tendsto (λ n, hf.approx_bounded c n x) at_top (𝓝 (f x)) := begin have h_tendsto := hf.tendsto_approx x, simp only [strongly_measurable.approx_bounded, simple_func.coe_map, function.comp_app], by_cases hfx0 : ‖f x‖ = 0, { rw norm_eq_zero at hfx0, rw hfx0 at h_tendsto ⊢, have h_tendsto_norm : tendsto (λ n, ‖hf.approx n x‖) at_top (𝓝 0), { convert h_tendsto.norm, rw norm_zero, }, refine squeeze_zero_norm (λ n, _) h_tendsto_norm, calc ‖min 1 (c / ‖hf.approx n x‖) • hf.approx n x‖ = ‖min 1 (c / ‖hf.approx n x‖)‖ * ‖hf.approx n x‖ : norm_smul _ _ ... ≤ ‖(1 : ℝ)‖ * ‖hf.approx n x‖ : begin refine mul_le_mul_of_nonneg_right _ (norm_nonneg _), rw [norm_one, real.norm_of_nonneg], { exact min_le_left _ _, }, { exact le_min zero_le_one (div_nonneg ((norm_nonneg _).trans hfx) (norm_nonneg _)), }, end ... = ‖hf.approx n x‖ : by rw [norm_one, one_mul], }, rw ← one_smul ℝ (f x), refine tendsto.smul _ h_tendsto, have : min 1 (c / ‖f x‖) = 1, { rw [min_eq_left_iff, one_le_div (lt_of_le_of_ne (norm_nonneg _) (ne.symm hfx0))], exact hfx, }, nth_rewrite 0 this.symm, refine tendsto.min tendsto_const_nhds _, refine tendsto.div tendsto_const_nhds h_tendsto.norm hfx0, end lemma tendsto_approx_bounded_ae {β} {f : α → β} [normed_add_comm_group β] [normed_space ℝ β] {m m0 : measurable_space α} {μ : measure α} (hf : strongly_measurable[m] f) {c : ℝ} (hf_bound : ∀ᵐ x ∂μ, ‖f x‖ ≤ c) : ∀ᵐ x ∂μ, tendsto (λ n, hf.approx_bounded c n x) at_top (𝓝 (f x)) := by filter_upwards [hf_bound] with x hfx using tendsto_approx_bounded_of_norm_le hf hfx lemma norm_approx_bounded_le {β} {f : α → β} [seminormed_add_comm_group β] [normed_space ℝ β] {m : measurable_space α} {c : ℝ} (hf : strongly_measurable[m] f) (hc : 0 ≤ c) (n : ℕ) (x : α) : ‖hf.approx_bounded c n x‖ ≤ c := begin simp only [strongly_measurable.approx_bounded, simple_func.coe_map, function.comp_app], refine (norm_smul _ _).le.trans _, by_cases h0 : ‖hf.approx n x‖ = 0, { simp only [h0, div_zero, min_eq_right, zero_le_one, norm_zero, mul_zero], exact hc, }, cases le_total (‖hf.approx n x‖) c, { rw min_eq_left _, { simpa only [norm_one, one_mul] using h, }, { rwa one_le_div (lt_of_le_of_ne (norm_nonneg _) (ne.symm h0)), }, }, { rw min_eq_right _, { rw [norm_div, norm_norm, mul_comm, mul_div, div_eq_mul_inv, mul_comm, ← mul_assoc, inv_mul_cancel h0, one_mul, real.norm_of_nonneg hc], }, { rwa div_le_one (lt_of_le_of_ne (norm_nonneg _) (ne.symm h0)), }, }, end lemma _root_.strongly_measurable_bot_iff [nonempty β] [t2_space β] : strongly_measurable[⊥] f ↔ ∃ c, f = λ _, c := begin casesI is_empty_or_nonempty α with hα hα, { simp only [subsingleton.strongly_measurable', eq_iff_true_of_subsingleton, exists_const], }, refine ⟨λ hf, _, λ hf_eq, _⟩, { refine ⟨f hα.some, _⟩, let fs := hf.approx, have h_fs_tendsto : ∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x)) := hf.tendsto_approx, have : ∀ n, ∃ c, ∀ x, fs n x = c := λ n, simple_func.simple_func_bot (fs n), let cs := λ n, (this n).some, have h_cs_eq : ∀ n, ⇑(fs n) = (λ x, cs n) := λ n, funext (this n).some_spec, simp_rw h_cs_eq at h_fs_tendsto, have h_tendsto : tendsto cs at_top (𝓝 (f hα.some)) := h_fs_tendsto hα.some, ext1 x, exact tendsto_nhds_unique (h_fs_tendsto x) h_tendsto, }, { obtain ⟨c, rfl⟩ := hf_eq, exact strongly_measurable_const, }, end end basic_properties_in_any_topological_space lemma fin_strongly_measurable_of_set_sigma_finite [topological_space β] [has_zero β] {m : measurable_space α} {μ : measure α} (hf_meas : strongly_measurable f) {t : set α} (ht : measurable_set t) (hft_zero : ∀ x ∈ tᶜ, f x = 0) (htμ : sigma_finite (μ.restrict t)) : fin_strongly_measurable f μ := begin haveI : sigma_finite (μ.restrict t) := htμ, let S := spanning_sets (μ.restrict t), have hS_meas : ∀ n, measurable_set (S n), from measurable_spanning_sets (μ.restrict t), let f_approx := hf_meas.approx, let fs := λ n, simple_func.restrict (f_approx n) (S n ∩ t), have h_fs_t_compl : ∀ n, ∀ x ∉ t, fs n x = 0, { intros n x hxt, rw simple_func.restrict_apply _ ((hS_meas n).inter ht), refine set.indicator_of_not_mem _ _, simp [hxt], }, refine ⟨fs, _, λ x, _⟩, { simp_rw simple_func.support_eq, refine λ n, (measure_bUnion_finset_le _ _).trans_lt _, refine ennreal.sum_lt_top_iff.mpr (λ y hy, _), rw simple_func.restrict_preimage_singleton _ ((hS_meas n).inter ht), swap, { rw finset.mem_filter at hy, exact hy.2, }, refine (measure_mono (set.inter_subset_left _ _)).trans_lt _, have h_lt_top := measure_spanning_sets_lt_top (μ.restrict t) n, rwa measure.restrict_apply' ht at h_lt_top, }, { by_cases hxt : x ∈ t, swap, { rw [funext (λ n, h_fs_t_compl n x hxt), hft_zero x hxt], exact tendsto_const_nhds, }, have h : tendsto (λ n, (f_approx n) x) at_top (𝓝 (f x)), from hf_meas.tendsto_approx x, obtain ⟨n₁, hn₁⟩ : ∃ n, ∀ m, n ≤ m → fs m x = f_approx m x, { obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → x ∈ S m ∩ t, { rsuffices ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → x ∈ S m, { exact ⟨n, λ m hnm, set.mem_inter (hn m hnm) hxt⟩, }, rsuffices ⟨n, hn⟩ : ∃ n, x ∈ S n, { exact ⟨n, λ m hnm, monotone_spanning_sets (μ.restrict t) hnm hn⟩, }, rw [← set.mem_Union, Union_spanning_sets (μ.restrict t)], trivial, }, refine ⟨n, λ m hnm, _⟩, simp_rw [fs, simple_func.restrict_apply _ ((hS_meas m).inter ht), set.indicator_of_mem (hn m hnm)], }, rw tendsto_at_top' at h ⊢, intros s hs, obtain ⟨n₂, hn₂⟩ := h s hs, refine ⟨max n₁ n₂, λ m hm, _⟩, rw hn₁ m ((le_max_left _ _).trans hm.le), exact hn₂ m ((le_max_right _ _).trans hm.le), }, end /-- If the measure is sigma-finite, all strongly measurable functions are `fin_strongly_measurable`. -/ protected lemma fin_strongly_measurable [topological_space β] [has_zero β] {m0 : measurable_space α} (hf : strongly_measurable f) (μ : measure α) [sigma_finite μ] : fin_strongly_measurable f μ := hf.fin_strongly_measurable_of_set_sigma_finite measurable_set.univ (by simp) (by rwa measure.restrict_univ) /-- A strongly measurable function is measurable. -/ protected lemma measurable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : strongly_measurable f) : measurable f := measurable_of_tendsto_metrizable (λ n, (hf.approx n).measurable) (tendsto_pi_nhds.mpr hf.tendsto_approx) /-- A strongly measurable function is almost everywhere measurable. -/ protected lemma ae_measurable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] {μ : measure α} (hf : strongly_measurable f) : ae_measurable f μ := hf.measurable.ae_measurable lemma _root_.continuous.comp_strongly_measurable {m : measurable_space α} [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} (hg : continuous g) (hf : strongly_measurable f) : strongly_measurable (λ x, g (f x)) := ⟨λ n, simple_func.map g (hf.approx n), λ x, (hg.tendsto _).comp (hf.tendsto_approx x)⟩ @[to_additive] lemma measurable_set_mul_support {m : measurable_space α} [has_one β] [topological_space β] [metrizable_space β] (hf : strongly_measurable f) : measurable_set (mul_support f) := by { borelize β, exact measurable_set_mul_support hf.measurable } protected lemma mono {m m' : measurable_space α} [topological_space β] (hf : strongly_measurable[m'] f) (h_mono : m' ≤ m) : strongly_measurable[m] f := begin let f_approx : ℕ → @simple_func α m β := λ n, { to_fun := hf.approx n, measurable_set_fiber' := λ x, h_mono _ (simple_func.measurable_set_fiber' _ x), finite_range' := simple_func.finite_range (hf.approx n) }, exact ⟨f_approx, hf.tendsto_approx⟩, end protected lemma prod_mk {m : measurable_space α} [topological_space β] [topological_space γ] {f : α → β} {g : α → γ} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, (f x, g x)) := begin refine ⟨λ n, simple_func.pair (hf.approx n) (hg.approx n), λ x, _⟩, rw nhds_prod_eq, exact tendsto.prod_mk (hf.tendsto_approx x) (hg.tendsto_approx x), end lemma comp_measurable [topological_space β] {m : measurable_space α} {m' : measurable_space γ} {f : α → β} {g : γ → α} (hf : strongly_measurable f) (hg : measurable g) : strongly_measurable (f ∘ g) := ⟨λ n, simple_func.comp (hf.approx n) g hg, λ x, hf.tendsto_approx (g x)⟩ lemma of_uncurry_left [topological_space β] {mα : measurable_space α} {mγ : measurable_space γ} {f : α → γ → β} (hf : strongly_measurable (uncurry f)) {x : α} : strongly_measurable (f x) := hf.comp_measurable measurable_prod_mk_left lemma of_uncurry_right [topological_space β] {mα : measurable_space α} {mγ : measurable_space γ} {f : α → γ → β} (hf : strongly_measurable (uncurry f)) {y : γ} : strongly_measurable (λ x, f x y) := hf.comp_measurable measurable_prod_mk_right section arithmetic variables {mα : measurable_space α} [topological_space β] include mα @[to_additive] protected lemma mul [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f * g) := ⟨λ n, hf.approx n * hg.approx n, λ x, (hf.tendsto_approx x).mul (hg.tendsto_approx x)⟩ @[to_additive] lemma mul_const [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, f x * c) := hf.mul strongly_measurable_const @[to_additive] lemma const_mul [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, c * f x) := strongly_measurable_const.mul hf @[to_additive] protected lemma inv [group β] [topological_group β] (hf : strongly_measurable f) : strongly_measurable f⁻¹ := ⟨λ n, (hf.approx n)⁻¹, λ x, (hf.tendsto_approx x).inv⟩ @[to_additive] protected lemma div [has_div β] [has_continuous_div β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f / g) := ⟨λ n, hf.approx n / hg.approx n, λ x, (hf.tendsto_approx x).div' (hg.tendsto_approx x)⟩ @[to_additive] protected lemma smul {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} {g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, f x • g x) := continuous_smul.comp_strongly_measurable (hf.prod_mk hg) protected lemma const_smul {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : strongly_measurable f) (c : 𝕜) : strongly_measurable (c • f) := ⟨λ n, c • (hf.approx n), λ x, (hf.tendsto_approx x).const_smul c⟩ protected lemma const_smul' {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : strongly_measurable f) (c : 𝕜) : strongly_measurable (λ x, c • (f x)) := hf.const_smul c @[to_additive] protected lemma smul_const {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, f x • c) := continuous_smul.comp_strongly_measurable (hf.prod_mk strongly_measurable_const) end arithmetic section mul_action variables [topological_space β] {G : Type*} [group G] [mul_action G β] [has_continuous_const_smul G β] lemma _root_.strongly_measurable_const_smul_iff {m : measurable_space α} (c : G) : strongly_measurable (λ x, c • f x) ↔ strongly_measurable f := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ variables {G₀ : Type*} [group_with_zero G₀] [mul_action G₀ β] [has_continuous_const_smul G₀ β] lemma _root_.strongly_measurable_const_smul_iff₀ {m : measurable_space α} {c : G₀} (hc : c ≠ 0) : strongly_measurable (λ x, c • f x) ↔ strongly_measurable f := begin refine ⟨λ h, _, λ h, h.const_smul c⟩, convert h.const_smul' c⁻¹, simp [smul_smul, inv_mul_cancel hc] end end mul_action section order variables [measurable_space α] [topological_space β] open filter open_locale filter protected lemma sup [has_sup β] [has_continuous_sup β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f ⊔ g) := ⟨λ n, hf.approx n ⊔ hg.approx n, λ x, (hf.tendsto_approx x).sup_right_nhds (hg.tendsto_approx x)⟩ protected lemma inf [has_inf β] [has_continuous_inf β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f ⊓ g) := ⟨λ n, hf.approx n ⊓ hg.approx n, λ x, (hf.tendsto_approx x).inf_right_nhds (hg.tendsto_approx x)⟩ end order /-! ### Big operators: `∏` and `∑` -/ section monoid variables {M : Type*} [monoid M] [topological_space M] [has_continuous_mul M] {m : measurable_space α} include m @[to_additive] lemma _root_.list.strongly_measurable_prod' (l : list (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable l.prod := begin induction l with f l ihl, { exact strongly_measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive] lemma _root_.list.strongly_measurable_prod (l : list (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable (λ x, (l.map (λ f : α → M, f x)).prod) := by simpa only [← pi.list_prod_apply] using l.strongly_measurable_prod' hl end monoid section comm_monoid variables {M : Type*} [comm_monoid M] [topological_space M] [has_continuous_mul M] {m : measurable_space α} include m @[to_additive] lemma _root_.multiset.strongly_measurable_prod' (l : multiset (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable l.prod := by { rcases l with ⟨l⟩, simpa using l.strongly_measurable_prod' (by simpa using hl) } @[to_additive] lemma _root_.multiset.strongly_measurable_prod (s : multiset (α → M)) (hs : ∀ f ∈ s, strongly_measurable f) : strongly_measurable (λ x, (s.map (λ f : α → M, f x)).prod) := by simpa only [← pi.multiset_prod_apply] using s.strongly_measurable_prod' hs @[to_additive] lemma _root_.finset.strongly_measurable_prod' {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, strongly_measurable (f i)) : strongly_measurable (∏ i in s, f i) := finset.prod_induction _ _ (λ a b ha hb, ha.mul hb) (@strongly_measurable_one α M _ _ _) hf @[to_additive] lemma _root_.finset.strongly_measurable_prod {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, strongly_measurable (f i)) : strongly_measurable (λ a, ∏ i in s, f i a) := by simpa only [← finset.prod_apply] using s.strongly_measurable_prod' hf end comm_monoid /-- The range of a strongly measurable function is separable. -/ lemma is_separable_range {m : measurable_space α} [topological_space β] (hf : strongly_measurable f) : topological_space.is_separable (range f) := begin have : is_separable (closure (⋃ n, range (hf.approx n))) := (is_separable_Union (λ n, (simple_func.finite_range (hf.approx n)).is_separable)).closure, apply this.mono, rintros _ ⟨x, rfl⟩, apply mem_closure_of_tendsto (hf.tendsto_approx x), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact mem_range_self _ end lemma separable_space_range_union_singleton {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] (hf : strongly_measurable f) {b : β} : separable_space (range f ∪ {b} : set β) := begin letI := pseudo_metrizable_space_pseudo_metric β, exact (hf.is_separable_range.union (finite_singleton _).is_separable).separable_space end section second_countable_strongly_measurable variables {mα : measurable_space α} [measurable_space β] include mα /-- In a space with second countable topology, measurable implies strongly measurable. -/ lemma _root_.measurable.strongly_measurable [topological_space β] [pseudo_metrizable_space β] [second_countable_topology β] [opens_measurable_space β] (hf : measurable f) : strongly_measurable f := begin letI := pseudo_metrizable_space_pseudo_metric β, rcases is_empty_or_nonempty β; resetI, { exact subsingleton.strongly_measurable f, }, { inhabit β, exact ⟨simple_func.approx_on f hf set.univ default (set.mem_univ _), λ x, simple_func.tendsto_approx_on hf (set.mem_univ _) (by simp)⟩, }, end /-- In a space with second countable topology, strongly measurable and measurable are equivalent. -/ lemma _root_.strongly_measurable_iff_measurable [topological_space β] [metrizable_space β] [borel_space β] [second_countable_topology β] : strongly_measurable f ↔ measurable f := ⟨λ h, h.measurable, λ h, measurable.strongly_measurable h⟩ lemma _root_.strongly_measurable_id [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] [second_countable_topology α] : strongly_measurable (id : α → α) := measurable_id.strongly_measurable end second_countable_strongly_measurable /-- A function is strongly measurable if and only if it is measurable and has separable range. -/ theorem _root_.strongly_measurable_iff_measurable_separable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] : strongly_measurable f ↔ (measurable f ∧ is_separable (range f)) := begin refine ⟨λ H, ⟨H.measurable, H.is_separable_range⟩, _⟩, rintros ⟨H, H'⟩, letI := pseudo_metrizable_space_pseudo_metric β, let g := cod_restrict f (closure (range f)) (λ x, subset_closure (mem_range_self x)), have fg : f = (coe : closure (range f) → β) ∘ g, by { ext x, refl }, have T : measurable_embedding (coe : closure (range f) → β), { apply closed_embedding.measurable_embedding, exact closed_embedding_subtype_coe is_closed_closure }, have g_meas : measurable g, { rw fg at H, exact T.measurable_comp_iff.1 H }, haveI : second_countable_topology (closure (range f)), { suffices : separable_space (closure (range f)), by exactI uniform_space.second_countable_of_separable _, exact (is_separable.closure H').separable_space }, have g_smeas : strongly_measurable g := measurable.strongly_measurable g_meas, rw fg, exact continuous_subtype_coe.comp_strongly_measurable g_smeas, end /-- A continuous function is strongly measurable when either the source space or the target space is second-countable. -/ lemma _root_.continuous.strongly_measurable [measurable_space α] [topological_space α] [opens_measurable_space α] {β : Type*} [topological_space β] [pseudo_metrizable_space β] [h : second_countable_topology_either α β] {f : α → β} (hf : continuous f) : strongly_measurable f := begin borelize β, casesI h.out, { rw strongly_measurable_iff_measurable_separable, refine ⟨hf.measurable, _⟩, rw ← image_univ, exact (is_separable_of_separable_space univ).image hf }, { exact hf.measurable.strongly_measurable } end /-- If `g` is a topological embedding, then `f` is strongly measurable iff `g ∘ f` is. -/ lemma _root_.embedding.comp_strongly_measurable_iff {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [topological_space γ] [pseudo_metrizable_space γ] {g : β → γ} {f : α → β} (hg : embedding g) : strongly_measurable (λ x, g (f x)) ↔ strongly_measurable f := begin letI := pseudo_metrizable_space_pseudo_metric γ, borelize [β, γ], refine ⟨λ H, strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, λ H, hg.continuous.comp_strongly_measurable H⟩, { let G : β → range g := cod_restrict g (range g) mem_range_self, have hG : closed_embedding G := { closed_range := begin convert is_closed_univ, apply eq_univ_of_forall, rintros ⟨-, ⟨x, rfl⟩⟩, exact mem_range_self x end, .. hg.cod_restrict _ _ }, have : measurable (G ∘ f) := measurable.subtype_mk H.measurable, exact hG.measurable_embedding.measurable_comp_iff.1 this }, { have : is_separable (g ⁻¹' (range (g ∘ f))) := hg.is_separable_preimage H.is_separable_range, convert this, ext x, simp [hg.inj.eq_iff] } end /-- A sequential limit of strongly measurable functions is strongly measurable. -/ lemma _root_.strongly_measurable_of_tendsto {ι : Type*} {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] (u : filter ι) [ne_bot u] [is_countably_generated u] {f : ι → α → β} {g : α → β} (hf : ∀ i, strongly_measurable (f i)) (lim : tendsto f u (𝓝 g)) : strongly_measurable g := begin borelize β, refine strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, { exact measurable_of_tendsto_metrizable' u (λ i, (hf i).measurable) lim }, { rcases u.exists_seq_tendsto with ⟨v, hv⟩, have : is_separable (closure (⋃ i, range (f (v i)))) := (is_separable_Union (λ i, (hf (v i)).is_separable_range)).closure, apply this.mono, rintros _ ⟨x, rfl⟩, rw [tendsto_pi_nhds] at lim, apply mem_closure_of_tendsto ((lim x).comp hv), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact mem_range_self _ } end protected lemma piecewise {m : measurable_space α} [topological_space β] {s : set α} {_ : decidable_pred (∈ s)} (hs : measurable_set s) (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (set.piecewise s f g) := begin refine ⟨λ n, simple_func.piecewise s hs (hf.approx n) (hg.approx n), λ x, _⟩, by_cases hx : x ∈ s, { simpa [hx] using hf.tendsto_approx x }, { simpa [hx] using hg.tendsto_approx x }, end /-- this is slightly different from `strongly_measurable.piecewise`. It can be used to show `strongly_measurable (ite (x=0) 0 1)` by `exact strongly_measurable.ite (measurable_set_singleton 0) strongly_measurable_const strongly_measurable_const`, but replacing `strongly_measurable.ite` by `strongly_measurable.piecewise` in that example proof does not work. -/ protected lemma ite {m : measurable_space α} [topological_space β] {p : α → Prop} {_ : decidable_pred p} (hp : measurable_set {a : α | p a}) (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, ite (p x) (f x) (g x)) := strongly_measurable.piecewise hp hf hg lemma _root_.strongly_measurable_of_strongly_measurable_union_cover {m : measurable_space α} [topological_space β] {f : α → β} (s t : set α) (hs : measurable_set s) (ht : measurable_set t) (h : univ ⊆ s ∪ t) (hc : strongly_measurable (λ a : s, f a)) (hd : strongly_measurable (λ a : t, f a)) : strongly_measurable f := begin classical, let f : ℕ → α →ₛ β := λ n, { to_fun := λ x, if hx : x ∈ s then hc.approx n ⟨x, hx⟩ else hd.approx n ⟨x, by simpa [hx] using h (mem_univ x)⟩, measurable_set_fiber' := begin assume x, convert (hs.subtype_image ((hc.approx n).measurable_set_fiber x)).union ((ht.subtype_image ((hd.approx n).measurable_set_fiber x)).diff hs), ext1 y, simp only [mem_union, mem_preimage, mem_singleton_iff, mem_image, set_coe.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right, mem_diff], by_cases hy : y ∈ s, { rw dif_pos hy, simp only [hy, exists_true_left, not_true, and_false, or_false]}, { rw dif_neg hy, have A : y ∈ t, by simpa [hy] using h (mem_univ y), simp only [A, hy, false_or, is_empty.exists_iff, not_false_iff, and_true, exists_true_left] } end, finite_range' := begin apply ((hc.approx n).finite_range.union (hd.approx n).finite_range).subset, rintros - ⟨y, rfl⟩, dsimp, by_cases hy : y ∈ s, { left, rw dif_pos hy, exact mem_range_self _ }, { right, rw dif_neg hy, exact mem_range_self _ } end }, refine ⟨f, λ y, _⟩, by_cases hy : y ∈ s, { convert hc.tendsto_approx ⟨y, hy⟩ using 1, ext1 n, simp only [dif_pos hy, simple_func.apply_mk] }, { have A : y ∈ t, by simpa [hy] using h (mem_univ y), convert hd.tendsto_approx ⟨y, A⟩ using 1, ext1 n, simp only [dif_neg hy, simple_func.apply_mk] } end lemma _root_.strongly_measurable_of_restrict_of_restrict_compl {m : measurable_space α} [topological_space β] {f : α → β} {s : set α} (hs : measurable_set s) (h₁ : strongly_measurable (s.restrict f)) (h₂ : strongly_measurable (sᶜ.restrict f)) : strongly_measurable f := strongly_measurable_of_strongly_measurable_union_cover s sᶜ hs hs.compl (union_compl_self s).ge h₁ h₂ protected lemma indicator {m : measurable_space α} [topological_space β] [has_zero β] (hf : strongly_measurable f) {s : set α} (hs : measurable_set s) : strongly_measurable (s.indicator f) := hf.piecewise hs strongly_measurable_const protected lemma dist {m : measurable_space α} {β : Type*} [pseudo_metric_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, dist (f x) (g x)) := continuous_dist.comp_strongly_measurable (hf.prod_mk hg) protected lemma norm {m : measurable_space α} {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : strongly_measurable f) : strongly_measurable (λ x, ‖f x‖) := continuous_norm.comp_strongly_measurable hf protected lemma nnnorm {m : measurable_space α} {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : strongly_measurable f) : strongly_measurable (λ x, ‖f x‖₊) := continuous_nnnorm.comp_strongly_measurable hf protected lemma ennnorm {m : measurable_space α} {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : strongly_measurable f) : measurable (λ a, (‖f a‖₊ : ℝ≥0∞)) := (ennreal.continuous_coe.comp_strongly_measurable hf.nnnorm).measurable protected lemma real_to_nnreal {m : measurable_space α} {f : α → ℝ} (hf : strongly_measurable f) : strongly_measurable (λ x, (f x).to_nnreal) := continuous_real_to_nnreal.comp_strongly_measurable hf lemma _root_.measurable_embedding.strongly_measurable_extend {f : α → β} {g : α → γ} {g' : γ → β} {mα : measurable_space α} {mγ : measurable_space γ} [topological_space β] (hg : measurable_embedding g) (hf : strongly_measurable f) (hg' : strongly_measurable g') : strongly_measurable (function.extend g f g') := begin refine ⟨λ n, simple_func.extend (hf.approx n) g hg (hg'.approx n), _⟩, assume x, by_cases hx : ∃ y, g y = x, { rcases hx with ⟨y, rfl⟩, simpa only [simple_func.extend_apply, hg.injective, injective.extend_apply] using hf.tendsto_approx y }, { simpa only [hx, simple_func.extend_apply', not_false_iff, extend_apply'] using hg'.tendsto_approx x } end lemma _root_.measurable_embedding.exists_strongly_measurable_extend {f : α → β} {g : α → γ} {mα : measurable_space α} {mγ : measurable_space γ} [topological_space β] (hg : measurable_embedding g) (hf : strongly_measurable f) (hne : γ → nonempty β) : ∃ f' : γ → β, strongly_measurable f' ∧ f' ∘ g = f := ⟨function.extend g f (λ x, classical.choice (hne x)), hg.strongly_measurable_extend hf (strongly_measurable_const' $ λ _ _, rfl), funext $ λ x, hg.injective.extend_apply _ _ _⟩ lemma measurable_set_eq_fun {m : measurable_space α} {E} [topological_space E] [metrizable_space E] {f g : α → E} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {x | f x = g x} := begin borelize E × E, exact (hf.prod_mk hg).measurable is_closed_diagonal.measurable_set end lemma measurable_set_lt {m : measurable_space α} [topological_space β] [linear_order β] [order_closed_topology β] [pseudo_metrizable_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {a | f a < g a} := begin borelize β × β, exact (hf.prod_mk hg).measurable is_open_lt_prod.measurable_set end lemma measurable_set_le {m : measurable_space α} [topological_space β] [preorder β] [order_closed_topology β] [pseudo_metrizable_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {a | f a ≤ g a} := begin borelize β × β, exact (hf.prod_mk hg).measurable is_closed_le_prod.measurable_set end lemma strongly_measurable_in_set {m : measurable_space α} [topological_space β] [has_zero β] {s : set α} {f : α → β} (hs : measurable_set s) (hf : strongly_measurable f) (hf_zero : ∀ x ∉ s, f x = 0) : ∃ fs : ℕ → α →ₛ β, (∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x))) ∧ (∀ (x ∉ s) n, fs n x = 0) := begin let g_seq_s : ℕ → @simple_func α m β := λ n, (hf.approx n).restrict s, have hg_eq : ∀ x ∈ s, ∀ n, g_seq_s n x = hf.approx n x, { intros x hx n, rw [simple_func.coe_restrict _ hs, set.indicator_of_mem hx], }, have hg_zero : ∀ x ∉ s, ∀ n, g_seq_s n x = 0, { intros x hx n, rw [simple_func.coe_restrict _ hs, set.indicator_of_not_mem hx], }, refine ⟨g_seq_s, λ x, _, hg_zero⟩, by_cases hx : x ∈ s, { simp_rw hg_eq x hx, exact hf.tendsto_approx x, }, { simp_rw [hg_zero x hx, hf_zero x hx], exact tendsto_const_nhds, }, end /-- If the restriction to a set `s` of a σ-algebra `m` is included in the restriction to `s` of another σ-algebra `m₂` (hypothesis `hs`), the set `s` is `m` measurable and a function `f` supported on `s` is `m`-strongly-measurable, then `f` is also `m₂`-strongly-measurable. -/ lemma strongly_measurable_of_measurable_space_le_on {α E} {m m₂ : measurable_space α} [topological_space E] [has_zero E] {s : set α} {f : α → E} (hs_m : measurable_set[m] s) (hs : ∀ t, measurable_set[m] (s ∩ t) → measurable_set[m₂] (s ∩ t)) (hf : strongly_measurable[m] f) (hf_zero : ∀ x ∉ s, f x = 0) : strongly_measurable[m₂] f := begin have hs_m₂ : measurable_set[m₂] s, { rw ← set.inter_univ s, refine hs set.univ _, rwa [set.inter_univ], }, obtain ⟨g_seq_s, hg_seq_tendsto, hg_seq_zero⟩ := strongly_measurable_in_set hs_m hf hf_zero, let g_seq_s₂ : ℕ → @simple_func α m₂ E := λ n, { to_fun := g_seq_s n, measurable_set_fiber' := λ x, begin rw [← set.inter_univ ((g_seq_s n) ⁻¹' {x}), ← set.union_compl_self s, set.inter_union_distrib_left, set.inter_comm ((g_seq_s n) ⁻¹' {x})], refine measurable_set.union (hs _ (hs_m.inter _)) _, { exact @simple_func.measurable_set_fiber _ _ m _ _, }, by_cases hx : x = 0, { suffices : (g_seq_s n) ⁻¹' {x} ∩ sᶜ = sᶜ, by { rw this, exact hs_m₂.compl, }, ext1 y, rw [hx, set.mem_inter_iff, set.mem_preimage, set.mem_singleton_iff], exact ⟨λ h, h.2, λ h, ⟨hg_seq_zero y h n, h⟩⟩, }, { suffices : (g_seq_s n) ⁻¹' {x} ∩ sᶜ = ∅, by { rw this, exact measurable_set.empty, }, ext1 y, simp only [mem_inter_iff, mem_preimage, mem_singleton_iff, mem_compl_iff, mem_empty_iff_false, iff_false, not_and, not_not_mem], refine imp_of_not_imp_not _ _ (λ hys, _), rw hg_seq_zero y hys n, exact ne.symm hx, }, end, finite_range' := @simple_func.finite_range _ _ m (g_seq_s n), }, have hg_eq : ∀ x n, g_seq_s₂ n x = g_seq_s n x := λ x n, rfl, refine ⟨g_seq_s₂, λ x, _⟩, simp_rw hg_eq, exact hg_seq_tendsto x, end /-- If a function `f` is strongly measurable w.r.t. a sub-σ-algebra `m` and the measure is σ-finite on `m`, then there exists spanning measurable sets with finite measure on which `f` has bounded norm. In particular, `f` is integrable on each of those sets. -/ lemma exists_spanning_measurable_set_norm_le [seminormed_add_comm_group β] {m m0 : measurable_space α} (hm : m ≤ m0) (hf : strongly_measurable[m] f) (μ : measure α) [sigma_finite (μ.trim hm)] : ∃ s : ℕ → set α, (∀ n, measurable_set[m] (s n) ∧ μ (s n) < ∞ ∧ ∀ x ∈ s n, ‖f x‖ ≤ n) ∧ (⋃ i, s i) = set.univ := begin let sigma_finite_sets := spanning_sets (μ.trim hm), let norm_sets := λ (n : ℕ), {x | ‖f x‖ ≤ n}, have norm_sets_spanning : (⋃ n, norm_sets n) = set.univ, { ext1 x, simp only [set.mem_Union, set.mem_set_of_eq, set.mem_univ, iff_true], exact ⟨⌈‖f x‖⌉₊, nat.le_ceil (‖f x‖)⟩, }, let sets := λ n, sigma_finite_sets n ∩ norm_sets n, have h_meas : ∀ n, measurable_set[m] (sets n), { refine λ n, measurable_set.inter _ _, { exact measurable_spanning_sets (μ.trim hm) n, }, { exact hf.norm.measurable_set_le strongly_measurable_const, }, }, have h_finite : ∀ n, μ (sets n) < ∞, { refine λ n, (measure_mono (set.inter_subset_left _ _)).trans_lt _, exact (le_trim hm).trans_lt (measure_spanning_sets_lt_top (μ.trim hm) n), }, refine ⟨sets, λ n, ⟨h_meas n, h_finite n, _⟩, _⟩, { exact λ x hx, hx.2, }, { have : (⋃ i, sigma_finite_sets i ∩ norm_sets i) = (⋃ i, sigma_finite_sets i) ∩ (⋃ i, norm_sets i), { refine set.Union_inter_of_monotone (monotone_spanning_sets (μ.trim hm)) (λ i j hij x, _), simp only [norm_sets, set.mem_set_of_eq], refine λ hif, hif.trans _, exact_mod_cast hij, }, rw [this, norm_sets_spanning, Union_spanning_sets (μ.trim hm), set.inter_univ], }, end end strongly_measurable /-! ## Finitely strongly measurable functions -/ lemma fin_strongly_measurable_zero {α β} {m : measurable_space α} {μ : measure α} [has_zero β] [topological_space β] : fin_strongly_measurable (0 : α → β) μ := ⟨0, by simp only [pi.zero_apply, simple_func.coe_zero, support_zero', measure_empty, with_top.zero_lt_top, forall_const], λ n, tendsto_const_nhds⟩ namespace fin_strongly_measurable variables {m0 : measurable_space α} {μ : measure α} {f g : α → β} lemma ae_fin_strongly_measurable [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) : ae_fin_strongly_measurable f μ := ⟨f, hf, ae_eq_refl f⟩ section sequence variables [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) /-- A sequence of simple functions such that `∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x))` and `∀ n, μ (support (hf.approx n)) < ∞`. These properties are given by `fin_strongly_measurable.tendsto_approx` and `fin_strongly_measurable.fin_support_approx`. -/ protected noncomputable def approx : ℕ → α →ₛ β := hf.some protected lemma fin_support_approx : ∀ n, μ (support (hf.approx n)) < ∞ := hf.some_spec.1 protected lemma tendsto_approx : ∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x)) := hf.some_spec.2 end sequence protected lemma strongly_measurable [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) : strongly_measurable f := ⟨hf.approx, hf.tendsto_approx⟩ lemma exists_set_sigma_finite [has_zero β] [topological_space β] [t2_space β] (hf : fin_strongly_measurable f μ) : ∃ t, measurable_set t ∧ (∀ x ∈ tᶜ, f x = 0) ∧ sigma_finite (μ.restrict t) := begin rcases hf with ⟨fs, hT_lt_top, h_approx⟩, let T := λ n, support (fs n), have hT_meas : ∀ n, measurable_set (T n), from λ n, simple_func.measurable_set_support (fs n), let t := ⋃ n, T n, refine ⟨t, measurable_set.Union hT_meas, _, _⟩, { have h_fs_zero : ∀ n, ∀ x ∈ tᶜ, fs n x = 0, { intros n x hxt, rw [set.mem_compl_iff, set.mem_Union, not_exists] at hxt, simpa using (hxt n), }, refine λ x hxt, tendsto_nhds_unique (h_approx x) _, rw funext (λ n, h_fs_zero n x hxt), exact tendsto_const_nhds, }, { refine ⟨⟨⟨λ n, tᶜ ∪ T n, λ n, trivial, λ n, _, _⟩⟩⟩, { rw [measure.restrict_apply' (measurable_set.Union hT_meas), set.union_inter_distrib_right, set.compl_inter_self t, set.empty_union], exact (measure_mono (set.inter_subset_left _ _)).trans_lt (hT_lt_top n), }, { rw ← set.union_Union tᶜ T, exact set.compl_union_self _ } } end /-- A finitely strongly measurable function is measurable. -/ protected lemma measurable [has_zero β] [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : fin_strongly_measurable f μ) : measurable f := hf.strongly_measurable.measurable section arithmetic variables [topological_space β] protected lemma mul [monoid_with_zero β] [has_continuous_mul β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f * g) μ := begin refine ⟨λ n, hf.approx n * hg.approx n, _, λ x, (hf.tendsto_approx x).mul (hg.tendsto_approx x)⟩, intro n, exact (measure_mono (support_mul_subset_left _ _)).trans_lt (hf.fin_support_approx n), end protected lemma add [add_monoid β] [has_continuous_add β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f + g) μ := ⟨λ n, hf.approx n + hg.approx n, λ n, (measure_mono (function.support_add _ _)).trans_lt ((measure_union_le _ _).trans_lt (ennreal.add_lt_top.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩)), λ x, (hf.tendsto_approx x).add (hg.tendsto_approx x)⟩ protected lemma neg [add_group β] [topological_add_group β] (hf : fin_strongly_measurable f μ) : fin_strongly_measurable (-f) μ := begin refine ⟨λ n, -hf.approx n, λ n, _, λ x, (hf.tendsto_approx x).neg⟩, suffices : μ (function.support (λ x, - (hf.approx n) x)) < ∞, by convert this, rw function.support_neg (hf.approx n), exact hf.fin_support_approx n, end protected lemma sub [add_group β] [has_continuous_sub β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f - g) μ := ⟨λ n, hf.approx n - hg.approx n, λ n, (measure_mono (function.support_sub _ _)).trans_lt ((measure_union_le _ _).trans_lt (ennreal.add_lt_top.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩)), λ x, (hf.tendsto_approx x).sub (hg.tendsto_approx x)⟩ protected lemma const_smul {𝕜} [topological_space 𝕜] [add_monoid β] [monoid 𝕜] [distrib_mul_action 𝕜 β] [has_continuous_smul 𝕜 β] (hf : fin_strongly_measurable f μ) (c : 𝕜) : fin_strongly_measurable (c • f) μ := begin refine ⟨λ n, c • (hf.approx n), λ n, _, λ x, (hf.tendsto_approx x).const_smul c⟩, rw simple_func.coe_smul, refine (measure_mono (support_smul_subset_right c _)).trans_lt (hf.fin_support_approx n), end end arithmetic section order variables [topological_space β] [has_zero β] protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f ⊔ g) μ := begin refine ⟨λ n, hf.approx n ⊔ hg.approx n, λ n, _, λ x, (hf.tendsto_approx x).sup_right_nhds (hg.tendsto_approx x)⟩, refine (measure_mono (support_sup _ _)).trans_lt _, exact measure_union_lt_top_iff.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩, end protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f ⊓ g) μ := begin refine ⟨λ n, hf.approx n ⊓ hg.approx n, λ n, _, λ x, (hf.tendsto_approx x).inf_right_nhds (hg.tendsto_approx x)⟩, refine (measure_mono (support_inf _ _)).trans_lt _, exact measure_union_lt_top_iff.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩, end end order end fin_strongly_measurable lemma fin_strongly_measurable_iff_strongly_measurable_and_exists_set_sigma_finite {α β} {f : α → β} [topological_space β] [t2_space β] [has_zero β] {m : measurable_space α} {μ : measure α} : fin_strongly_measurable f μ ↔ (strongly_measurable f ∧ (∃ t, measurable_set t ∧ (∀ x ∈ tᶜ, f x = 0) ∧ sigma_finite (μ.restrict t))) := ⟨λ hf, ⟨hf.strongly_measurable, hf.exists_set_sigma_finite⟩, λ hf, hf.1.fin_strongly_measurable_of_set_sigma_finite hf.2.some_spec.1 hf.2.some_spec.2.1 hf.2.some_spec.2.2⟩ lemma ae_fin_strongly_measurable_zero {α β} {m : measurable_space α} (μ : measure α) [has_zero β] [topological_space β] : ae_fin_strongly_measurable (0 : α → β) μ := ⟨0, fin_strongly_measurable_zero, eventually_eq.rfl⟩ /-! ## Almost everywhere strongly measurable functions -/ lemma ae_strongly_measurable_const {α β} {m : measurable_space α} {μ : measure α} [topological_space β] {b : β} : ae_strongly_measurable (λ a : α, b) μ := strongly_measurable_const.ae_strongly_measurable @[to_additive] lemma ae_strongly_measurable_one {α β} {m : measurable_space α} {μ : measure α} [topological_space β] [has_one β] : ae_strongly_measurable (1 : α → β) μ := strongly_measurable_one.ae_strongly_measurable @[simp] lemma subsingleton.ae_strongly_measurable {m : measurable_space α} [topological_space β] [subsingleton β] {μ : measure α} (f : α → β) : ae_strongly_measurable f μ := (subsingleton.strongly_measurable f).ae_strongly_measurable @[simp] lemma subsingleton.ae_strongly_measurable' {m : measurable_space α} [topological_space β] [subsingleton α] {μ : measure α} (f : α → β) : ae_strongly_measurable f μ := (subsingleton.strongly_measurable' f).ae_strongly_measurable @[simp] lemma ae_strongly_measurable_zero_measure [measurable_space α] [topological_space β] (f : α → β) : ae_strongly_measurable f (0 : measure α) := begin nontriviality α, inhabit α, exact ⟨λ x, f default, strongly_measurable_const, rfl⟩ end lemma simple_func.ae_strongly_measurable {m : measurable_space α} {μ : measure α} [topological_space β] (f : α →ₛ β) : ae_strongly_measurable f μ := f.strongly_measurable.ae_strongly_measurable namespace ae_strongly_measurable variables {m : measurable_space α} {μ : measure α} [topological_space β] [topological_space γ] {f g : α → β} section mk /-- A `strongly_measurable` function such that `f =ᵐ[μ] hf.mk f`. See lemmas `strongly_measurable_mk` and `ae_eq_mk`. -/ protected noncomputable def mk (f : α → β) (hf : ae_strongly_measurable f μ) : α → β := hf.some lemma strongly_measurable_mk (hf : ae_strongly_measurable f μ) : strongly_measurable (hf.mk f) := hf.some_spec.1 lemma measurable_mk [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : ae_strongly_measurable f μ) : measurable (hf.mk f) := hf.strongly_measurable_mk.measurable lemma ae_eq_mk (hf : ae_strongly_measurable f μ) : f =ᵐ[μ] hf.mk f := hf.some_spec.2 protected lemma ae_measurable {β} [measurable_space β] [topological_space β] [pseudo_metrizable_space β] [borel_space β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_measurable f μ := ⟨hf.mk f, hf.strongly_measurable_mk.measurable, hf.ae_eq_mk⟩ end mk lemma congr (hf : ae_strongly_measurable f μ) (h : f =ᵐ[μ] g) : ae_strongly_measurable g μ := ⟨hf.mk f, hf.strongly_measurable_mk, h.symm.trans hf.ae_eq_mk⟩ lemma _root_.ae_strongly_measurable_congr (h : f =ᵐ[μ] g) : ae_strongly_measurable f μ ↔ ae_strongly_measurable g μ := ⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩ lemma mono_measure {ν : measure α} (hf : ae_strongly_measurable f μ) (h : ν ≤ μ) : ae_strongly_measurable f ν := ⟨hf.mk f, hf.strongly_measurable_mk, eventually.filter_mono (ae_mono h) hf.ae_eq_mk⟩ protected lemma mono' {ν : measure α} (h : ae_strongly_measurable f μ) (h' : ν ≪ μ) : ae_strongly_measurable f ν := ⟨h.mk f, h.strongly_measurable_mk, h' h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_strongly_measurable f (μ.restrict t)) : ae_strongly_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) protected lemma restrict (hfm : ae_strongly_measurable f μ) {s} : ae_strongly_measurable f (μ.restrict s) := hfm.mono_measure measure.restrict_le_self lemma ae_mem_imp_eq_mk {s} (h : ae_strongly_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk /-- The composition of a continuous function and an ae strongly measurable function is ae strongly measurable. -/ lemma _root_.continuous.comp_ae_strongly_measurable {g : β → γ} {f : α → β} (hg : continuous g) (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, g (f x)) μ := ⟨_, hg.comp_strongly_measurable hf.strongly_measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk g⟩ /-- A continuous function from `α` to `β` is ae strongly measurable when one of the two spaces is second countable. -/ lemma _root_.continuous.ae_strongly_measurable [topological_space α] [opens_measurable_space α] [pseudo_metrizable_space β] [second_countable_topology_either α β] (hf : continuous f) : ae_strongly_measurable f μ := hf.strongly_measurable.ae_strongly_measurable protected lemma prod_mk {f : α → β} {g : α → γ} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, (f x, g x)) μ := ⟨λ x, (hf.mk f x, hg.mk g x), hf.strongly_measurable_mk.prod_mk hg.strongly_measurable_mk, hf.ae_eq_mk.prod_mk hg.ae_eq_mk⟩ /-- In a space with second countable topology, measurable implies ae strongly measurable. -/ lemma _root_.measurable.ae_strongly_measurable {m : measurable_space α} {μ : measure α} [measurable_space β] [pseudo_metrizable_space β] [second_countable_topology β] [opens_measurable_space β] (hf : measurable f) : ae_strongly_measurable f μ := hf.strongly_measurable.ae_strongly_measurable section arithmetic @[to_additive] protected lemma mul [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f * g) μ := ⟨hf.mk f * hg.mk g, hf.strongly_measurable_mk.mul hg.strongly_measurable_mk, hf.ae_eq_mk.mul hg.ae_eq_mk⟩ @[to_additive] protected lemma mul_const [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, f x * c) μ := hf.mul ae_strongly_measurable_const @[to_additive] protected lemma const_mul [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, c * f x) μ := ae_strongly_measurable_const.mul hf @[to_additive] protected lemma inv [group β] [topological_group β] (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (f⁻¹) μ := ⟨(hf.mk f)⁻¹, hf.strongly_measurable_mk.inv, hf.ae_eq_mk.inv⟩ @[to_additive] protected lemma div [group β] [topological_group β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f / g) μ := ⟨hf.mk f / hg.mk g, hf.strongly_measurable_mk.div hg.strongly_measurable_mk, hf.ae_eq_mk.div hg.ae_eq_mk⟩ @[to_additive] protected lemma smul {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} {g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, f x • g x) μ := continuous_smul.comp_ae_strongly_measurable (hf.prod_mk hg) protected lemma const_smul {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : ae_strongly_measurable f μ) (c : 𝕜) : ae_strongly_measurable (c • f) μ := ⟨c • hf.mk f, hf.strongly_measurable_mk.const_smul c, hf.ae_eq_mk.const_smul c⟩ protected lemma const_smul' {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : ae_strongly_measurable f μ) (c : 𝕜) : ae_strongly_measurable (λ x, c • (f x)) μ := hf.const_smul c @[to_additive] protected lemma smul_const {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, f x • c) μ := continuous_smul.comp_ae_strongly_measurable (hf.prod_mk ae_strongly_measurable_const) end arithmetic section order protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f ⊔ g) μ := ⟨hf.mk f ⊔ hg.mk g, hf.strongly_measurable_mk.sup hg.strongly_measurable_mk, hf.ae_eq_mk.sup hg.ae_eq_mk⟩ protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f ⊓ g) μ := ⟨hf.mk f ⊓ hg.mk g, hf.strongly_measurable_mk.inf hg.strongly_measurable_mk, hf.ae_eq_mk.inf hg.ae_eq_mk⟩ end order /-! ### Big operators: `∏` and `∑` -/ section monoid variables {M : Type*} [monoid M] [topological_space M] [has_continuous_mul M] @[to_additive] lemma _root_.list.ae_strongly_measurable_prod' (l : list (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable l.prod μ := begin induction l with f l ihl, { exact ae_strongly_measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive] lemma _root_.list.ae_strongly_measurable_prod (l : list (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (l.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.list_prod_apply] using l.ae_strongly_measurable_prod' hl end monoid section comm_monoid variables {M : Type*} [comm_monoid M] [topological_space M] [has_continuous_mul M] @[to_additive] lemma _root_.multiset.ae_strongly_measurable_prod' (l : multiset (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable l.prod μ := by { rcases l with ⟨l⟩, simpa using l.ae_strongly_measurable_prod' (by simpa using hl) } @[to_additive] lemma _root_.multiset.ae_strongly_measurable_prod (s : multiset (α → M)) (hs : ∀ f ∈ s, ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (s.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.multiset_prod_apply] using s.ae_strongly_measurable_prod' hs @[to_additive] lemma _root_.finset.ae_strongly_measurable_prod' {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, ae_strongly_measurable (f i) μ) : ae_strongly_measurable (∏ i in s, f i) μ := multiset.ae_strongly_measurable_prod' _ $ λ g hg, let ⟨i, hi, hg⟩ := multiset.mem_map.1 hg in (hg ▸ hf _ hi) @[to_additive] lemma _root_.finset.ae_strongly_measurable_prod {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, ae_strongly_measurable (f i) μ) : ae_strongly_measurable (λ a, ∏ i in s, f i a) μ := by simpa only [← finset.prod_apply] using s.ae_strongly_measurable_prod' hf end comm_monoid section second_countable_ae_strongly_measurable variables [measurable_space β] /-- In a space with second countable topology, measurable implies strongly measurable. -/ lemma _root_.ae_measurable.ae_strongly_measurable [pseudo_metrizable_space β] [opens_measurable_space β] [second_countable_topology β] (hf : ae_measurable f μ) : ae_strongly_measurable f μ := ⟨hf.mk f, hf.measurable_mk.strongly_measurable, hf.ae_eq_mk⟩ lemma _root_.ae_strongly_measurable_id {α : Type*} [topological_space α] [pseudo_metrizable_space α] {m : measurable_space α} [opens_measurable_space α] [second_countable_topology α] {μ : measure α} : ae_strongly_measurable (id : α → α) μ := ae_measurable_id.ae_strongly_measurable /-- In a space with second countable topology, strongly measurable and measurable are equivalent. -/ lemma _root_.ae_strongly_measurable_iff_ae_measurable [pseudo_metrizable_space β] [borel_space β] [second_countable_topology β] : ae_strongly_measurable f μ ↔ ae_measurable f μ := ⟨λ h, h.ae_measurable, λ h, h.ae_strongly_measurable⟩ end second_countable_ae_strongly_measurable protected lemma dist {β : Type*} [pseudo_metric_space β] {f g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, dist (f x) (g x)) μ := continuous_dist.comp_ae_strongly_measurable (hf.prod_mk hg) protected lemma norm {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, ‖f x‖) μ := continuous_norm.comp_ae_strongly_measurable hf protected lemma nnnorm {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, ‖f x‖₊) μ := continuous_nnnorm.comp_ae_strongly_measurable hf protected lemma ennnorm {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_measurable (λ a, (‖f a‖₊ : ℝ≥0∞)) μ := (ennreal.continuous_coe.comp_ae_strongly_measurable hf.nnnorm).ae_measurable protected lemma edist {β : Type*} [seminormed_add_comm_group β] {f g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (continuous_edist.comp_ae_strongly_measurable (hf.prod_mk hg)).ae_measurable protected lemma real_to_nnreal {f : α → ℝ} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (f x).to_nnreal) μ := continuous_real_to_nnreal.comp_ae_strongly_measurable hf lemma _root_.ae_strongly_measurable_indicator_iff [has_zero β] {s : set α} (hs : measurable_set s) : ae_strongly_measurable (indicator s f) μ ↔ ae_strongly_measurable f (μ.restrict s) := begin split, { intro h, exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }, { intro h, refine ⟨indicator s (h.mk f), h.strongly_measurable_mk.indicator hs, _⟩, have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (h.mk f) := (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm), have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (h.mk f) := (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm, exact ae_of_ae_restrict_of_ae_restrict_compl _ A B }, end protected lemma indicator [has_zero β] (hfm : ae_strongly_measurable f μ) {s : set α} (hs : measurable_set s) : ae_strongly_measurable (s.indicator f) μ := (ae_strongly_measurable_indicator_iff hs).mpr hfm.restrict lemma _root_.ae_strongly_measurable_of_ae_strongly_measurable_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_strongly_measurable f (μ.trim hm)) : ae_strongly_measurable f μ := ⟨hf.mk f, strongly_measurable.mono hf.strongly_measurable_mk hm, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩ lemma comp_ae_measurable {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hg : ae_strongly_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : ae_strongly_measurable (g ∘ f) μ := ⟨(hg.mk g) ∘ hf.mk f, hg.strongly_measurable_mk.comp_measurable hf.measurable_mk, (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (hg.mk g))⟩ lemma comp_measurable {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hg : ae_strongly_measurable g (measure.map f μ)) (hf : measurable f) : ae_strongly_measurable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma comp_quasi_measure_preserving {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} {ν : measure α} (hg : ae_strongly_measurable g ν) (hf : quasi_measure_preserving f μ ν) : ae_strongly_measurable (g ∘ f) μ := (hg.mono' hf.absolutely_continuous).comp_measurable hf.measurable lemma is_separable_ae_range (hf : ae_strongly_measurable f μ) : ∃ (t : set β), is_separable t ∧ ∀ᵐ x ∂μ, f x ∈ t := begin refine ⟨range (hf.mk f), hf.strongly_measurable_mk.is_separable_range, _⟩, filter_upwards [hf.ae_eq_mk] with x hx, simp [hx] end /-- A function is almost everywhere strongly measurable if and only if it is almost everywhere measurable, and up to a zero measure set its range is contained in a separable set. -/ theorem _root_.ae_strongly_measurable_iff_ae_measurable_separable [pseudo_metrizable_space β] [measurable_space β] [borel_space β] : ae_strongly_measurable f μ ↔ (ae_measurable f μ ∧ ∃ (t : set β), is_separable t ∧ ∀ᵐ x ∂μ, f x ∈ t) := begin refine ⟨λ H, ⟨H.ae_measurable, H.is_separable_ae_range⟩, _⟩, rintros ⟨H, ⟨t, t_sep, ht⟩⟩, rcases eq_empty_or_nonempty t with rfl|h₀, { simp only [mem_empty_iff_false, eventually_false_iff_eq_bot, ae_eq_bot] at ht, rw ht, exact ae_strongly_measurable_zero_measure f }, { obtain ⟨g, g_meas, gt, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g := H.exists_ae_eq_range_subset ht h₀, refine ⟨g, _, fg⟩, exact strongly_measurable_iff_measurable_separable.2 ⟨g_meas, t_sep.mono gt⟩ } end lemma _root_.measurable_embedding.ae_strongly_measurable_map_iff {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hf : measurable_embedding f) {g : α → β} : ae_strongly_measurable g (measure.map f μ) ↔ ae_strongly_measurable (g ∘ f) μ := begin refine ⟨λ H, H.comp_measurable hf.measurable, _⟩, rintro ⟨g₁, hgm₁, heq⟩, rcases hf.exists_strongly_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩, exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩ end lemma _root_.embedding.ae_strongly_measurable_comp_iff [pseudo_metrizable_space β] [pseudo_metrizable_space γ] {g : β → γ} {f : α → β} (hg : embedding g) : ae_strongly_measurable (λ x, g (f x)) μ ↔ ae_strongly_measurable f μ := begin letI := pseudo_metrizable_space_pseudo_metric γ, borelize [β, γ], refine ⟨λ H, ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨_, _⟩, λ H, hg.continuous.comp_ae_strongly_measurable H⟩, { let G : β → range g := cod_restrict g (range g) mem_range_self, have hG : closed_embedding G := { closed_range := begin convert is_closed_univ, apply eq_univ_of_forall, rintros ⟨-, ⟨x, rfl⟩⟩, exact mem_range_self x end, .. hg.cod_restrict _ _ }, have : ae_measurable (G ∘ f) μ := ae_measurable.subtype_mk H.ae_measurable, exact hG.measurable_embedding.ae_measurable_comp_iff.1 this }, { rcases (ae_strongly_measurable_iff_ae_measurable_separable.1 H).2 with ⟨t, ht, h't⟩, exact ⟨g⁻¹' t, hg.is_separable_preimage ht, h't⟩ } end lemma _root_.measure_theory.measure_preserving.ae_strongly_measurable_comp_iff {β : Type*} {f : α → β} {mα : measurable_space α} {μa : measure α} {mβ : measurable_space β} {μb : measure β} (hf : measure_preserving f μa μb) (h₂ : measurable_embedding f) {g : β → γ} : ae_strongly_measurable (g ∘ f) μa ↔ ae_strongly_measurable g μb := by rw [← hf.map_eq, h₂.ae_strongly_measurable_map_iff] /-- An almost everywhere sequential limit of almost everywhere strongly measurable functions is almost everywhere strongly measurable. -/ lemma _root_.ae_strongly_measurable_of_tendsto_ae {ι : Type*} [pseudo_metrizable_space β] (u : filter ι) [ne_bot u] [is_countably_generated u] {f : ι → α → β} {g : α → β} (hf : ∀ i, ae_strongly_measurable (f i) μ) (lim : ∀ᵐ x ∂μ, tendsto (λ n, f n x) u (𝓝 (g x))) : ae_strongly_measurable g μ := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨_, _⟩, { exact ae_measurable_of_tendsto_metrizable_ae _ (λ n, (hf n).ae_measurable) lim }, { rcases u.exists_seq_tendsto with ⟨v, hv⟩, have : ∀ (n : ℕ), ∃ (t : set β), is_separable t ∧ f (v n) ⁻¹' t ∈ μ.ae := λ n, (ae_strongly_measurable_iff_ae_measurable_separable.1 (hf (v n))).2, choose t t_sep ht using this, refine ⟨closure (⋃ i, (t i)), (is_separable_Union (λ i, (t_sep i))).closure, _⟩, filter_upwards [ae_all_iff.2 ht, lim] with x hx h'x, apply mem_closure_of_tendsto ((h'x).comp hv), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact hx n } end /-- If a sequence of almost everywhere strongly measurable functions converges almost everywhere, one can select a strongly measurable function as the almost everywhere limit. -/ lemma _root_.exists_strongly_measurable_limit_of_tendsto_ae [pseudo_metrizable_space β] {f : ℕ → α → β} (hf : ∀ n, ae_strongly_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, tendsto (λ n, f n x) at_top (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : strongly_measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x)) := begin borelize β, obtain ⟨g, g_meas, hg⟩ : ∃ (g : α → β) (g_meas : measurable g), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x)) := measurable_limit_of_tendsto_metrizable_ae (λ n, (hf n).ae_measurable) h_ae_tendsto, have Hg : ae_strongly_measurable g μ := ae_strongly_measurable_of_tendsto_ae _ hf hg, refine ⟨Hg.mk g, Hg.strongly_measurable_mk, _⟩, filter_upwards [hg, Hg.ae_eq_mk] with x hx h'x, rwa h'x at hx, end lemma sum_measure [pseudo_metrizable_space β] {m : measurable_space α} {μ : ι → measure α} (h : ∀ i, ae_strongly_measurable f (μ i)) : ae_strongly_measurable f (measure.sum μ) := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨ae_measurable.sum_measure (λ i, (h i).ae_measurable), _⟩, have A : ∀ (i : ι), ∃ (t : set β), is_separable t ∧ f ⁻¹' t ∈ (μ i).ae := λ i, (ae_strongly_measurable_iff_ae_measurable_separable.1 (h i)).2, choose t t_sep ht using A, refine ⟨(⋃ i, t i), is_separable_Union t_sep, _⟩, simp only [measure.ae_sum_eq, mem_Union, eventually_supr], assume i, filter_upwards [ht i] with x hx, exact ⟨i, hx⟩ end @[simp] lemma _root_.ae_strongly_measurable_sum_measure_iff [pseudo_metrizable_space β] {m : measurable_space α} {μ : ι → measure α} : ae_strongly_measurable f (sum μ) ↔ ∀ i, ae_strongly_measurable f (μ i) := ⟨λ h i, h.mono_measure (measure.le_sum _ _), sum_measure⟩ @[simp] lemma _root_.ae_strongly_measurable_add_measure_iff [pseudo_metrizable_space β] {ν : measure α} : ae_strongly_measurable f (μ + ν) ↔ ae_strongly_measurable f μ ∧ ae_strongly_measurable f ν := by { rw [← sum_cond, ae_strongly_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl } lemma add_measure [pseudo_metrizable_space β] {ν : measure α} {f : α → β} (hμ : ae_strongly_measurable f μ) (hν : ae_strongly_measurable f ν) : ae_strongly_measurable f (μ + ν) := ae_strongly_measurable_add_measure_iff.2 ⟨hμ, hν⟩ protected lemma Union [pseudo_metrizable_space β] {s : ι → set α} (h : ∀ i, ae_strongly_measurable f (μ.restrict (s i))) : ae_strongly_measurable f (μ.restrict (⋃ i, s i)) := (sum_measure h).mono_measure $ restrict_Union_le @[simp] lemma _root_.ae_strongly_measurable_Union_iff [pseudo_metrizable_space β] {s : ι → set α} : ae_strongly_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_strongly_measurable f (μ.restrict (s i)) := ⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_strongly_measurable.Union⟩ @[simp] lemma _root_.ae_strongly_measurable_union_iff [pseudo_metrizable_space β] {s t : set α} : ae_strongly_measurable f (μ.restrict (s ∪ t)) ↔ ae_strongly_measurable f (μ.restrict s) ∧ ae_strongly_measurable f (μ.restrict t) := by simp only [union_eq_Union, ae_strongly_measurable_Union_iff, bool.forall_bool, cond, and.comm] lemma ae_strongly_measurable_uIoc_iff [linear_order α] [pseudo_metrizable_space β] {f : α → β} {a b : α} : ae_strongly_measurable f (μ.restrict $ uIoc a b) ↔ ae_strongly_measurable f (μ.restrict $ Ioc a b) ∧ ae_strongly_measurable f (μ.restrict $ Ioc b a) := by rw [uIoc_eq_union, ae_strongly_measurable_union_iff] lemma smul_measure {R : Type*} [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (h : ae_strongly_measurable f μ) (c : R) : ae_strongly_measurable f (c • μ) := ⟨h.mk f, h.strongly_measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ section normed_space variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] lemma _root_.ae_strongly_measurable_smul_const_iff {f : α → 𝕜} {c : E} (hc : c ≠ 0) : ae_strongly_measurable (λ x, f x • c) μ ↔ ae_strongly_measurable f μ := (closed_embedding_smul_left hc).to_embedding.ae_strongly_measurable_comp_iff end normed_space section mul_action variables {G : Type*} [group G] [mul_action G β] [has_continuous_const_smul G β] lemma _root_.ae_strongly_measurable_const_smul_iff (c : G) : ae_strongly_measurable (λ x, c • f x) μ ↔ ae_strongly_measurable f μ := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ variables {G₀ : Type*} [group_with_zero G₀] [mul_action G₀ β] [has_continuous_const_smul G₀ β] lemma _root_.ae_strongly_measurable_const_smul_iff₀ {c : G₀} (hc : c ≠ 0) : ae_strongly_measurable (λ x, c • f x) μ ↔ ae_strongly_measurable f μ := begin refine ⟨λ h, _, λ h, h.const_smul c⟩, convert h.const_smul' c⁻¹, simp [smul_smul, inv_mul_cancel hc] end end mul_action section continuous_linear_map_nontrivially_normed_field variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] lemma _root_.strongly_measurable.apply_continuous_linear_map {m : measurable_space α} {φ : α → F →L[𝕜] E} (hφ : strongly_measurable φ) (v : F) : strongly_measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).continuous.comp_strongly_measurable hφ lemma apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : ae_strongly_measurable φ μ) (v : F) : ae_strongly_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).continuous.comp_ae_strongly_measurable hφ lemma _root_.continuous_linear_map.ae_strongly_measurable_comp₂ (L : E →L[𝕜] F →L[𝕜] G) {f : α → E} {g : α → F} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, L (f x) (g x)) μ := L.continuous₂.comp_ae_strongly_measurable $ hf.prod_mk hg end continuous_linear_map_nontrivially_normed_field lemma _root_.ae_strongly_measurable_with_density_iff {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f : α → ℝ≥0} (hf : measurable f) {g : α → E} : ae_strongly_measurable g (μ.with_density (λ x, (f x : ℝ≥0∞))) ↔ ae_strongly_measurable (λ x, (f x : ℝ) • 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_real.strongly_measurable.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'] with a ha h'a, have : (f a : ℝ≥0∞) ≠ 0, by simpa only [ne.def, ennreal.coe_eq_zero] using h'a, rw ha this }, { filter_upwards [ae_restrict_mem A.compl] with 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_real.inv.strongly_measurable.smul g'meas, _⟩, rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal], filter_upwards [hg'] with x hx h'x, rw [← hx, smul_smul, _root_.inv_mul_cancel, one_smul], simp only [ne.def, ennreal.coe_eq_zero] at h'x, simpa only [nnreal.coe_eq_zero, ne.def] using h'x } end end ae_strongly_measurable /-! ## Almost everywhere finitely strongly measurable functions -/ namespace ae_fin_strongly_measurable variables {m : measurable_space α} {μ : measure α} [topological_space β] {f g : α → β} section mk variables [has_zero β] /-- A `fin_strongly_measurable` function such that `f =ᵐ[μ] hf.mk f`. See lemmas `fin_strongly_measurable_mk` and `ae_eq_mk`. -/ protected noncomputable def mk (f : α → β) (hf : ae_fin_strongly_measurable f μ) : α → β := hf.some lemma fin_strongly_measurable_mk (hf : ae_fin_strongly_measurable f μ) : fin_strongly_measurable (hf.mk f) μ := hf.some_spec.1 lemma ae_eq_mk (hf : ae_fin_strongly_measurable f μ) : f =ᵐ[μ] hf.mk f := hf.some_spec.2 protected lemma ae_measurable {β} [has_zero β] [measurable_space β] [topological_space β] [pseudo_metrizable_space β] [borel_space β] {f : α → β} (hf : ae_fin_strongly_measurable f μ) : ae_measurable f μ := ⟨hf.mk f, hf.fin_strongly_measurable_mk.measurable, hf.ae_eq_mk⟩ end mk section arithmetic protected lemma mul [monoid_with_zero β] [has_continuous_mul β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f * g) μ := ⟨hf.mk f * hg.mk g, hf.fin_strongly_measurable_mk.mul hg.fin_strongly_measurable_mk, hf.ae_eq_mk.mul hg.ae_eq_mk⟩ protected lemma add [add_monoid β] [has_continuous_add β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f + g) μ := ⟨hf.mk f + hg.mk g, hf.fin_strongly_measurable_mk.add hg.fin_strongly_measurable_mk, hf.ae_eq_mk.add hg.ae_eq_mk⟩ protected lemma neg [add_group β] [topological_add_group β] (hf : ae_fin_strongly_measurable f μ) : ae_fin_strongly_measurable (-f) μ := ⟨-hf.mk f, hf.fin_strongly_measurable_mk.neg, hf.ae_eq_mk.neg⟩ protected lemma sub [add_group β] [has_continuous_sub β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f - g) μ := ⟨hf.mk f - hg.mk g, hf.fin_strongly_measurable_mk.sub hg.fin_strongly_measurable_mk, hf.ae_eq_mk.sub hg.ae_eq_mk⟩ protected lemma const_smul {𝕜} [topological_space 𝕜] [add_monoid β] [monoid 𝕜] [distrib_mul_action 𝕜 β] [has_continuous_smul 𝕜 β] (hf : ae_fin_strongly_measurable f μ) (c : 𝕜) : ae_fin_strongly_measurable (c • f) μ := ⟨c • hf.mk f, hf.fin_strongly_measurable_mk.const_smul c, hf.ae_eq_mk.const_smul c⟩ end arithmetic section order variables [has_zero β] protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f ⊔ g) μ := ⟨hf.mk f ⊔ hg.mk g, hf.fin_strongly_measurable_mk.sup hg.fin_strongly_measurable_mk, hf.ae_eq_mk.sup hg.ae_eq_mk⟩ protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f ⊓ g) μ := ⟨hf.mk f ⊓ hg.mk g, hf.fin_strongly_measurable_mk.inf hg.fin_strongly_measurable_mk, hf.ae_eq_mk.inf hg.ae_eq_mk⟩ end order variables [has_zero β] [t2_space β] lemma exists_set_sigma_finite (hf : ae_fin_strongly_measurable f μ) : ∃ t, measurable_set t ∧ f =ᵐ[μ.restrict tᶜ] 0 ∧ sigma_finite (μ.restrict t) := begin rcases hf with ⟨g, hg, hfg⟩, obtain ⟨t, ht, hgt_zero, htμ⟩ := hg.exists_set_sigma_finite, refine ⟨t, ht, _, htμ⟩, refine eventually_eq.trans (ae_restrict_of_ae hfg) _, rw [eventually_eq, ae_restrict_iff' ht.compl], exact eventually_of_forall hgt_zero, end /-- A measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `sigma_finite (μ.restrict t)`. -/ def sigma_finite_set (hf : ae_fin_strongly_measurable f μ) : set α := hf.exists_set_sigma_finite.some protected lemma measurable_set (hf : ae_fin_strongly_measurable f μ) : measurable_set hf.sigma_finite_set := hf.exists_set_sigma_finite.some_spec.1 lemma ae_eq_zero_compl (hf : ae_fin_strongly_measurable f μ) : f =ᵐ[μ.restrict hf.sigma_finite_setᶜ] 0 := hf.exists_set_sigma_finite.some_spec.2.1 instance sigma_finite_restrict (hf : ae_fin_strongly_measurable f μ) : sigma_finite (μ.restrict hf.sigma_finite_set) := hf.exists_set_sigma_finite.some_spec.2.2 end ae_fin_strongly_measurable section second_countable_topology variables {G : Type*} {p : ℝ≥0∞} {m m0 : measurable_space α} {μ : measure α} [seminormed_add_comm_group G] [measurable_space G] [borel_space G] [second_countable_topology G] {f : α → G} /-- In a space with second countable topology and a sigma-finite measure, `fin_strongly_measurable` and `measurable` are equivalent. -/ lemma fin_strongly_measurable_iff_measurable {m0 : measurable_space α} (μ : measure α) [sigma_finite μ] : fin_strongly_measurable f μ ↔ measurable f := ⟨λ h, h.measurable, λ h, (measurable.strongly_measurable h).fin_strongly_measurable μ⟩ /-- In a space with second countable topology and a sigma-finite measure, `ae_fin_strongly_measurable` and `ae_measurable` are equivalent. -/ lemma ae_fin_strongly_measurable_iff_ae_measurable {m0 : measurable_space α} (μ : measure α) [sigma_finite μ] : ae_fin_strongly_measurable f μ ↔ ae_measurable f μ := by simp_rw [ae_fin_strongly_measurable, ae_measurable, fin_strongly_measurable_iff_measurable] end second_countable_topology lemma measurable_uncurry_of_continuous_of_measurable {α β ι : Type*} [topological_space ι] [metrizable_space ι] [measurable_space ι] [second_countable_topology ι] [opens_measurable_space ι] {mβ : measurable_space β} [topological_space β] [pseudo_metrizable_space β] [borel_space β] {m : measurable_space α} {u : ι → α → β} (hu_cont : ∀ x, continuous (λ i, u i x)) (h : ∀ i, measurable (u i)) : measurable (function.uncurry u) := begin obtain ⟨t_sf, ht_sf⟩ : ∃ t : ℕ → simple_func ι ι, ∀ j x, tendsto (λ n, u (t n j) x) at_top (𝓝 $ u j x), { have h_str_meas : strongly_measurable (id : ι → ι), from strongly_measurable_id, refine ⟨h_str_meas.approx, λ j x, _⟩, exact ((hu_cont x).tendsto j).comp (h_str_meas.tendsto_approx j), }, let U := λ (n : ℕ) (p : ι × α), u (t_sf n p.fst) p.snd, have h_tendsto : tendsto U at_top (𝓝 (λ p, u p.fst p.snd)), { rw tendsto_pi_nhds, exact λ p, ht_sf p.fst p.snd, }, refine measurable_of_tendsto_metrizable (λ n, _) h_tendsto, have h_meas : measurable (λ (p : (t_sf n).range × α), u ↑p.fst p.snd), { have : (λ (p : ↥((t_sf n).range) × α), u ↑(p.fst) p.snd) = (λ (p : α × ((t_sf n).range)), u ↑(p.snd) p.fst) ∘ prod.swap := rfl, rw [this, @measurable_swap_iff α ↥((t_sf n).range) β m], exact measurable_from_prod_countable (λ j, h j), }, have : (λ p : ι × α, u (t_sf n p.fst) p.snd) = (λ p : ↥(t_sf n).range × α, u p.fst p.snd) ∘ (λ p : ι × α, (⟨t_sf n p.fst, simple_func.mem_range_self _ _⟩, p.snd)) := rfl, simp_rw [U, this], refine h_meas.comp (measurable.prod_mk _ measurable_snd), exact ((t_sf n).measurable.comp measurable_fst).subtype_mk, end lemma strongly_measurable_uncurry_of_continuous_of_strongly_measurable {α β ι : Type*} [topological_space ι] [metrizable_space ι] [measurable_space ι] [second_countable_topology ι] [opens_measurable_space ι] [topological_space β] [pseudo_metrizable_space β] [measurable_space α] {u : ι → α → β} (hu_cont : ∀ x, continuous (λ i, u i x)) (h : ∀ i, strongly_measurable (u i)) : strongly_measurable (function.uncurry u) := begin borelize β, obtain ⟨t_sf, ht_sf⟩ : ∃ t : ℕ → simple_func ι ι, ∀ j x, tendsto (λ n, u (t n j) x) at_top (𝓝 $ u j x), { have h_str_meas : strongly_measurable (id : ι → ι), from strongly_measurable_id, refine ⟨h_str_meas.approx, λ j x, _⟩, exact ((hu_cont x).tendsto j).comp (h_str_meas.tendsto_approx j), }, let U := λ (n : ℕ) (p : ι × α), u (t_sf n p.fst) p.snd, have h_tendsto : tendsto U at_top (𝓝 (λ p, u p.fst p.snd)), { rw tendsto_pi_nhds, exact λ p, ht_sf p.fst p.snd, }, refine strongly_measurable_of_tendsto _ (λ n, _) h_tendsto, have h_str_meas : strongly_measurable (λ (p : (t_sf n).range × α), u ↑p.fst p.snd), { refine strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, { have : (λ (p : ↥((t_sf n).range) × α), u ↑(p.fst) p.snd) = (λ (p : α × ((t_sf n).range)), u ↑(p.snd) p.fst) ∘ prod.swap := rfl, rw [this, measurable_swap_iff], exact measurable_from_prod_countable (λ j, (h j).measurable), }, { have : is_separable (⋃ (i : (t_sf n).range), range (u i)) := is_separable_Union (λ i, (h i).is_separable_range), apply this.mono, rintros _ ⟨⟨i, x⟩, rfl⟩, simp only [mem_Union, mem_range], exact ⟨i, x, rfl⟩ } }, have : (λ p : ι × α, u (t_sf n p.fst) p.snd) = (λ p : ↥(t_sf n).range × α, u p.fst p.snd) ∘ (λ p : ι × α, (⟨t_sf n p.fst, simple_func.mem_range_self _ _⟩, p.snd)) := rfl, simp_rw [U, this], refine h_str_meas.comp_measurable (measurable.prod_mk _ measurable_snd), exact ((t_sf n).measurable.comp measurable_fst).subtype_mk, end end measure_theory -- Guard against import creep assert_not_exists inner_product_space
3472e6d110bcd4ab464701e6806c65d1e507e716
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tactic4.lean
4a333dc407434cd3871d0afdbb5cf473cf404bdf
[ "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
138
lean
import logic open tactic (renaming id->id_tac) theorem tst {A B : Prop} (H1 : A) (H2 : B) : id A := by unfold id; assumption check tst
c135d403a961fb24ad931966502fe77ffb2811d4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/euclidean_absolute_value.lean
cef698d857b7855f75b11f4a8c5b9bd875375945
[ "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
2,234
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.order.absolute_value import algebra.euclidean_domain.instances /-! # Euclidean absolute values > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a predicate `absolute_value.is_euclidean abv` stating the absolute value is compatible with the Euclidean domain structure on its domain. ## Main definitions * `absolute_value.is_euclidean abv` is a predicate on absolute values on `R` mapping to `S` that preserve the order on `R` arising from the Euclidean domain structure. * `absolute_value.abs_is_euclidean` shows the "standard" absolute value on `ℤ`, mapping negative `x` to `-x`, is euclidean. -/ local infix ` ≺ `:50 := euclidean_domain.r namespace absolute_value section ordered_semiring variables {R S : Type*} [euclidean_domain R] [ordered_semiring S] variables (abv : absolute_value R S) /-- An absolute value `abv : R → S` is Euclidean if it is compatible with the `euclidean_domain` structure on `R`, namely `abv` is strictly monotone with respect to the well founded relation `≺` on `R`. -/ structure is_euclidean : Prop := (map_lt_map_iff' : ∀ {x y}, abv x < abv y ↔ x ≺ y) namespace is_euclidean variables {abv} -- Rearrange the parameters to `map_lt_map_iff'` so it elaborates better. lemma map_lt_map_iff {x y : R} (h : abv.is_euclidean) : abv x < abv y ↔ x ≺ y := map_lt_map_iff' h attribute [simp] map_lt_map_iff lemma sub_mod_lt (h : abv.is_euclidean) (a : R) {b : R} (hb : b ≠ 0) : abv (a % b) < abv b := h.map_lt_map_iff.mpr (euclidean_domain.mod_lt a hb) end is_euclidean end ordered_semiring section int open int -- TODO: generalize to `linear_ordered_euclidean_domain`s if we ever get a definition of those /-- `abs : ℤ → ℤ` is a Euclidean absolute value -/ protected lemma abs_is_euclidean : is_euclidean (absolute_value.abs : absolute_value ℤ ℤ) := { map_lt_map_iff' := λ x y, show abs x < abs y ↔ nat_abs x < nat_abs y, by rw [abs_eq_nat_abs, abs_eq_nat_abs, coe_nat_lt] } end int end absolute_value
7deeb175a2406769c688d1c41172b8e2d469e8db
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/lean/semantics/soundness/assembly.lean
060f4c0aec3c7a131d6ae0cb8ff0b7524d7cc516
[ "Apache-2.0" ]
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
21,970
lean
/- This file does the following: o defines the Cairo assembly language in terms of the raw machine language instructions o defines Lean notation for the assembly language instructions o proves theorems characterizing the next state for each instruction -/ import starkware.cairo.lean.semantics.cpu /- Functions for clipping natural numbers and integers to the right range. -/ section variables {F : Type*} [field F] def nat_clip (x : int) : nat := ((x + 2^15).to_nat % 2^16 : nat) def int_clip (x : int) : F := nat_clip x - 2^15 lemma int_clip_eq {x : int} (h₁ : -2^15 ≤ x) (h₂ : x < 2^15) : (int_clip x : F) = x := begin have h : (x + 2^15).to_nat ≤ 2^16 - 1, { rw [int.to_nat_le, int.coe_nat_sub], apply int.le_sub_one_of_lt, apply lt_of_lt_of_le (add_lt_add_right h₂ _), norm_num, norm_num }, rw [int_clip, nat_clip, nat.mod_eq_of_lt], have h' : x = ((x + 2 ^ 15).to_nat : ℤ) - 2^15, { apply eq_sub_of_add_eq, rw [int.to_nat_of_nonneg], linarith }, conv { to_rhs, rw h' }, simp, apply nat.lt_of_succ_le, convert nat.succ_le_succ h end lemma int_clip_eq' (x : int) : int_clip x = ((nat_clip x - 2^15 : int) : F) := by simp [int_clip] @[simp] theorem int.zero_clip : int_clip 0 = (0 : F) := by rw int_clip_eq; norm_num def checked (x : int) {h₁ : -2^15 ≤ x} {h₂ : x < 2^15} : int := x @[simp] lemma clip_checked (x : int) (h₁ :-2^15 ≤ x) (h₂ : x < 2^15) : (int_clip (@checked x h₁ h₂) : F) = ↑x := int_clip_eq h₁ h₂ notation `'[#` x `]` := @checked x (by norm_num) (by norm_num) end /- A more convenient representation of instructions. -/ structure instr := (off_dst : int) (off_op0 : int) (off_op1 : int) (dst_reg : bool) (op0_reg : bool) (op1_src : bool × bool × bool) (res_logic : bool × bool) (pc_update : bool × bool × bool) (ap_update : bool × bool) (opcode : bool × bool × bool) namespace instr def to_instruction (i : instr) : instruction := { off_dst := bitvec.of_natr 16 (i.off_dst + 2^15).to_nat, off_op0 := bitvec.of_natr 16 (i.off_op0 + 2^15).to_nat, off_op1 := bitvec.of_natr 16 (i.off_op1 + 2^15).to_nat, flags := { val := [i.dst_reg, i.op0_reg, i.op1_src.1, i.op1_src.2.1, i.op1_src.2.2, i.res_logic.1, i.res_logic.2, i.pc_update.1, i.pc_update.2.1, i.pc_update.2.2, i.ap_update.1, i.ap_update.2, i.opcode.1, i.opcode.2.1, i.opcode.2.2], property := rfl } } def to_nat (i : instr) : nat := i.to_instruction.to_nat @[simp] lemma dst_reg_to_instruction (i : instr) : i.to_instruction.dst_reg = i.dst_reg := rfl @[simp] lemma op0_reg_to_instruction (i : instr) : i.to_instruction.op0_reg = i.op0_reg := rfl @[simp] lemma op1_imm_to_instruction (i : instr) : i.to_instruction.op1_imm = i.op1_src.1 := rfl @[simp] lemma op1_fp_to_instruction (i : instr) : i.to_instruction.op1_fp = i.op1_src.2.1 := rfl @[simp] lemma op1_ap_to_instruction (i : instr) : i.to_instruction.op1_ap = i.op1_src.2.2 := rfl @[simp] lemma res_add_to_instruction (i : instr) : i.to_instruction.res_add = i.res_logic.1 := rfl @[simp] lemma res_mul_to_instruction (i : instr) : i.to_instruction.res_mul = i.res_logic.2 := rfl @[simp] lemma pc_jump_abs_to_instruction (i : instr) : i.to_instruction.pc_jump_abs = i.pc_update.1 := rfl @[simp] lemma pc_jump_rel_to_instruction (i : instr) : i.to_instruction.pc_jump_rel = i.pc_update.2.1 := rfl @[simp] lemma pc_jnz_to_instruction (i : instr) : i.to_instruction.pc_jnz = i.pc_update.2.2 := rfl @[simp] lemma ap_add_to_instruction (i : instr) : i.to_instruction.ap_add = i.ap_update.1 := rfl @[simp] lemma ap_add1_to_instruction (i : instr) : i.to_instruction.ap_add1 = i.ap_update.2 := rfl @[simp] lemma opcode_call_to_instruction (i : instr) : i.to_instruction.opcode_call = i.opcode.1 := rfl @[simp] lemma opcode_ret_to_instruction (i : instr) : i.to_instruction.opcode_ret = i.opcode.2.1 := rfl @[simp] lemma opcode_assert_eq_to_instruction (i : instr) : i.to_instruction.opcode_assert_eq = i.opcode.2.2 := rfl @[simp] lemma off_dst_to_instruction (i : instr) : i.to_instruction.off_dst.to_natr = nat_clip i.off_dst := by simp [instr.to_instruction, bitvec.to_natr_of_natr, nat_clip] @[simp] lemma off_op0_to_instruction (i : instr) : i.to_instruction.off_op0.to_natr = nat_clip i.off_op0 := by simp [instr.to_instruction, bitvec.to_natr_of_natr, nat_clip] @[simp] lemma off_op1_to_instruction (i : instr) : i.to_instruction.off_op1.to_natr = nat_clip i.off_op1 := by simp [instr.to_instruction, bitvec.to_natr_of_natr, nat_clip] def next_state {F : Type*} [field F] [decidable_eq F] (i : instr) (mem : F → F) (s t : register_state F) := i.to_instruction.next_state mem s t end instr /- Model the assembly language. -/ inductive op0_spec | ap_plus : int → op0_spec | fp_plus : int → op0_spec @[simp] def op0_spec.op0_reg : op0_spec → bool | (op0_spec.ap_plus i) := ff | (op0_spec.fp_plus i) := tt @[simp] def op0_spec.off_op0 : op0_spec → int | (op0_spec.ap_plus i) := i | (op0_spec.fp_plus i) := i inductive op1_spec | mem_op0_plus : int → op1_spec | mem_pc_plus : int → op1_spec | mem_fp_plus : int → op1_spec | mem_ap_plus : int → op1_spec @[simp] def op1_spec.op1 : op1_spec → int | (op1_spec.mem_op0_plus i) := i | (op1_spec.mem_pc_plus i) := i | (op1_spec.mem_fp_plus i) := i | (op1_spec.mem_ap_plus i) := i @[simp] def op1_spec.op1_imm : op1_spec → bool | (op1_spec.mem_pc_plus i) := tt | _ := ff @[simp] def op1_spec.op1_fp : op1_spec → bool | (op1_spec.mem_fp_plus i) := tt | _ := ff @[simp] def op1_spec.op1_ap : op1_spec → bool | (op1_spec.mem_ap_plus i) := tt | _ := ff inductive res_spec | op1 : op1_spec → res_spec | op0_plus_op1 : op1_spec → res_spec | op0_times_op1 : op1_spec → res_spec @[simp] def res_spec.res_add : res_spec → bool | (res_spec.op0_plus_op1 i) := tt | _ := ff @[simp] def res_spec.res_mul : res_spec → bool | (res_spec.op0_times_op1 i) := tt | _ := ff @[simp] def res_spec.to_op1 : res_spec → op1_spec | (res_spec.op1 o1) := o1 | (res_spec.op0_plus_op1 o1) := o1 | (res_spec.op0_times_op1 o1) := o1 inductive dst_spec | mem_ap_plus : int → dst_spec | mem_fp_plus : int → dst_spec @[simp] def dst_spec.dst_reg : dst_spec → bool | (dst_spec.mem_ap_plus i) := ff | (dst_spec.mem_fp_plus i) := tt @[simp] def dst_spec.off_dst : dst_spec → int | (dst_spec.mem_ap_plus i) := i | (dst_spec.mem_fp_plus i) := i def assert_eq_instr (op0 : op0_spec) (res : res_spec) (dst : dst_spec) (ap_update : bool) : instr := { off_dst := dst.off_dst, off_op0 := op0.off_op0, off_op1 := res.to_op1.op1, dst_reg := dst.dst_reg, op0_reg := op0.op0_reg, op1_src := (res.to_op1.op1_imm, res.to_op1.op1_fp, res.to_op1.op1_ap), res_logic := (res.res_add, res.res_mul), pc_update := (ff, ff, ff), ap_update := (ff, ap_update), opcode := (ff, ff, tt) } def jump_instr (jump_abs : bool) (op0 : op0_spec) (res : res_spec) (ap_update : bool) : instr := { off_dst := -1, off_op0 := op0.off_op0, off_op1 := res.to_op1.op1, dst_reg := tt, op0_reg := op0.op0_reg, op1_src := (res.to_op1.op1_imm, res.to_op1.op1_fp, res.to_op1.op1_ap), res_logic := (res.res_add, res.res_mul), pc_update := (jump_abs, bnot jump_abs, ff), ap_update := (ff, ap_update), opcode := (ff, ff, ff) } def jnz_instr (op0 : op0_spec) (op1 : op1_spec) (dst : dst_spec) (ap_update : bool) : instr := { off_dst := dst.off_dst, off_op0 := op0.off_op0, off_op1 := op1.op1, dst_reg := dst.dst_reg, op0_reg := op0.op0_reg, op1_src := (op1.op1_imm, op1.op1_fp, op1.op1_ap), res_logic := (ff, ff), pc_update := (ff, ff, tt), ap_update := (ff, ap_update), opcode := (ff, ff, ff) } def call_instr (call_abs : bool) (res : res_spec) : instr := { off_dst := 0, off_op0 := 1, off_op1 := res.to_op1.op1, dst_reg := ff, op0_reg := ff, op1_src := (res.to_op1.op1_imm, res.to_op1.op1_fp, res.to_op1.op1_ap), res_logic := (res.res_add, res.res_mul), pc_update := (call_abs, bnot call_abs, ff), ap_update := (ff, ff), opcode := (tt, ff, ff) } def ret_instr : instr := { off_dst := -2, off_op0 := -1, off_op1 := -1, dst_reg := tt, op0_reg := tt, op1_src := (ff, tt, ff), res_logic := (ff, ff), pc_update := (tt, ff, ff), ap_update := (ff, ff), opcode := (ff, tt, ff) } def advance_ap_instr (op0 : op0_spec) (res : res_spec) : instr := { off_dst := -1, off_op0 := op0.off_op0, off_op1 := res.to_op1.op1, dst_reg := tt, op0_reg := op0.op0_reg, op1_src := (res.to_op1.op1_imm, res.to_op1.op1_fp, res.to_op1.op1_ap), res_logic := (res.res_add, res.res_mul), pc_update := (ff, ff, ff), ap_update := (tt, ff), opcode := (ff, ff, ff) } /- Notations for the assembly language. -/ notation `'op0[ap]` := op0_spec.ap_plus '[# 0] notation `'op0[fp]` := op0_spec.fp_plus '[# 0] notation `'op0[ap+` i `]` := op0_spec.ap_plus '[# i] notation `'op0[fp+` i `]` := op0_spec.fp_plus '[# i] notation `'op1[op0]` := op1_spec.mem_op0_plus '[# 0] notation `'op1[pc]` := op1_spec.mem_pc_plus '[# 0] notation `'op1[fp]` := op1_spec.mem_fp_plus '[# 0] notation `'op1[ap]` := op1_spec.mem_ap_plus '[# 0] notation `'op1[op0+` i `]` := op1_spec.mem_op0_plus '[# i] notation `'op1[pc+` i `]` := op1_spec.mem_pc_plus '[# i] notation `'op1[fp+` i `]` := op1_spec.mem_fp_plus '[# i] notation `'op1[ap+` i `]` := op1_spec.mem_ap_plus '[# i] notation `'op1[imm]` := op1_spec.mem_pc_plus '[# 1] notation `'res[` o1 `]` := res_spec.op1 o1 notation `'res[op0+` o1 `]` := res_spec.op0_plus_op1 o1 notation `'res[op0*` o1 `]` := res_spec.op0_times_op1 o1 notation `'dst[ap]` := dst_spec.mem_ap_plus '[# 0] notation `'dst[fp]` := dst_spec.mem_fp_plus '[# 0] notation `'dst[ap+` i `]` := dst_spec.mem_ap_plus '[# i] notation `'dst[fp+` i `]` := dst_spec.mem_fp_plus '[# i] notation `'assert_eq[op0:=` op0 `,` dst `===` res `]` := assert_eq_instr op0 res dst ff notation `'assert_eq[op0:=` op0 `,` dst `===` res `;ap++]` := assert_eq_instr op0 res dst tt notation `'assert_eq[` dst `===` res `]` := assert_eq_instr (op0_spec.fp_plus (-1)) res dst ff notation `'assert_eq[` dst `===` res `;ap++]` := assert_eq_instr (op0_spec.fp_plus (-1)) res dst tt notation `'jmp_abs[` o1 `]` := jump_instr tt (op0_spec.fp_plus (-1)) (res_spec.op1 o1) ff notation `'jmp_abs[+` o0 `,` o1 `]` := jump_instr tt o0 (res_spec.op0_plus_op1 o1) ff notation `'jmp_abs[*` o0 `,` o1 `]` := jump_instr tt o0 (res_spec.op0_times_op1 o1) ff notation `'jmp_abs[` o1 `;ap++]` := jump_instr tt (op0_spec.fp_plus (-1)) (res_spec.op1 o1) tt notation `'jmp_abs[+` o0 `,` o1 `;ap++]` := jump_instr tt o0 (res_spec.op0_plus_op1 o1) tt notation `'jmp_abs[*` o0 `,` o1 `;ap++]` := jump_instr tt o0 (res_spec.op0_times_op1 o1) tt notation `'jmp_rel[` o1 `]` := jump_instr ff (op0_spec.fp_plus (-1)) (res_spec.op1 o1) ff notation `'jmp_rel[+` o0 `,` o1 `]` := jump_instr ff o0 (res_spec.op0_plus_op1 o1) ff notation `'jmp_rel[*` o0 `,` o1 `]` := jump_instr ff o0 (res_spec.op0_times_op1 o1) ff notation `'jmp_rel[` o1 `;ap++]` := jump_instr ff (op0_spec.fp_plus (-1)) (res_spec.op1 o1) tt notation `'jmp_rel[+` o0 `,` o1 `;ap++]` := jump_instr ff o0 (res_spec.op0_plus_op1 o1) tt notation `'jmp_rel[*` o0 `,` o1 `;ap++]` := jump_instr ff o0 (res_spec.op0_times_op1 o1) tt notation `'jnz_rel[` o1 `,` dst `]` := jnz_instr (op0_spec.fp_plus (-1)) o1 dst ff notation `'jnz_rel[` o1 `,` dst `;ap++]` := jnz_instr (op0_spec.fp_plus (-1)) o1 dst tt notation `'jnz_rel[op0:=` op0 `,` o1 `,` dst `]` := jnz_instr op0 o1 dst ff notation `'jnz_rel[op0:=` op0 `,` o1 `,` dst `;ap++]` := jnz_instr op0 o1 dst tt notation `'call_abs[` o1 `]` := call_instr tt (res_spec.op1 o1) notation `'call_rel[` o1 `]` := call_instr ff (res_spec.op1 o1) notation `'ret[]` := ret_instr notation `'ap+=[op0:=` op0 `,` res `]` := advance_ap_instr op0 res notation `'ap+=[` res `]` := advance_ap_instr (op0_spec.fp_plus (-1)) res notation `'assert_eq[op0:=` op0 `,` dst `===` res `]` := assert_eq_instr op0 res dst ff /- Semantics of the assembly language. -/ section variables {F : Type*} [field F] variable mem : F → F variables s t : register_state F variables (op0 : op0_spec) (res : res_spec) (dst : dst_spec) (ap_update : bool) lemma agrees_iff_of_eq_some {T : Type*} {a : option T} {b : T} (h : a = some b) (c : T) : a.agrees c ↔ c = b := by { rw h, simp [option.agrees], split; apply eq.symm } lemma some_if {T : Type*} (P : Prop) [decidable P] (a b : T) : option.some (if P then a else b) = if P then option.some a else option.some b := by { by_cases h : P, { simp [if_pos h] }, simp [if_neg h] } @[simp] def bump_ap : bool → F | tt := s.ap + 1 | ff := s.ap @[simp] def compute_op0 : op0_spec → F | (op0_spec.ap_plus i) := mem (s.ap + int_clip i) | (op0_spec.fp_plus i) := mem (s.fp + int_clip i) @[simp] def compute_op1 : op1_spec → F | (op1_spec.mem_op0_plus i) := mem (compute_op0 mem s op0 + int_clip i) | (op1_spec.mem_pc_plus i) := mem (s.pc + int_clip i) | (op1_spec.mem_fp_plus i) := mem (s.fp + int_clip i) | (op1_spec.mem_ap_plus i) := mem (s.ap + int_clip i) @[simp] def compute_dst : dst_spec → F | (dst_spec.mem_ap_plus i) := mem (s.ap + int_clip i) | (dst_spec.mem_fp_plus i) := mem (s.fp + int_clip i) @[simp] def compute_res : res_spec → F | (res_spec.op1 o1) := compute_op1 mem s op0 o1 | (res_spec.op0_plus_op1 o1) := compute_op0 mem s op0 + compute_op1 mem s op0 o1 | (res_spec.op0_times_op1 o1) := compute_op0 mem s op0 * compute_op1 mem s op0 o1 @[simp] def bump_pc : bool → F | ff := s.pc + 1 | tt := s.pc + 2 @[simp] def jump_pc : bool → F → F | ff i := s.pc + i | tt i := i @[simp] lemma instruction_next_ap_aux_match_eq (i : instruction) : (instruction.next_ap_aux._match_1 i mem s ff ap_update) = some (bump_ap s ap_update) := by cases ap_update; { simp [instruction.next_ap_aux._match_1] } lemma instruction_op1_match_eq (i : instruction) (op1 : op1_spec) (h : i.op0_reg = op0.op0_reg) (h' : i.off_op0.to_natr = nat_clip op0.off_op0) (h'' : i.off_op1.to_natr = nat_clip op1.op1) : (instruction.op1._match_1 i mem s op1.op1_imm op1.op1_fp op1.op1_ap) = some (compute_op1 mem s op0 op1) := begin cases op1 with op1 op1 op1 op1; simp [instruction.op1._match_1, instruction.op0, h]; cases op0 with op0 op0; simp [bitvec.to_biased_16, h', h'']; refl end lemma instruction_res_aux_match_eq (i : instruction) (h : i.op0_reg = op0.op0_reg) (h' : i.off_op0.to_natr = nat_clip op0.off_op0) : instruction.res_aux._match_1 i mem s (some (compute_op1 mem s op0 res.to_op1)) res.res_add res.res_mul = some (compute_res mem s op0 res) := begin cases res with op1 op1 op1; simp [instruction.res_aux._match_1, instruction.op0, h, h']; cases op0 with op0 op0; simp [h', bitvec.to_biased_16]; try {refl}; {left, refl} end variable [decidable_eq F] theorem next_state_assert_eq : (assert_eq_instr op0 res dst ap_update).next_state mem s t ↔ (t.pc = bump_pc s res.to_op1.op1_imm ∧ t.ap = bump_ap s ap_update ∧ t.fp = s.fp ∧ compute_dst mem s dst = compute_res mem s op0 res) := begin simp [instr.next_state, assert_eq_instr, instruction.next_state, option.agrees, instruction.next_pc, instruction.size, instruction.next_fp, instruction.next_ap, instruction.asserts, instruction.dst, instruction.next_ap_aux], apply and_congr, { cases res.to_op1.op1_imm; simp; split; apply eq.symm }, repeat { apply and_congr, split; apply eq.symm }, transitivity ((some (compute_res mem s op0 res)).agrees (compute_dst mem s dst)), swap, { split; apply eq.symm }, congr', { simp [instruction.res, instruction.res_aux, instruction.op1], convert (instruction_res_aux_match_eq mem s op0 res _ _ _); try {simp}, convert (instruction_op1_match_eq mem s op0 _ _ _ _ _); simp [nat_clip] }, cases dst; simp [bitvec.to_biased_16]; refl end theorem next_state_jump (jump_abs : bool) : (jump_instr jump_abs op0 res ap_update).next_state mem s t ↔ (t.pc = jump_pc s jump_abs (compute_res mem s op0 res) ∧ t.ap = bump_ap s ap_update ∧ t.fp = s.fp) := begin simp [instr.next_state, jump_instr, instruction.next_state, option.agrees, instruction.next_pc, instruction.size, instruction.next_fp, instruction.next_ap, instruction.asserts, instruction.dst, instruction.next_ap_aux], apply and_congr, swap, { split; rintros ⟨h1, h2⟩; rw [h1, h2]; split; trivial }, apply agrees_iff_of_eq_some, cases jump_abs; simp [instruction.next_pc._match_1, instruction.res, instruction.res_aux], swap, { convert (instruction_res_aux_match_eq mem s op0 res _ _ _); try {simp}, convert (instruction_op1_match_eq mem s op0 _ _ _ _ _); simp [nat_clip] }, transitivity (instruction.next_pc._match_2 s (some (compute_res mem s op0 res))), swap, { refl }, congr', convert (instruction_res_aux_match_eq mem s op0 res _ _ _); try {simp}, convert (instruction_op1_match_eq mem s op0 _ _ _ _ _); simp [nat_clip] end theorem next_state_jnz (op1 : op1_spec) : (jnz_instr op0 op1 dst ap_update).next_state mem s t ↔ ((t.pc = if compute_dst mem s dst = 0 then bump_pc s op1.op1_imm else s.pc + compute_op1 mem s op0 op1) ∧ t.ap = bump_ap s ap_update ∧ t.fp = s.fp) := begin simp [instr.next_state, jnz_instr, instruction.next_state, option.agrees, instruction.next_pc, instruction.size, instruction.next_fp, instruction.next_ap, instruction.asserts, instruction.dst, instruction.next_ap_aux], apply and_congr, swap, { split; rintros ⟨h1, h2⟩; rw [h1, h2]; split; trivial }, apply agrees_iff_of_eq_some, rw some_if, congr', { cases dst with dst_reg dst_off; simp [bitvec.to_biased_16]; refl }, { cases op1.op1_imm; simp; refl }, transitivity (instruction.next_pc._match_3 s (some (compute_op1 mem s op0 op1))), swap, { refl }, congr', convert (instruction_op1_match_eq mem s op0 _ _ _ _ _); simp [nat_clip] end theorem next_state_call (call_abs : bool) : (call_instr call_abs res).next_state mem s t ↔ (t.pc = jump_pc s call_abs (compute_res mem s (op0_spec.ap_plus 1) res) ∧ t.ap = s.ap + 2 ∧ t.fp = s.ap + 2 ∧ mem (s.ap + 1) = bump_pc s res.to_op1.op1_imm ∧ mem s.ap = s.fp) := begin simp [instr.next_state, call_instr, instruction.next_state, option.agrees, instruction.next_pc, instruction.size, instruction.next_fp, instruction.next_ap, instruction.asserts, instruction.dst, instruction.next_ap_aux], apply and_congr, swap, { apply and_congr, { split; intro h; rw h }, apply and_congr, { split; intro h; rw h }, apply and_congr, { simp [instruction.op0, instruction.off_op0], rw [bitvec.to_biased_16, instr.off_op0_to_instruction], dsimp, rw [←int_clip_eq', @int_clip_eq]; norm_num, cases res.to_op1.op1_imm; simp, refl }, rw [bitvec.to_biased_16, instr.off_dst_to_instruction], dsimp, rw [←int_clip_eq', @int_clip_eq]; norm_num }, apply agrees_iff_of_eq_some, cases call_abs; simp [instruction.next_pc._match_1, instruction.res, instruction.res_aux], { transitivity (instruction.next_pc._match_2 s (some (compute_res mem s 'op0[ap+ 1] res))), swap, { refl }, congr', convert (instruction_res_aux_match_eq mem s 'op0[ap+ 1] res _ _ _); try { simp [checked] }, convert (instruction_op1_match_eq mem s 'op0[ap+ 1] _ _ _ _ _); simp [nat_clip, checked] }, convert (instruction_res_aux_match_eq mem s 'op0[ap+ 1] res _ _ _); try { simp [checked] }, convert (instruction_op1_match_eq mem s 'op0[ap+ 1] _ _ _ _ _); simp [nat_clip, checked], end theorem next_state_ret : ret_instr.next_state mem s t ↔ (t.pc = mem (s.fp + -1) ∧ t.ap = s.ap ∧ t.fp = mem (s.fp - 2)) := begin simp [instr.next_state, ret_instr, instruction.next_state, option.agrees, instruction.next_pc, instruction.size, instruction.next_fp, instruction.next_ap, instruction.asserts, instruction.dst, instruction.next_ap_aux, instruction.res, instruction.res_aux, instruction.res_aux._match_1, instruction.op1], rw [bitvec.to_biased_16, instr.off_op1_to_instruction], dsimp, rw [bitvec.to_biased_16, instr.off_dst_to_instruction], dsimp, rw [←int_clip_eq', ←int_clip_eq', int_clip_eq, int_clip_eq, sub_eq_add_neg]; norm_num, repeat { apply and_congr, split; apply eq.symm }, split; apply eq.symm end theorem next_state_advance_ap : (advance_ap_instr op0 res).next_state mem s t ↔ (t.pc = bump_pc s res.to_op1.op1_imm ∧ t.ap = s.ap + compute_res mem s op0 res ∧ t.fp = s.fp) := begin simp [instr.next_state, advance_ap_instr, instruction.next_state, option.agrees, instruction.next_pc, instruction.size, instruction.next_fp, instruction.next_ap, instruction.asserts, instruction.dst, instruction.next_ap_aux, instruction.res, instruction.res_aux, instruction.op1], apply and_congr, { cases res.to_op1.op1_imm; simp; split; apply eq.symm }, apply and_congr, swap, { split; apply eq.symm }, apply agrees_iff_of_eq_some, have : ∀ (s : register_state F) x y, x = some y → instruction.next_ap_aux._match_2 s x = some (s.ap + y), { rintros s x y rfl, simp [instruction.next_ap_aux._match_2] }, apply this s, convert (instruction_res_aux_match_eq mem s op0 res _ _ _); try {simp}, convert (instruction_op1_match_eq mem s op0 _ _ _ _ _); simp [nat_clip] end end
244cb0c16e8d730edb515ea56fae4a670bf1669e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_tuple2.lean
cbcba8d9aeaf575f5495bee1d767adaa2beac1b4
[ "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
3,340
lean
import data.fin open function constant tuple.{l} : Type.{l} → nat → Type.{l} constant nil {A : Type} : tuple A 0 constant cons {A : Type} {n : nat} : A → tuple A n → tuple A (nat.succ n) constant append {A : Type} {n m : nat} : tuple A n → tuple A m → tuple A (n + m) constant reverse {A : Type} {n : nat} : tuple A n → tuple A n constant map {A B : Type} {n : nat} : (A → B) → tuple A n → tuple B n constant ith {A : Type} {n : nat} : tuple A n → fin n → A constant tail {A : Type} {n : nat} : tuple A (nat.succ n) → tuple A n infix ` ++ ` := append axiom append_nil {A : Type} {n : nat} (v : tuple A n) : v ++ nil = v axiom nil_append {A : Type} {n : nat} (v : tuple A n) : nil ++ v == v axiom append_assoc {A : Type} {n₁ n₂ n₃ : nat} (v₁ : tuple A n₁) (v₂ : tuple A n₂) (v₃ : tuple A n₃) : (v₁ ++ v₂) ++ v₃ == v₁ ++ (v₂ ++ v₃) axiom reverse_reverse {A : Type} {n : nat} (v : tuple A n) : reverse (reverse v) = v axiom map_cons {A B : Type} {n : nat} (f : A → B) (a : A) (v : tuple A n) : map f (cons a v) = cons (f a) (map f v) axiom map_map {A B C : Type} {n : nat} (g : B → C) (f : A → B) (v : tuple A n) : map g (map f v) = map (g ∘ f) v axiom ith_succ_eq_ith_tail {A : Type} {n : nat} (v : tuple A (nat.succ n)) (i : fin n) : ith v (fin.succ i) = ith (tail v) i attribute append_nil nil_append append_assoc reverse_reverse map_cons map_map ith_succ_eq_ith_tail [simp] set_option blast.strategy "cc" set_option blast.cc.heq true set_option blast.cc.subsingleton true universes l1 l2 l3 constants {A : Type.{l1}} (a b c : A) (f g : A → A) (m n p q : ℕ) (xs : tuple A m) (ys : tuple A n) (zs : tuple A p) (ws : tuple A q) {B : Type.{l2}} (h1 h2 : A → B) {C : Type.{l3}} (k1 k2 : B → C) example : a = b → m = n → xs == ys → cons a xs == cons b ys := by blast example : a = b → b = c → m = n → n = p → xs == ys → ys == zs → cons a (cons b xs) == cons c (cons a zs) := by blast example : a = b → b = c → m = n → n = p → xs == ys → ys == zs → cons (f a) (cons (g b) xs) == cons (f c) (cons (g a) zs) := by blast example : m = n → xs == ys → xs ++ zs == ys ++ zs := by blast example : m = n → p = q → xs == ys → zs == ws → xs ++ zs == ys ++ ws := by blast example : m = n → xs == ys → nil ++ xs == ys := by inst_simp example : (xs ++ ys) ++ zs == xs ++ (ys ++ zs) := by inst_simp example : p = m + n → zs == xs ++ ys → zs ++ ws == (xs ++ ys) ++ ws := by inst_simp example : m + n = p → xs ++ ys == zs → zs ++ ws == xs ++ (ys ++ ws) := by inst_simp example : m = n → p = q → m + n = p → xs == ys → zs == ws → xs ++ ys == zs → ws ++ ws == (ys ++ xs) ++ (xs ++ ys) := by inst_simp example : m = n → n = p → xs == reverse ys → ys == reverse zs → xs == zs := by inst_simp example : m = n → xs == ys → f = g → a = b → map f (cons a xs) == cons (g b) (map g ys) := by inst_simp attribute function.comp [semireducible] example : m = n → xs == ys → h1 = h2 → k1 = k2 → map k1 (map h1 xs) == map (k2 ∘ h2) ys := by inst_simp example : ∀ (xs : tuple A (nat.succ m)) (ys : tuple A (nat.succ n)) (i : fin m) (j : fin n), m = n → i == j → xs == ys → ith xs (fin.succ i) == ith (tail ys) j := by inst_simp
942addefaf03d2c1f0914fc60505db68e9b59ef6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/eigenspace.lean
adcae415e2635c64918aabc9a219c9214dd63cf9
[ "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
24,980
lean
/- Copyright (c) 2020 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import field_theory.algebraic_closure import linear_algebra.finsupp import linear_algebra.matrix.to_lin import order.preorder_hom /-! # Eigenvectors and eigenvalues This file defines eigenspaces, eigenvalues, and eigenvalues, as well as their generalized counterparts. We follow Axler's approach [axler2015] because it allows us to derive many properties without choosing a basis and without using matrices. An eigenspace of a linear map `f` for a scalar `μ` is the kernel of the map `(f - μ • id)`. The nonzero elements of an eigenspace are eigenvectors `x`. They have the property `f x = μ • x`. If there are eigenvectors for a scalar `μ`, the scalar `μ` is called an eigenvalue. There is no consensus in the literature whether `0` is an eigenvector. Our definition of `has_eigenvector` permits only nonzero vectors. For an eigenvector `x` that may also be `0`, we write `x ∈ f.eigenspace μ`. A generalized eigenspace of a linear map `f` for a natural number `k` and a scalar `μ` is the kernel of the map `(f - μ • id) ^ k`. The nonzero elements of a generalized eigenspace are generalized eigenvectors `x`. If there are generalized eigenvectors for a natural number `k` and a scalar `μ`, the scalar `μ` is called a generalized eigenvalue. ## References * [Sheldon Axler, *Linear Algebra Done Right*][axler2015] * https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors ## Tags eigenspace, eigenvector, eigenvalue, eigen -/ universes u v w namespace module namespace End open module principal_ideal_ring polynomial finite_dimensional variables {K R : Type v} {V M : Type w} [comm_ring R] [add_comm_group M] [module R M] [field K] [add_comm_group V] [module K V] /-- The submodule `eigenspace f μ` for a linear map `f` and a scalar `μ` consists of all vectors `x` such that `f x = μ • x`. (Def 5.36 of [axler2015])-/ def eigenspace (f : End R M) (μ : R) : submodule R M := (f - algebra_map R (End R M) μ).ker /-- A nonzero element of an eigenspace is an eigenvector. (Def 5.7 of [axler2015]) -/ def has_eigenvector (f : End R M) (μ : R) (x : M) : Prop := x ∈ eigenspace f μ ∧ x ≠ 0 /-- A scalar `μ` is an eigenvalue for a linear map `f` if there are nonzero vectors `x` such that `f x = μ • x`. (Def 5.5 of [axler2015]) -/ def has_eigenvalue (f : End R M) (a : R) : Prop := eigenspace f a ≠ ⊥ lemma has_eigenvalue_of_has_eigenvector {f : End R M} {μ : R} {x : M} (h : has_eigenvector f μ x) : has_eigenvalue f μ := begin rw [has_eigenvalue, submodule.ne_bot_iff], use x, exact h, end lemma mem_eigenspace_iff {f : End R M} {μ : R} {x : M} : x ∈ eigenspace f μ ↔ f x = μ • x := by rw [eigenspace, linear_map.mem_ker, linear_map.sub_apply, algebra_map_End_apply, sub_eq_zero] lemma eigenspace_div (f : End K V) (a b : K) (hb : b ≠ 0) : eigenspace f (a / b) = (b • f - algebra_map K (End K V) a).ker := calc eigenspace f (a / b) = eigenspace f (b⁻¹ * a) : by { rw [div_eq_mul_inv, mul_comm] } ... = (f - (b⁻¹ * a) • linear_map.id).ker : rfl ... = (f - b⁻¹ • a • linear_map.id).ker : by rw smul_smul ... = (f - b⁻¹ • algebra_map K (End K V) a).ker : rfl ... = (b • (f - b⁻¹ • algebra_map K (End K V) a)).ker : by rw linear_map.ker_smul _ b hb ... = (b • f - algebra_map K (End K V) a).ker : by rw [smul_sub, smul_inv_smul' hb] lemma eigenspace_aeval_polynomial_degree_1 (f : End K V) (q : polynomial K) (hq : degree q = 1) : eigenspace f (- q.coeff 0 / q.leading_coeff) = (aeval f q).ker := calc eigenspace f (- q.coeff 0 / q.leading_coeff) = (q.leading_coeff • f - algebra_map K (End K V) (- q.coeff 0)).ker : by { rw eigenspace_div, intro h, rw leading_coeff_eq_zero_iff_deg_eq_bot.1 h at hq, cases hq } ... = (aeval f (C q.leading_coeff * X + C (q.coeff 0))).ker : by { rw [C_mul', aeval_def], simpa [algebra_map, algebra.to_ring_hom], } ... = (aeval f q).ker : by { congr, apply (eq_X_add_C_of_degree_eq_one hq).symm } lemma ker_aeval_ring_hom'_unit_polynomial (f : End K V) (c : units (polynomial K)) : (aeval f (c : polynomial K)).ker = ⊥ := begin rw polynomial.eq_C_of_degree_eq_zero (degree_coe_units c), simp only [aeval_def, eval₂_C], apply ker_algebra_map_End, apply coeff_coe_units_zero_ne_zero c end theorem aeval_apply_of_has_eigenvector {f : End K V} {p : polynomial K} {μ : K} {x : V} (h : f.has_eigenvector μ x) : aeval f p x = (p.eval μ) • x := begin apply p.induction_on, { intro a, simp [module.algebra_map_End_apply] }, { intros p q hp hq, simp [hp, hq, add_smul] }, { intros n a hna, rw [mul_comm, pow_succ, mul_assoc, alg_hom.map_mul, linear_map.mul_apply, mul_comm, hna], simp [algebra_map_End_apply, mem_eigenspace_iff.1 h.1, smul_smul, mul_comm] } end section minpoly theorem is_root_of_has_eigenvalue {f : End K V} {μ : K} (h : f.has_eigenvalue μ) : (minpoly K f).is_root μ := begin rcases (submodule.ne_bot_iff _).1 h with ⟨w, ⟨H, ne0⟩⟩, refine or.resolve_right (smul_eq_zero.1 _) ne0, simp [← aeval_apply_of_has_eigenvector ⟨H, ne0⟩, minpoly.aeval K f], end variables [finite_dimensional K V] (f : End K V) protected theorem is_integral : is_integral K f := is_integral_of_noetherian (by apply_instance) f variables {f} {μ : K} theorem has_eigenvalue_of_is_root (h : (minpoly K f).is_root μ) : f.has_eigenvalue μ := begin cases dvd_iff_is_root.2 h with p hp, rw [has_eigenvalue, eigenspace], intro con, cases (linear_map.is_unit_iff _).2 con with u hu, have p_ne_0 : p ≠ 0, { intro con, apply minpoly.ne_zero f.is_integral, rw [hp, con, mul_zero] }, have h_deg := minpoly.degree_le_of_ne_zero K f p_ne_0 _, { rw [hp, degree_mul, degree_X_sub_C, polynomial.degree_eq_nat_degree p_ne_0] at h_deg, norm_cast at h_deg, linarith, }, { have h_aeval := minpoly.aeval K f, revert h_aeval, simp [hp, ← hu] }, end theorem has_eigenvalue_iff_is_root : f.has_eigenvalue μ ↔ (minpoly K f).is_root μ := ⟨is_root_of_has_eigenvalue, has_eigenvalue_of_is_root⟩ end minpoly /-- Every linear operator on a vector space over an algebraically closed field has an eigenvalue. -/ -- This is Lemma 5.21 of [axler2015], although we are no longer following that proof. lemma exists_eigenvalue [is_alg_closed K] [finite_dimensional K V] [nontrivial V] (f : End K V) : ∃ (c : K), f.has_eigenvalue c := begin obtain ⟨c, nu⟩ := exists_spectrum_of_is_alg_closed_of_finite_dimensional K f, use c, rw linear_map.is_unit_iff at nu, exact has_eigenvalue_of_has_eigenvector (exists_mem_ne_zero_of_ne_bot nu).some_spec, end /-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly independent. (Lemma 5.10 of [axler2015]) We use the eigenvalues as indexing set to ensure that there is only one eigenvector for each eigenvalue in the image of `xs`. -/ lemma eigenvectors_linear_independent (f : End K V) (μs : set K) (xs : μs → V) (h_eigenvec : ∀ μ : μs, f.has_eigenvector μ (xs μ)) : linear_independent K xs := begin classical, -- We need to show that if a linear combination `l` of the eigenvectors `xs` is `0`, then all -- its coefficients are zero. suffices : ∀ l, finsupp.total μs V K xs l = 0 → l = 0, { rw linear_independent_iff, apply this }, intros l hl, -- We apply induction on the finite set of eigenvalues whose eigenvectors have nonzero -- coefficients, i.e. on the support of `l`. induction h_l_support : l.support using finset.induction with μ₀ l_support' hμ₀ ih generalizing l, -- If the support is empty, all coefficients are zero and we are done. { exact finsupp.support_eq_empty.1 h_l_support }, -- Now assume that the support of `l` contains at least one eigenvalue `μ₀`. We define a new -- linear combination `l'` to apply the induction hypothesis on later. The linear combination `l'` -- is derived from `l` by multiplying the coefficient of the eigenvector with eigenvalue `μ` -- by `μ - μ₀`. -- To get started, we define `l'` as a function `l'_f : μs → K` with potentially infinite support. { let l'_f : μs → K := (λ μ : μs, (↑μ - ↑μ₀) * l μ), -- The support of `l'_f` is the support of `l` without `μ₀`. have h_l_support' : ∀ (μ : μs), μ ∈ l_support' ↔ l'_f μ ≠ 0 , { intro μ, suffices : μ ∈ l_support' → μ ≠ μ₀, { simp [l'_f, ← finsupp.not_mem_support_iff, h_l_support, sub_eq_zero, ←subtype.ext_iff], tauto }, rintro hμ rfl, contradiction }, -- Now we can define `l'_f` as an actual linear combination `l'` because we know that the -- support is finite. let l' : μs →₀ K := { to_fun := l'_f, support := l_support', mem_support_to_fun := h_l_support' }, -- The linear combination `l'` over `xs` adds up to `0`. have total_l' : finsupp.total μs V K xs l' = 0, { let g := f - algebra_map K (End K V) μ₀, have h_gμ₀: g (l μ₀ • xs μ₀) = 0, by rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).1, algebra_map_End_apply, sub_self, smul_zero], have h_useless_filter : finset.filter (λ (a : μs), l'_f a ≠ 0) l_support' = l_support', { rw finset.filter_congr _, { apply finset.filter_true }, { apply_instance }, exact λ μ hμ, (iff_true _).mpr ((h_l_support' μ).1 hμ) }, have bodies_eq : ∀ (μ : μs), l'_f μ • xs μ = g (l μ • xs μ), { intro μ, dsimp only [g, l'_f], rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).1, algebra_map_End_apply, ←sub_smul, smul_smul, mul_comm] }, rw [←linear_map.map_zero g, ←hl, finsupp.total_apply, finsupp.total_apply, finsupp.sum, finsupp.sum, linear_map.map_sum, h_l_support, finset.sum_insert hμ₀, h_gμ₀, zero_add], refine finset.sum_congr rfl (λ μ _, _), apply bodies_eq }, -- Therefore, by the induction hypothesis, all coefficients in `l'` are zero. have l'_eq_0 : l' = 0 := ih l' total_l' rfl, -- By the defintion of `l'`, this means that `(μ - μ₀) * l μ = 0` for all `μ`. have h_mul_eq_0 : ∀ μ : μs, (↑μ - ↑μ₀) * l μ = 0, { intro μ, calc (↑μ - ↑μ₀) * l μ = l' μ : rfl ... = 0 : by { rw [l'_eq_0], refl } }, -- Thus, the coefficients in `l` for all `μ ≠ μ₀` are `0`. have h_lμ_eq_0 : ∀ μ : μs, μ ≠ μ₀ → l μ = 0, { intros μ hμ, apply or_iff_not_imp_left.1 (mul_eq_zero.1 (h_mul_eq_0 μ)), rwa [sub_eq_zero, ←subtype.ext_iff] }, -- So if we sum over all these coefficients, we obtain `0`. have h_sum_l_support'_eq_0 : finset.sum l_support' (λ (μ : ↥μs), l μ • xs μ) = 0, { rw ←finset.sum_const_zero, apply finset.sum_congr rfl, intros μ hμ, rw h_lμ_eq_0, apply zero_smul, intro h, rw h at hμ, contradiction }, -- The only potentially nonzero coefficient in `l` is the one corresponding to `μ₀`. But since -- the overall sum is `0` by assumption, this coefficient must also be `0`. have : l μ₀ = 0, { rw [finsupp.total_apply, finsupp.sum, h_l_support, finset.sum_insert hμ₀, h_sum_l_support'_eq_0, add_zero] at hl, by_contra h, exact (h_eigenvec μ₀).2 ((smul_eq_zero.1 hl).resolve_left h) }, -- Thus, all coefficients in `l` are `0`. show l = 0, { ext μ, by_cases h_cases : μ = μ₀, { rw h_cases, assumption }, exact h_lμ_eq_0 μ h_cases } } end /-- The generalized eigenspace for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the kernel of `(f - μ • id) ^ k`. (Def 8.10 of [axler2015]). Furthermore, a generalized eigenspace for some exponent `k` is contained in the generalized eigenspace for exponents larger than `k`. -/ def generalized_eigenspace (f : End R M) (μ : R) : ℕ →ₘ submodule R M := { to_fun := λ k, ((f - algebra_map R (End R M) μ) ^ k).ker, monotone' := λ k m hm, begin simp only [← pow_sub_mul_pow _ hm], exact linear_map.ker_le_ker_comp ((f - algebra_map R (End R M) μ) ^ k) ((f - algebra_map R (End R M) μ) ^ (m - k)), end } @[simp] lemma mem_generalized_eigenspace (f : End R M) (μ : R) (k : ℕ) (m : M) : m ∈ f.generalized_eigenspace μ k ↔ ((f - μ • 1)^k) m = 0 := iff.rfl /-- A nonzero element of a generalized eigenspace is a generalized eigenvector. (Def 8.9 of [axler2015])-/ def has_generalized_eigenvector (f : End R M) (μ : R) (k : ℕ) (x : M) : Prop := x ≠ 0 ∧ x ∈ generalized_eigenspace f μ k /-- A scalar `μ` is a generalized eigenvalue for a linear map `f` and an exponent `k ∈ ℕ` if there are generalized eigenvectors for `f`, `k`, and `μ`. -/ def has_generalized_eigenvalue (f : End R M) (μ : R) (k : ℕ) : Prop := generalized_eigenspace f μ k ≠ ⊥ /-- The generalized eigenrange for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the range of `(f - μ • id) ^ k`. -/ def generalized_eigenrange (f : End R M) (μ : R) (k : ℕ) : submodule R M := ((f - algebra_map R (End R M) μ) ^ k).range /-- The exponent of a generalized eigenvalue is never 0. -/ lemma exp_ne_zero_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ} (h : f.has_generalized_eigenvalue μ k) : k ≠ 0 := begin rintro rfl, exact h linear_map.ker_id end /-- The union of the kernels of `(f - μ • id) ^ k` over all `k`. -/ def maximal_generalized_eigenspace (f : End R M) (μ : R) : submodule R M := ⨆ k, f.generalized_eigenspace μ k lemma generalized_eigenspace_le_maximal (f : End R M) (μ : R) (k : ℕ) : f.generalized_eigenspace μ k ≤ f.maximal_generalized_eigenspace μ := le_supr _ _ @[simp] lemma mem_maximal_generalized_eigenspace (f : End R M) (μ : R) (m : M) : m ∈ f.maximal_generalized_eigenspace μ ↔ ∃ (k : ℕ), ((f - μ • 1)^k) m = 0 := by simp only [maximal_generalized_eigenspace, ← mem_generalized_eigenspace, submodule.mem_supr_of_chain] /-- If there exists a natural number `k` such that the kernel of `(f - μ • id) ^ k` is the maximal generalized eigenspace, then this value is the least such `k`. If not, this value is not meaningful. -/ noncomputable def maximal_generalized_eigenspace_index (f : End R M) (μ : R) := monotonic_sequence_limit_index (f.generalized_eigenspace μ) /-- For an endomorphism of a Noetherian module, the maximal eigenspace is always of the form kernel `(f - μ • id) ^ k` for some `k`. -/ lemma maximal_generalized_eigenspace_eq [h : is_noetherian R M] (f : End R M) (μ : R) : maximal_generalized_eigenspace f μ = f.generalized_eigenspace μ (maximal_generalized_eigenspace_index f μ) := begin rw is_noetherian_iff_well_founded at h, exact (well_founded.supr_eq_monotonic_sequence_limit h (f.generalized_eigenspace μ) : _), end /-- A generalized eigenvalue for some exponent `k` is also a generalized eigenvalue for exponents larger than `k`. -/ lemma has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le {f : End R M} {μ : R} {k : ℕ} {m : ℕ} (hm : k ≤ m) (hk : f.has_generalized_eigenvalue μ k) : f.has_generalized_eigenvalue μ m := begin unfold has_generalized_eigenvalue at *, contrapose! hk, rw [←le_bot_iff, ←hk], exact (f.generalized_eigenspace μ).monotone hm, end /-- The eigenspace is a subspace of the generalized eigenspace. -/ lemma eigenspace_le_generalized_eigenspace {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) : f.eigenspace μ ≤ f.generalized_eigenspace μ k := (f.generalized_eigenspace μ).monotone (nat.succ_le_of_lt hk) /-- All eigenvalues are generalized eigenvalues. -/ lemma has_generalized_eigenvalue_of_has_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) (hμ : f.has_eigenvalue μ) : f.has_generalized_eigenvalue μ k := begin apply has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le hk, rw [has_generalized_eigenvalue, generalized_eigenspace, preorder_hom.coe_fun_mk, pow_one], exact hμ, end /-- All generalized eigenvalues are eigenvalues. -/ lemma has_eigenvalue_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hμ : f.has_generalized_eigenvalue μ k) : f.has_eigenvalue μ := begin intros contra, apply hμ, erw linear_map.ker_eq_bot at ⊢ contra, rw linear_map.coe_pow, exact function.injective.iterate contra k, end /-- Generalized eigenvalues are actually just eigenvalues. -/ @[simp] lemma has_generalized_eigenvalue_iff_has_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) : f.has_generalized_eigenvalue μ k ↔ f.has_eigenvalue μ := ⟨has_eigenvalue_of_has_generalized_eigenvalue, has_generalized_eigenvalue_of_has_eigenvalue hk⟩ /-- Every generalized eigenvector is a generalized eigenvector for exponent `finrank K V`. (Lemma 8.11 of [axler2015]) -/ lemma generalized_eigenspace_le_generalized_eigenspace_finrank [finite_dimensional K V] (f : End K V) (μ : K) (k : ℕ) : f.generalized_eigenspace μ k ≤ f.generalized_eigenspace μ (finrank K V) := ker_pow_le_ker_pow_finrank _ _ /-- Generalized eigenspaces for exponents at least `finrank K V` are equal to each other. -/ lemma generalized_eigenspace_eq_generalized_eigenspace_finrank_of_le [finite_dimensional K V] (f : End K V) (μ : K) {k : ℕ} (hk : finrank K V ≤ k) : f.generalized_eigenspace μ k = f.generalized_eigenspace μ (finrank K V) := ker_pow_eq_ker_pow_finrank_of_le hk /-- If `f` maps a subspace `p` into itself, then the generalized eigenspace of the restriction of `f` to `p` is the part of the generalized eigenspace of `f` that lies in `p`. -/ lemma generalized_eigenspace_restrict (f : End R M) (p : submodule R M) (k : ℕ) (μ : R) (hfp : ∀ (x : M), x ∈ p → f x ∈ p) : generalized_eigenspace (linear_map.restrict f hfp) μ k = submodule.comap p.subtype (f.generalized_eigenspace μ k) := begin simp only [generalized_eigenspace, preorder_hom.coe_fun_mk, ← linear_map.ker_comp], induction k with k ih, { rw [pow_zero, pow_zero, linear_map.one_eq_id], apply (submodule.ker_subtype _).symm }, { erw [pow_succ', pow_succ', linear_map.ker_comp, ih, ←linear_map.ker_comp, linear_map.comp_assoc], } end /-- Generalized eigenrange and generalized eigenspace for exponent `finrank K V` are disjoint. -/ lemma generalized_eigenvec_disjoint_range_ker [finite_dimensional K V] (f : End K V) (μ : K) : disjoint (f.generalized_eigenrange μ (finrank K V)) (f.generalized_eigenspace μ (finrank K V)) := begin have h := calc submodule.comap ((f - algebra_map _ _ μ) ^ finrank K V) (f.generalized_eigenspace μ (finrank K V)) = ((f - algebra_map _ _ μ) ^ finrank K V * (f - algebra_map K (End K V) μ) ^ finrank K V).ker : by { simpa only [generalized_eigenspace, preorder_hom.coe_fun_mk, ← linear_map.ker_comp] } ... = f.generalized_eigenspace μ (finrank K V + finrank K V) : by { rw ←pow_add, refl } ... = f.generalized_eigenspace μ (finrank K V) : by { rw generalized_eigenspace_eq_generalized_eigenspace_finrank_of_le, linarith }, rw [disjoint, generalized_eigenrange, linear_map.range_eq_map, submodule.map_inf_eq_map_inf_comap, top_inf_eq, h], apply submodule.map_comap_le end /-- The generalized eigenspace of an eigenvalue has positive dimension for positive exponents. -/ lemma pos_finrank_generalized_eigenspace_of_has_eigenvalue [finite_dimensional K V] {f : End K V} {k : ℕ} {μ : K} (hx : f.has_eigenvalue μ) (hk : 0 < k): 0 < finrank K (f.generalized_eigenspace μ k) := calc 0 = finrank K (⊥ : submodule K V) : by rw finrank_bot ... < finrank K (f.eigenspace μ) : submodule.finrank_lt_finrank_of_lt (bot_lt_iff_ne_bot.2 hx) ... ≤ finrank K (f.generalized_eigenspace μ k) : submodule.finrank_mono ((f.generalized_eigenspace μ).monotone (nat.succ_le_of_lt hk)) /-- A linear map maps a generalized eigenrange into itself. -/ lemma map_generalized_eigenrange_le {f : End K V} {μ : K} {n : ℕ} : submodule.map f (f.generalized_eigenrange μ n) ≤ f.generalized_eigenrange μ n := calc submodule.map f (f.generalized_eigenrange μ n) = (f * ((f - algebra_map _ _ μ) ^ n)).range : (linear_map.range_comp _ _).symm ... = (((f - algebra_map _ _ μ) ^ n) * f).range : by rw algebra.mul_sub_algebra_map_pow_commutes ... = submodule.map ((f - algebra_map _ _ μ) ^ n) f.range : linear_map.range_comp _ _ ... ≤ f.generalized_eigenrange μ n : linear_map.map_le_range /-- The generalized eigenvectors span the entire vector space (Lemma 8.21 of [axler2015]). -/ lemma supr_generalized_eigenspace_eq_top [is_alg_closed K] [finite_dimensional K V] (f : End K V) : (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤ := begin tactic.unfreeze_local_instances, -- We prove the claim by strong induction on the dimension of the vector space. induction h_dim : finrank K V using nat.strong_induction_on with n ih generalizing V, cases n, -- If the vector space is 0-dimensional, the result is trivial. { rw ←top_le_iff, simp only [finrank_eq_zero.1 (eq.trans finrank_top h_dim), bot_le] }, -- Otherwise the vector space is nontrivial. { haveI : nontrivial V := finrank_pos_iff.1 (by { rw h_dim, apply nat.zero_lt_succ }), -- Hence, `f` has an eigenvalue `μ₀`. obtain ⟨μ₀, hμ₀⟩ : ∃ μ₀, f.has_eigenvalue μ₀ := exists_eigenvalue f, -- We define `ES` to be the generalized eigenspace let ES := f.generalized_eigenspace μ₀ (finrank K V), -- and `ER` to be the generalized eigenrange. let ER := f.generalized_eigenrange μ₀ (finrank K V), -- `f` maps `ER` into itself. have h_f_ER : ∀ (x : V), x ∈ ER → f x ∈ ER, from λ x hx, map_generalized_eigenrange_le (submodule.mem_map_of_mem hx), -- Therefore, we can define the restriction `f'` of `f` to `ER`. let f' : End K ER := f.restrict h_f_ER, -- The dimension of `ES` is positive have h_dim_ES_pos : 0 < finrank K ES, { dsimp only [ES], rw h_dim, apply pos_finrank_generalized_eigenspace_of_has_eigenvalue hμ₀ (nat.zero_lt_succ n) }, -- and the dimensions of `ES` and `ER` add up to `finrank K V`. have h_dim_add : finrank K ER + finrank K ES = finrank K V, { apply linear_map.finrank_range_add_finrank_ker }, -- Therefore the dimension `ER` mus be smaller than `finrank K V`. have h_dim_ER : finrank K ER < n.succ, by linarith, -- This allows us to apply the induction hypothesis on `ER`: have ih_ER : (⨆ (μ : K) (k : ℕ), f'.generalized_eigenspace μ k) = ⊤, from ih (finrank K ER) h_dim_ER f' rfl, -- The induction hypothesis gives us a statement about subspaces of `ER`. We can transfer this -- to a statement about subspaces of `V` via `submodule.subtype`: have ih_ER' : (⨆ (μ : K) (k : ℕ), (f'.generalized_eigenspace μ k).map ER.subtype) = ER, by simp only [(submodule.map_supr _ _).symm, ih_ER, submodule.map_subtype_top ER], -- Moreover, every generalized eigenspace of `f'` is contained in the corresponding generalized -- eigenspace of `f`. have hff' : ∀ μ k, (f'.generalized_eigenspace μ k).map ER.subtype ≤ f.generalized_eigenspace μ k, { intros, rw generalized_eigenspace_restrict, apply submodule.map_comap_le }, -- It follows that `ER` is contained in the span of all generalized eigenvectors. have hER : ER ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, { rw ← ih_ER', apply supr_le_supr _, exact λ μ, supr_le_supr (λ k, hff' μ k), }, -- `ES` is contained in this span by definition. have hES : ES ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, from le_trans (le_supr (λ k, f.generalized_eigenspace μ₀ k) (finrank K V)) (le_supr (λ (μ : K), ⨆ (k : ℕ), f.generalized_eigenspace μ k) μ₀), -- Moreover, we know that `ER` and `ES` are disjoint. have h_disjoint : disjoint ER ES, from generalized_eigenvec_disjoint_range_ker f μ₀, -- Since the dimensions of `ER` and `ES` add up to the dimension of `V`, it follows that the -- span of all generalized eigenvectors is all of `V`. show (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤, { rw [←top_le_iff, ←submodule.eq_top_of_disjoint ER ES h_dim_add h_disjoint], apply sup_le hER hES } } end end End end module variables {K V : Type*} [field K] [add_comm_group V] [module K V] [finite_dimensional K V] protected lemma linear_map.is_integral (f : V →ₗ[K] V) : is_integral K f := module.End.is_integral f
1bae05b64927e01d91f16d44314cd9757462ecfe
abd85493667895c57a7507870867b28124b3998f
/src/data/fintype/card.lean
0cb2ad4e844e12009ec6a214eca34bf555d8753b
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
15,077
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.fintype.basic import data.nat.choose import tactic.ring /-! Results about "big operations" over a `fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `data.fintype`, but was moved here to avoid requiring `algebra.big_operators` (and hence many other imports) as a dependency of `fintype`. -/ universes u v variables {α : Type*} {β : Type*} {γ : Type*} open_locale big_operators namespace fintype lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 := finset.card_eq_sum_ones _ section open finset variables {ι : Type*} [fintype ι] [decidable_eq ι] @[to_additive] lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variables {M : Type*} [fintype α] [comm_monoid M] @[to_additive] lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : (∏ a, f a) = 1 := finset.prod_eq_one $ λ a ha, h a @[to_additive] lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) : (∏ a, f a) = ∏ a, g a := finset.prod_congr rfl $ λ a ha, h a @[to_additive] lemma prod_unique [unique β] (f : β → M) : (∏ x, f x) = f (default β) := by simp only [finset.prod_singleton, univ_unique] end end fintype open finset theorem fin.prod_univ_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.prod f = f 0 * univ.prod (λ i:fin n, f i.succ) := begin rw [fin.univ_succ, prod_insert, prod_image], { intros x _ y _ hxy, exact fin.succ.inj hxy }, { simpa using fin.succ_ne_zero } end @[simp, to_additive] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : univ.prod f = 1 := rfl theorem fin.sum_univ_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.sum f = f 0 + univ.sum (λ i:fin n, f i.succ) := by apply @fin.prod_univ_succ (multiplicative β) attribute [to_additive] fin.prod_univ_succ theorem fin.prod_univ_cast_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.prod f = univ.prod (λ i:fin n, f i.cast_succ) * f (fin.last n) := begin rw [fin.univ_cast_succ, prod_insert, prod_image, mul_comm], { intros x _ y _ hxy, exact fin.cast_succ_inj.mp hxy }, { simpa using fin.cast_succ_ne_last } end theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.sum f = univ.sum (λ i:fin n, f i.cast_succ) + f (fin.last n) := by apply @fin.prod_univ_cast_succ (multiplicative β) attribute [to_additive] fin.prod_univ_cast_succ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ -- FIXME ouch, this should be in the main file. @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by simp [sum.fintype, fintype.of_equiv_card] @[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α] {δ : α → Type*} (t : Π a, finset (δ a)) : (fintype.pi_finset t).card = finset.univ.prod (λ a, card (t a)) := by simp [fintype.pi_finset, card_map] @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := fintype.card_pi_finset _ -- FIXME ouch, this should be in the main file. @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) @[to_additive] lemma finset.range_prod_eq_univ_prod [comm_monoid β] (n : ℕ) (f : ℕ → β) : (range n).prod f = univ.prod (λ (k : fin n), f k) := begin symmetry, refine prod_bij (λ k hk, k) _ _ _ _, { rintro ⟨k, hk⟩ _, simp * }, { rintro ⟨k, hk⟩ _, simp * }, { intros, rwa fin.eq_iff_veq }, { intros k hk, rw mem_range at hk, exact ⟨⟨k, hk⟩, mem_univ _, rfl⟩ } end /-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`. -/ @[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`."] lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β] {δ : α → Type*} {t : Π (a : α), finset (δ a)} (f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) : (univ.pi t).prod f = (fintype.pi_finset t).prod (λ x, f (λ a _, x a)) := prod_bij (λ x _ a, x a (mem_univ _)) (by simp) (by simp) (by simp [function.funext_iff] {contextual := tt}) (λ x hx, ⟨λ a _, x a, by simp * at *⟩) /-- The product over `univ` of a sum can be written as a sum over the product of sets, `fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not over `univ` -/ lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1} [Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)} {f : Π (a : α), δ a → β} : univ.prod (λ a, (t a).sum (λ b, f a b)) = (fintype.pi_finset t).sum (λ p, univ.prod (λ x, f x (p x))) := by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi] /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n` gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that `x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead a proof reducing to the usual binomial theorem to have a result over semirings. -/ lemma fintype.sum_pow_mul_eq_add_pow (α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) : finset.univ.sum (λ (s : finset α), a ^ s.card * b ^ (fintype.card α - s.card)) = (a + b) ^ (fintype.card α) := finset.sum_pow_mul_eq_add_pow _ _ _ lemma fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) : finset.univ.sum (λ (s : finset (fin n)), a ^ s.card * b ^ (n - s.card)) = (a + b) ^ n := by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b /-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/ @[to_additive] lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) : finset.univ.prod (λ (i : fin n), f i.val) = (finset.range n).prod f := begin apply finset.prod_bij (λ (a : fin n) ha, a.val), { assume a ha, simp [a.2] }, { assume a ha, refl }, { assume a b ha hb H, exact (fin.ext_iff _ _).2 H }, { assume b hb, exact ⟨⟨b, list.mem_range.mp hb⟩, finset.mem_univ _, rfl⟩, } end @[to_additive] lemma finset.prod_equiv [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) : finset.univ.prod (f ∘ e) = finset.univ.prod f := begin apply prod_bij (λ i hi, e i) (λ i hi, mem_univ _) _ (λ a b _ _ h, e.injective h), { assume b hb, rcases e.surjective b with ⟨a, ha⟩, exact ⟨a, mem_univ _, ha.symm⟩, }, { simp } end @[to_additive] lemma finset.prod_subtype {M : Type*} [comm_monoid M] {p : α → Prop} {F : fintype (subtype p)} {s : finset α} (h : ∀ x, x ∈ s ↔ p x) (f : α → M) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, begin rw ← prod_attach, resetI, subst p, congr, simp [finset.ext] end @[to_additive] lemma finset.prod_fiberwise [fintype β] [decidable_eq β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) : ∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a := begin classical, have key : ∏ (b : β), ∏ a in s.filter (λ a, f a = b), g a = ∏ (a : α) in univ.bind (λ (b : β), s.filter (λ a, f a = b)), g a := (@prod_bind _ _ β g _ _ finset.univ (λ b : β, s.filter (λ a, f a = b)) _).symm, { simp only [key, filter_congr_decidable], apply finset.prod_congr, { ext, simp only [mem_bind, mem_filter, mem_univ, exists_prop_of_true, exists_eq_right'] }, { intros, refl } }, { intros x hx y hy H z hz, apply H, simp only [mem_filter, inf_eq_inter, mem_inter] at hz, rw [← hz.1.2, ← hz.2.2] } end @[to_additive] lemma fintype.prod_fiberwise [fintype α] [fintype β] [decidable_eq β] [comm_monoid γ] (f : α → β) (g : α → γ) : (∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a := begin rw [← finset.prod_equiv (equiv.sigma_preimage_equiv f) _, ← univ_sigma_univ, prod_sigma], refl end section open finset variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M] @[to_additive] lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : (∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) := begin classical, let s : finset (α₁ ⊕ α₂) := univ.image sum.inr, rw [← prod_sdiff (subset_univ s), ← @prod_image (α₁ ⊕ α₂) _ _ _ _ _ _ sum.inl, ← @prod_image (α₁ ⊕ α₂) _ _ _ _ _ _ sum.inr], { congr, rw finset.ext, rintro (a|a); { simp only [mem_image, exists_eq, mem_sdiff, mem_univ, exists_false, exists_prop_of_true, not_false_iff, and_self, not_true, and_false], } }, all_goals { intros, solve_by_elim [sum.inl.inj, sum.inr.inj], } end end namespace list lemma prod_take_of_fn [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).prod = (finset.univ.filter (λ (j : fin n), j.val < i)).prod f := begin have A : ∀ (j : fin n), ¬ (j.val < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw prod_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)}, by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.prod_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), (j.val < i.succ) = (j.val < i), { assume j, have : j.val < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end -- `to_additive` does not work on `prod_take_of_fn` because of `0 : ℕ` in the proof. Copy-paste the -- proof instead... lemma sum_take_of_fn [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).sum = (finset.univ.filter (λ (j : fin n), j.val < i)).sum f := begin have A : ∀ (j : fin n), ¬ (j.val < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw sum_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ singleton (⟨i, h⟩ : fin n), by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.sum_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), (j.val < i.succ) = (j.val < i), { assume j, have : j.val < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end attribute [to_additive] prod_take_of_fn @[to_additive] lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} : (of_fn f).prod = finset.univ.prod f := begin convert prod_take_of_fn f n, { rw [take_all_of_le (le_of_eq (length_of_fn f))] }, { have : ∀ (j : fin n), j.val < n := λ j, j.2, simp [this] } end lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] : ∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) •ℤ L.nth_le i i.2 | [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∑ i : fin 1, (-1 : ℤ) ^ (i : ℕ) •ℤ [g].nth_le i i.2, rw [fin.sum_univ_succ], simp, end | (g :: h :: L) := calc g - h + L.alternating_sum = g - h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) •ℤ L.nth_le i i.2 : congr_arg _ (alternating_sum_eq_finset_sum _) ... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) •ℤ list.nth_le (g :: h :: L) i _ : begin rw [fin.sum_univ_succ, fin.sum_univ_succ, sub_eq_add_neg, add_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end @[to_additive] lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] : ∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ)) | [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ), rw [fin.prod_univ_succ], simp, end | (g :: h :: L) := calc g * h⁻¹ * L.alternating_prod = g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) : congr_arg _ (alternating_prod_eq_finset_prod _) ... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) : begin rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end end list
6f979aceaeb635adccb0872bbede68ca57e06741
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/monotonicity/basic_auto.lean
5cd2bb8edda8030ce30290d34b4a785f6cfc58cf
[]
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
651
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.ordered_ring import Mathlib.order.bounded_lattice import Mathlib.PostPort universes l u_1 namespace Mathlib namespace tactic.interactive structure mono_cfg where unify : Bool inductive mono_selection where | left : mono_selection | right : mono_selection | both : mono_selection def last_two {α : Type u_1} (l : List α) : Option (α × α) := sorry def mono_key := with_bot name × with_bot name end Mathlib
2ed2326336525fb888521b87596424ebdabe9176
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/valuation/integral.lean
d8244b4c9b1dee528e93b0bce470f7364b1137df
[ "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
2,097
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.integrally_closed import ring_theory.valuation.integers /-! # Integral elements over the ring of integers of a valution The ring of integers is integrally closed inside the original ring. -/ universes u v w open_locale big_operators namespace valuation namespace integers section comm_ring variables {R : Type u} {Γ₀ : Type v} [comm_ring R] [linear_ordered_comm_group_with_zero Γ₀] variables {v : valuation R Γ₀} {O : Type w} [comm_ring O] [algebra O R] (hv : integers v O) include hv open polynomial lemma mem_of_integral {x : R} (hx : is_integral O x) : x ∈ v.integer := let ⟨p, hpm, hpx⟩ := hx in le_of_not_lt $ λ hvx, begin rw [hpm.as_sum, eval₂_add, eval₂_pow, eval₂_X, eval₂_finset_sum, add_eq_zero_iff_eq_neg] at hpx, replace hpx := congr_arg v hpx, refine ne_of_gt _ hpx, rw [v.map_neg, v.map_pow], refine v.map_sum_lt' (zero_lt_one₀.trans_le (one_le_pow_of_one_le' hvx.le _)) (λ i hi, _), rw [eval₂_mul, eval₂_pow, eval₂_C, eval₂_X, v.map_mul, v.map_pow, ← one_mul (v x ^ p.nat_degree)], cases (hv.2 $ p.coeff i).lt_or_eq with hvpi hvpi, { exact mul_lt_mul₀ hvpi (pow_lt_pow₀ hvx $ finset.mem_range.1 hi) }, { erw hvpi, rw [one_mul, one_mul], exact pow_lt_pow₀ hvx (finset.mem_range.1 hi) } end protected lemma integral_closure : integral_closure O R = ⊥ := bot_unique $ λ r hr, let ⟨x, hx⟩ := hv.3 (hv.mem_of_integral hr) in algebra.mem_bot.2 ⟨x, hx⟩ end comm_ring section fraction_field variables {K : Type u} {Γ₀ : Type v} [field K] [linear_ordered_comm_group_with_zero Γ₀] variables {v : valuation K Γ₀} {O : Type w} [comm_ring O] [integral_domain O] variables [algebra O K] [is_fraction_ring O K] variables (hv : integers v O) lemma integrally_closed : is_integrally_closed O := (is_integrally_closed.integral_closure_eq_bot_iff K).mp (valuation.integers.integral_closure hv) end fraction_field end integers end valuation
916109b444aeb649d194ae54b85befef0cce9a37
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/types.lean
ad97ce8539f579bc321386921954147f33c672eb
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
11,259
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl -/ import category_theory.epi_mono import category_theory.functor.fully_faithful import logic.equiv.basic /-! # The category `Type`. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this section we set up the theory so that Lean's types and functions between them can be viewed as a `large_category` in our framework. Lean can not transparently view a function as a morphism in this category, and needs a hint in order to be able to type check. We provide the abbreviation `as_hom f` to guide type checking, as well as a corresponding notation `↾ f`. (Entered as `\upr `.) The notation is enabled using `open_locale category_theory.Type`. We provide various simplification lemmas for functors and natural transformations valued in `Type`. We define `ulift_functor`, from `Type u` to `Type (max u v)`, and show that it is fully faithful (but not, of course, essentially surjective). We prove some basic facts about the category `Type`: * epimorphisms are surjections and monomorphisms are injections, * `iso` is both `iso` and `equiv` to `equiv` (at least within a fixed universe), * every type level `is_lawful_functor` gives a categorical functor `Type ⥤ Type` (the corresponding fact about monads is in `src/category_theory/monad/types.lean`). -/ namespace category_theory -- morphism levels before object levels. See note [category_theory universes]. universes v v' w u u' /- The `@[to_additive]` attribute is just a hint that expressions involving this instance can still be additivized. -/ @[to_additive category_theory.types] instance types : large_category (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } lemma types_hom {α β : Type u} : (α ⟶ β) = (α → β) := rfl lemma types_id (X : Type u) : 𝟙 X = id := rfl lemma types_comp {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl @[simp] lemma types_id_apply (X : Type u) (x : X) : ((𝟙 X) : X → X) x = x := rfl @[simp] lemma types_comp_apply {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := rfl @[simp] lemma hom_inv_id_apply {X Y : Type u} (f : X ≅ Y) (x : X) : f.inv (f.hom x) = x := congr_fun f.hom_inv_id x @[simp] lemma inv_hom_id_apply {X Y : Type u} (f : X ≅ Y) (y : Y) : f.hom (f.inv y) = y := congr_fun f.inv_hom_id y /-- `as_hom f` helps Lean type check a function as a morphism in the category `Type`. -/ -- Unfortunately without this wrapper we can't use `category_theory` idioms, such as `is_iso f`. abbreviation as_hom {α β : Type u} (f : α → β) : α ⟶ β := f -- If you don't mind some notation you can use fewer keystrokes: localized "notation (name := category_theory.as_hom) `↾` f : 200 := category_theory.as_hom f" in category_theory.Type -- type as \upr in VScode section -- We verify the expected type checking behaviour of `as_hom`. variables (α β γ : Type u) (f : α → β) (g : β → γ) example : α → γ := ↾f ≫ ↾g example [is_iso ↾f] : mono ↾f := by apply_instance example [is_iso ↾f] : ↾f ≫ inv ↾f = 𝟙 α := by simp end namespace functor variables {J : Type u} [category.{v} J] /-- The sections of a functor `J ⥤ Type` are the choices of a point `u j : F.obj j` for each `j`, such that `F.map f (u j) = u j` for every morphism `f : j ⟶ j'`. We later use these to define limits in `Type` and in many concrete categories. -/ def sections (F : J ⥤ Type w) : set (Π j, F.obj j) := { u | ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'} end functor namespace functor_to_types variables {C : Type u} [category.{v} C] (F G H : C ⥤ Type w) {X Y Z : C} variables (σ : F ⟶ G) (τ : G ⟶ H) @[simp] lemma map_comp_apply (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp [types_comp] @[simp] lemma map_id_apply (a : F.obj X) : (F.map (𝟙 X)) a = a := by simp [types_id] lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) := congr_fun (σ.naturality f) x @[simp] lemma comp (x : F.obj X) : (σ ≫ τ).app X x = τ.app X (σ.app X x) := rfl variables {D : Type u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟶ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl @[simp] lemma map_inv_map_hom_apply (f : X ≅ Y) (x : F.obj X) : F.map f.inv (F.map f.hom x) = x := congr_fun (F.map_iso f).hom_inv_id x @[simp] lemma map_hom_map_inv_apply (f : X ≅ Y) (y : F.obj Y) : F.map f.hom (F.map f.inv y) = y := congr_fun (F.map_iso f).inv_hom_id y @[simp] lemma hom_inv_id_app_apply (α : F ≅ G) (X) (x) : α.inv.app X (α.hom.app X x) = x := congr_fun (α.hom_inv_id_app X) x @[simp] lemma inv_hom_id_app_apply (α : F ≅ G) (X) (x) : α.hom.app X (α.inv.app X x) = x := congr_fun (α.inv_hom_id_app X) x end functor_to_types /-- The isomorphism between a `Type` which has been `ulift`ed to the same universe, and the original type. -/ def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy /-- The functor embedding `Type u` into `Type (max u v)`. Write this as `ulift_functor.{5 2}` to get `Type 2 ⥤ Type 5`. -/ def ulift_functor : Type u ⥤ Type (max u v) := { obj := λ X, ulift.{v} X, map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } @[simp] lemma ulift_functor_map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) : ulift_functor.map f x = ulift.up (f x.down) := rfl instance ulift_functor_full : full.{u} ulift_functor := { preimage := λ X Y f x, (f (ulift.up x)).down } instance ulift_functor_faithful : faithful ulift_functor := { map_injective' := λ X Y f g p, funext $ λ x, congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) } /-- The functor embedding `Type u` into `Type u` via `ulift` is isomorphic to the identity functor. -/ def ulift_functor_trivial : ulift_functor.{u u} ≅ 𝟭 _ := nat_iso.of_components ulift_trivial (by tidy) /-- Any term `x` of a type `X` corresponds to a morphism `punit ⟶ X`. -/ -- TODO We should connect this to a general story about concrete categories -- whose forgetful functor is representable. def hom_of_element {X : Type u} (x : X) : punit ⟶ X := λ _, x lemma hom_of_element_eq_iff {X : Type u} (x y : X) : hom_of_element x = hom_of_element y ↔ x = y := ⟨λ H, congr_fun H punit.star, by cc⟩ /-- A morphism in `Type` is a monomorphism if and only if it is injective. See <https://stacks.math.columbia.edu/tag/003C>. -/ lemma mono_iff_injective {X Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intros H x x' h, resetI, rw ←hom_of_element_eq_iff at ⊢ h, exact (cancel_mono f).mp h }, { exact λ H, ⟨λ Z, H.comp_left⟩ } end lemma injective_of_mono {X Y : Type u} (f : X ⟶ Y) [hf : mono f] : function.injective f := (mono_iff_injective f).1 hf /-- A morphism in `Type` is an epimorphism if and only if it is surjective. See <https://stacks.math.columbia.edu/tag/003C>. -/ lemma epi_iff_surjective {X Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { rintros ⟨H⟩, refine function.surjective_of_right_cancellable_Prop (λ g₁ g₂ hg, _), rw [← equiv.ulift.symm.injective.comp_left.eq_iff], apply H, change ulift.up ∘ (g₁ ∘ f) = ulift.up ∘ (g₂ ∘ f), rw hg }, { exact λ H, ⟨λ Z, H.injective_comp_right⟩ } end lemma surjective_of_epi {X Y : Type u} (f : X ⟶ Y) [hf : epi f] : function.surjective f := (epi_iff_surjective f).1 hf section /-- `of_type_functor m` converts from Lean's `Type`-based `category` to `category_theory`. This allows us to use these functors in category theory. -/ def of_type_functor (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] : Type u ⥤ Type v := { obj := m, map := λα β, _root_.functor.map, map_id' := assume α, _root_.functor.map_id, map_comp' := assume α β γ f g, funext $ assume a, is_lawful_functor.comp_map f g _ } variables (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] @[simp] lemma of_type_functor_obj : (of_type_functor m).obj = m := rfl @[simp] lemma of_type_functor_map {α β} (f : α → β) : (of_type_functor m).map f = (_root_.functor.map f : m α → m β) := rfl end end category_theory -- Isomorphisms in Type and equivalences. namespace equiv universe u variables {X Y : Type u} /-- Any equivalence between types in the same universe gives a categorical isomorphism between those types. -/ def to_iso (e : X ≃ Y) : X ≅ Y := { hom := e.to_fun, inv := e.inv_fun, hom_inv_id' := funext e.left_inv, inv_hom_id' := funext e.right_inv } @[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl @[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl end equiv universe u namespace category_theory.iso open category_theory variables {X Y : Type u} /-- Any isomorphism between types gives an equivalence. -/ def to_equiv (i : X ≅ Y) : X ≃ Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, congr_fun i.hom_inv_id x, right_inv := λ y, congr_fun i.inv_hom_id y } @[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl @[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl @[simp] lemma to_equiv_id (X : Type u) : (iso.refl X).to_equiv = equiv.refl X := rfl @[simp] lemma to_equiv_comp {X Y Z : Type u} (f : X ≅ Y) (g : Y ≅ Z) : (f ≪≫ g).to_equiv = f.to_equiv.trans (g.to_equiv) := rfl end category_theory.iso namespace category_theory /-- A morphism in `Type u` is an isomorphism if and only if it is bijective. -/ lemma is_iso_iff_bijective {X Y : Type u} (f : X ⟶ Y) : is_iso f ↔ function.bijective f := iff.intro (λ i, (by exactI as_iso f : X ≅ Y).to_equiv.bijective) (λ b, is_iso.of_iso (equiv.of_bijective f b).to_iso) instance : split_epi_category (Type u) := { is_split_epi_of_epi := λ X Y f hf, is_split_epi.mk' { section_ := function.surj_inv $ (epi_iff_surjective f).1 hf, id' := funext $ function.right_inverse_surj_inv $ (epi_iff_surjective f).1 hf } } end category_theory -- We prove `equiv_iso_iso` and then use that to sneakily construct `equiv_equiv_iso`. -- (In this order the proofs are handled by `obviously`.) /-- Equivalences (between types in the same universe) are the same as (isomorphic to) isomorphisms of types. -/ @[simps] def equiv_iso_iso {X Y : Type u} : (X ≃ Y) ≅ (X ≅ Y) := { hom := λ e, e.to_iso, inv := λ i, i.to_equiv, } /-- Equivalences (between types in the same universe) are the same as (equivalent to) isomorphisms of types. -/ def equiv_equiv_iso {X Y : Type u} : (X ≃ Y) ≃ (X ≅ Y) := (equiv_iso_iso).to_equiv @[simp] lemma equiv_equiv_iso_hom {X Y : Type u} (e : X ≃ Y) : equiv_equiv_iso e = e.to_iso := rfl @[simp] lemma equiv_equiv_iso_inv {X Y : Type u} (e : X ≅ Y) : equiv_equiv_iso.symm e = e.to_equiv := rfl
6420748266fb9de8dc0e13fe9b9b4a122df48951
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/12_Sets/quiz.lean
8bc927109da628c93e3bff7d68396f63d09326ad
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
360
lean
#reduce { 2, 4 } ⊆ { n : ℕ | ∃ m, n = 2 * m } example : { 2, 4 } ⊆ { n : ℕ | ∃ m, n = 2 * m } := begin change ∀ ⦃a : ℕ⦄, a = 4 ∨ a = 2 ∨ false → (∃ (m : ℕ), a = nat.mul 2 m), intro, assume h, cases h with four rest, apply exists.intro 2, assumption, cases rest with two f, apply exists.intro 1, assumption, contradiction, end
6a4383a00a32a1584f649d5d9dd21d728b03e88e
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/measure_theory/probability_mass_function.lean
627b563a5076e4471cb1fbe3cee61581c70e3a8c
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,349
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.instances.ennreal /-! # Probability mass functions This file is about probability mass functions or discrete probability measures: a function `α → ℝ≥0` such that the values have (infinite) sum `1`. This file features the monadic structure of `pmf` and the Bernoulli distribution ## Implementation Notes This file is not yet connected to the `measure_theory` library in any way. At some point we need to define a `measure` from a `pmf` and prove the appropriate lemmas about that. ## Tags probability mass function, discrete probability measure, bernoulli distribution -/ noncomputable theory variables {α : Type*} {β : Type*} {γ : Type*} open_locale classical big_operators nnreal ennreal /-- A probability mass function, or discrete probability measures is a function `α → ℝ≥0` such that the values have (infinite) sum `1`. -/ def {u} pmf (α : Type u) : Type u := { f : α → ℝ≥0 // has_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) (λ p, α → ℝ≥0) := ⟨λ p a, p.1 a⟩ @[ext] protected lemma ext : ∀ {p q : pmf α}, (∀ a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2 lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable @[simp] lemma tsum_coe (p : pmf α) : ∑' a, p a = 1 := p.has_sum_coe_one.tsum_eq /-- The support of a `pmf` is the set where it is nonzero. -/ def support (p : pmf α) : set α := {a | p.1 a ≠ 0} @[simp] lemma mem_support_iff (p : pmf α) (a : α) : a ∈ p.support ↔ p a ≠ 0 := iff.rfl lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := has_sum_le (by { intro b, split_ifs; simp only [h, zero_le'] }) (has_sum_ite_eq a (p a)) (has_sum_coe_one p) section pure /-- The pure `pmf` is the `pmf` where all the mass lies in one point. The value of `pure a` is `1` at `a` and `0` elsewhere. -/ def pure (a : α) : pmf α := ⟨λ a', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩ @[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl lemma mem_support_pure_iff (a a' : α) : a' ∈ (pure a).support ↔ a' = a := by simp instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩ end pure section bind protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λ a : α, p a * f a b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end /-- The monadic bind operation for `pmf`. -/ def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λ b, ∑'a, p a * f a b, begin apply ennreal.has_sum_coe.1, simp only [ennreal.coe_tsum (bind.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm, (ennreal.coe_tsum p.summable_coe).symm] end⟩ @[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = ∑'a, p a * f a b := rfl lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) : (p.bind f b : ℝ≥0∞) = ∑'a, p a * f a b := eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀ b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure (p : pmf α) : p.bind pure = p := have ∀ a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) : (p.bind f).bind g = p.bind (λ a, (f a).bind g) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λ a, q.bind (f a)) = q.bind (λ b, p.bind (λ a, f a b)) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end end bind section bind_on_support protected lemma bind_on_support.summable (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : summable (λ a : α, p a * if h : p a = 0 then 0 else f a h b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, split_ifs, { refine (mul_zero (p a)).symm ▸ le_of_eq h.symm }, { suffices : p a * f a h b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a h).coe_le_one _) (p a).2 } end /-- Generalized version of `bind` allowing `f` to only be defined on the support of `p`. `p.bind f` is equivalent to `p.bind_on_support (λ a _, f a)`, see `bind_on_support_eq_bind` -/ def bind_on_support (p : pmf α) (f : ∀ a ∈ p.support, pmf β) : pmf β := ⟨λ b, ∑' a, p a * if h : p a = 0 then 0 else f a h b, ennreal.has_sum_coe.1 begin simp only [ennreal.coe_tsum (bind_on_support.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp only [ennreal.coe_mul, ennreal.coe_one, ennreal.tsum_mul_left], have : ∑' (a : α), (p a : ennreal) = 1 := by simp only [←ennreal.coe_tsum p.summable_coe, ennreal.coe_one, tsum_coe], refine trans (tsum_congr (λ a, _)) this, split_ifs with h, { simp [h] }, { simp [← ennreal.coe_tsum (f a h).summable_coe, (f a h).tsum_coe] } end⟩ @[simp] lemma bind_on_support_apply (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : p.bind_on_support f b = ∑' a, p a * if h : p a = 0 then 0 else f a h b := rfl /-- `bind_on_support` reduces to `bind` if `f` doesn't depend on the additional hypothesis -/ @[simp] lemma bind_on_support_eq_bind (p : pmf α) (f : α → pmf β) : p.bind_on_support (λ a _, f a) = p.bind f := begin ext b, simp only [p.bind_on_support_apply (λ a _, f a), p.bind_apply f, dite_eq_ite, nnreal.coe_eq, mul_ite, mul_zero], refine congr_arg _ (funext (λ a, _)), split_ifs with h; simp [h], end lemma coe_bind_on_support_apply (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : (p.bind_on_support f b : ℝ≥0∞) = ∑' a, p a * if h : p a = 0 then 0 else f a h b := by simp only [bind_on_support_apply, ennreal.coe_tsum (bind_on_support.summable p f b), dite_cast, ennreal.coe_mul, ennreal.coe_zero] @[simp] lemma mem_support_bind_on_support_iff (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : b ∈ (p.bind_on_support f).support ↔ ∃ a (ha : p a ≠ 0), b ∈ (f a ha).support := begin simp only [mem_support_iff, bind_on_support_apply, tsum_ne_zero_iff (bind_on_support.summable p f b), mul_ne_zero_iff], split; { rintro ⟨a, ha, haf⟩, refine ⟨a, ha, ne_of_eq_of_ne _ haf⟩, simp [ha], }, end lemma bind_on_support_eq_zero_iff (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : p.bind_on_support f b = 0 ↔ ∀ a (ha : p a ≠ 0), f a ha b = 0 := begin simp only [bind_on_support_apply, tsum_eq_zero_iff (bind_on_support.summable p f b), mul_eq_zero, or_iff_not_imp_left], exact ⟨λ h a ha, trans (dif_neg ha).symm (h a ha), λ h a ha, trans (dif_neg ha) (h a ha)⟩, end @[simp] lemma pure_bind_on_support (a : α) (f : ∀ (a' : α) (ha : a' ∈ (pure a).support), pmf β) : (pure a).bind_on_support f = f a ((mem_support_pure_iff a a).mpr rfl) := begin refine pmf.ext (λ b, _), simp only [nnreal.coe_eq, bind_on_support_apply, pure_apply], refine trans (tsum_congr (λ a', _)) (tsum_ite_eq a _), by_cases h : (a' = a); simp [h], end lemma bind_on_support_pure (p : pmf α) : p.bind_on_support (λ a _, pure a) = p := by simp only [pmf.bind_pure, pmf.bind_on_support_eq_bind] @[simp] lemma bind_on_support_bind_on_support (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (g : ∀ (b ∈ (p.bind_on_support f).support), pmf γ) : (p.bind_on_support f).bind_on_support g = p.bind_on_support (λ a ha, (f a ha).bind_on_support (λ b hb, g b ((p.mem_support_bind_on_support_iff f b).mpr ⟨a, ha, hb⟩))) := begin refine pmf.ext (λ a, _), simp only [ennreal.coe_eq_coe.symm, coe_bind_on_support_apply, ← tsum_dite_right, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], refine trans (ennreal.tsum_comm) (tsum_congr (λ a', _)), split_ifs with h, { simp only [h, ennreal.coe_zero, zero_mul, tsum_zero] }, { simp only [← ennreal.tsum_mul_left, ← mul_assoc], refine tsum_congr (λ b, _), split_ifs with h1 h2 h2, any_goals { ring1 }, { rw bind_on_support_eq_zero_iff at h1, simp only [h1 a' h, ennreal.coe_zero, zero_mul, mul_zero] }, { simp only [h2, ennreal.coe_zero, mul_zero, zero_mul] } } end lemma bind_on_support_comm (p : pmf α) (q : pmf β) (f : ∀ (a ∈ p.support) (b ∈ q.support), pmf γ) : p.bind_on_support (λ a ha, q.bind_on_support (f a ha)) = q.bind_on_support (λ b hb, p.bind_on_support (λ a ha, f a ha b hb)) := begin apply pmf.ext, rintro c, simp only [ennreal.coe_eq_coe.symm, coe_bind_on_support_apply, ← tsum_dite_right, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], refine trans (ennreal.tsum_comm) (tsum_congr (λ b, tsum_congr (λ a, _))), split_ifs with h1 h2 h2; ring, end end bind_on_support section map /-- The functorial action of a function on a `pmf`. -/ def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f) lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl lemma map_id (p : pmf α) : map id p = p := by simp [map] lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) := by simp [map] lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) := by simp [map] end map /-- The monadic sequencing operation for `pmf`. -/ def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λ m, p.bind $ λ a, pure (m a)) section of_finite /-- Given a finset `s` and a function `f : α → ℝ≥0` with sum `1` on `s`, such that `f x = 0` for `x ∉ s`, we get a `pmf` -/ def of_finset (f : α → ℝ≥0) (s : finset α) (h : ∑ x in s, f x = 1) (h' : ∀ x ∉ s, f x = 0) : pmf α := ⟨f, h ▸ has_sum_sum_of_ne_finset_zero h'⟩ @[simp] lemma of_finset_apply {f : α → ℝ≥0} {s : finset α} (h : ∑ x in s, f x = 1) (h' : ∀ x ∉ s, f x = 0) (a : α) : of_finset f s h h' a = f a := rfl lemma of_finset_apply_of_not_mem {f : α → ℝ≥0} {s : finset α} (h : ∑ x in s, f x = 1) (h' : ∀ x ∉ s, f x = 0) {a : α} (ha : a ∉ s) : of_finset f s h h' a = 0 := h' a ha /-- Given a finite type `α` and a function `f : α → ℝ≥0` with sum 1, we get a `pmf`. -/ def of_fintype [fintype α] (f : α → ℝ≥0) (h : ∑ x, f x = 1) : pmf α := of_finset f finset.univ h (λ x hx, absurd (finset.mem_univ x) hx) @[simp] lemma of_fintype_apply [fintype α] {f : α → ℝ≥0} (h : ∑ x, f x = 1) (a : α) : of_fintype f h a = f a := rfl /-- Given a non-empty multiset `s` we construct the `pmf` which sends `a` to the fraction of elements in `s` that are `a`. -/ def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α := ⟨λ a, s.count a / s.card, have ∑ a in s.to_finset, (s.count a : ℝ) / s.card = 1, by simp [div_eq_inv_mul, finset.mul_sum.symm, (nat.cast_sum _ _).symm, hs], have ∑ a in s.to_finset, (s.count a : ℝ≥0) / s.card = 1, by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.coe_sum]; simp, begin rw ← this, apply has_sum_sum_of_ne_finset_zero, simp {contextual := tt}, end⟩ @[simp] lemma of_multiset_apply {s : multiset α} (hs : s ≠ 0) (a : α) : of_multiset s hs a = s.count a / s.card := rfl lemma of_multiset_apply_of_not_mem {s : multiset α} (hs : s ≠ 0) {a : α} (ha : a ∉ s) : of_multiset s hs a = 0 := div_eq_zero_iff.2 (or.inl $ nat.cast_eq_zero.2 $ multiset.count_eq_zero_of_not_mem ha) end of_finite section uniform /-- Uniform distribution taking the same non-zero probability on the nonempty finset `s` -/ def uniform_of_finset (s : finset α) (hs : s.nonempty) : pmf α := of_finset (λ a, if a ∈ s then (s.card : ℝ≥0)⁻¹ else 0) s (Exists.rec_on hs (λ x hx, calc ∑ (a : α) in s, ite (a ∈ s) (s.card : ℝ≥0)⁻¹ 0 = ∑ (a : α) in s, (s.card : ℝ≥0)⁻¹ : finset.sum_congr rfl (λ x hx, by simp [hx]) ... = s.card • (s.card : ℝ≥0)⁻¹ : finset.sum_const _ ... = (s.card : ℝ≥0) * (s.card : ℝ≥0)⁻¹ : by rw nsmul_eq_mul ... = 1 : div_self (nat.cast_ne_zero.2 $ finset.card_ne_zero_of_mem hx) )) (λ x hx, by simp only [hx, if_false]) @[simp] lemma uniform_of_finset_apply {s : finset α} (hs : s.nonempty) (a : α) : uniform_of_finset s hs a = if a ∈ s then (s.card : ℝ≥0)⁻¹ else 0 := rfl lemma uniform_of_finset_apply_of_mem {s : finset α} (hs : s.nonempty) {a : α} (ha : a ∈ s) : uniform_of_finset s hs a = (s.card)⁻¹ := by simp [ha] lemma uniform_of_finset_apply_of_not_mem {s : finset α} (hs : s.nonempty) {a : α} (ha : a ∉ s) : uniform_of_finset s hs a = 0 := by simp [ha] /-- The uniform pmf taking the same uniform value on all of the fintype `α` -/ def uniform_of_fintype (α : Type*) [fintype α] [nonempty α] : pmf α := uniform_of_finset (finset.univ) (finset.univ_nonempty) @[simp] lemma uniform_of_fintype_apply [fintype α] [nonempty α] (a : α) : uniform_of_fintype α a = (fintype.card α)⁻¹ := by simpa only [uniform_of_fintype, finset.mem_univ, if_true, uniform_of_finset_apply] end uniform /-- Given a `f` with non-zero sum, we get a `pmf` by normalizing `f` by its `tsum` -/ def normalize (f : α → ℝ≥0) (hf0 : tsum f ≠ 0) : pmf α := ⟨λ a, f a * (∑' x, f x)⁻¹, (mul_inv_cancel hf0) ▸ has_sum.mul_right (∑' x, f x)⁻¹ (not_not.mp (mt tsum_eq_zero_of_not_summable hf0 : ¬¬summable f)).has_sum⟩ lemma normalize_apply {f : α → ℝ≥0} (hf0 : tsum f ≠ 0) (a : α) : (normalize f hf0) a = f a * (∑' x, f x)⁻¹ := rfl section filter /-- Create new `pmf` by filtering on a set with non-zero measure and normalizing -/ def filter (p : pmf α) (s : set α) (h : ∃ a ∈ s, p a ≠ 0) : pmf α := pmf.normalize (s.indicator p) $ nnreal.tsum_indicator_ne_zero p.2.summable h lemma filter_apply (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) {a : α} : (p.filter s h) a = (s.indicator p a) * (∑' x, (s.indicator p) x)⁻¹ := by rw [filter, normalize_apply] lemma filter_apply_eq_zero_of_not_mem (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) {a : α} (ha : a ∉ s) : (p.filter s h) a = 0 := by rw [filter_apply, set.indicator_apply_eq_zero.mpr (λ ha', absurd ha' ha), zero_mul] lemma filter_apply_eq_zero_iff (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) (a : α) : (p.filter s h) a = 0 ↔ a ∉ (p.support ∩ s) := begin rw [set.mem_inter_iff, p.mem_support_iff, not_and_distrib, not_not], split; intro ha, { rw [filter_apply, mul_eq_zero] at ha, refine ha.by_cases (λ ha, (em (a ∈ s)).by_cases (λ h, or.inl ((set.indicator_apply_eq_zero.mp ha) h)) or.inr) (λ ha, absurd (inv_eq_zero.1 ha) (nnreal.tsum_indicator_ne_zero p.2.summable h)) }, { rw [filter_apply, set.indicator_apply_eq_zero.2 (λ h, ha.by_cases id (absurd h)), zero_mul] } end lemma filter_apply_ne_zero_iff (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) (a : α) : (p.filter s h) a ≠ 0 ↔ a ∈ (p.support ∩ s) := by rw [← not_iff, filter_apply_eq_zero_iff, not_iff, not_not] end filter section bernoulli /-- A `pmf` which assigns probability `p` to `tt` and `1 - p` to `ff`. -/ def bernoulli (p : ℝ≥0) (h : p ≤ 1) : pmf bool := of_fintype (λ b, cond b p (1 - p)) (nnreal.eq $ by simp [h]) @[simp] lemma bernuolli_apply {p : ℝ≥0} (h : p ≤ 1) (b : bool) : bernoulli p h b = cond b p (1 - p) := rfl end bernoulli end pmf
ae9d59217dbf26c47971832b5dd38f15c34f74e8
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/pi_system.lean
0af61def42504b9fbe5111d9d985a031ca16e896
[ "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
28,573
lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Martin Zinkevich, Rémy Degenne -/ import logic.encodable.lattice import measure_theory.measurable_space_def /-! # Induction principles for measurable sets, related to π-systems and λ-systems. ## Main statements * The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. * The proof of this theorem relies on the notion of `is_pi_system`, i.e., a collection of sets which is closed under binary non-empty intersections. Note that this is a small variation around the usual notion in the literature, which often requires that a π-system is non-empty, and closed also under disjoint intersections. This variation turns out to be convenient for the formalization. * The proof of Dynkin's π-λ theorem also requires the notion of `dynkin_system`, i.e., a collection of sets which contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. * `generate_pi_system g` gives the minimal π-system containing `g`. This can be considered a Galois insertion into both measurable spaces and sets. * `generate_from_generate_pi_system_eq` proves that if you start from a collection of sets `g`, take the generated π-system, and then the generated σ-algebra, you get the same result as the σ-algebra generated from `g`. This is useful because there are connections between independent sets that are π-systems and the generated independent spaces. * `mem_generate_pi_system_Union_elim` and `mem_generate_pi_system_Union_elim'` show that any element of the π-system generated from the union of a set of π-systems can be represented as the intersection of a finite number of elements from these sets. * `pi_Union_Inter` defines a new π-system from a family of π-systems `π : ι → set (set α)` and a set of finsets `S : set (finset α)`. `pi_Union_Inter π S` is the set of sets that can be written as `⋂ x ∈ t, f x` for some `t ∈ S` and sets `f x ∈ π x`. If `S` is union-closed, then it is a π-system. The π-systems used to prove Kolmogorov's 0-1 law will be defined using this mechanism (TODO). ## Implementation details * `is_pi_system` is a predicate, not a type. Thus, we don't explicitly define the galois insertion, nor do we define a complete lattice. In theory, we could define a complete lattice and galois insertion on the subtype corresponding to `is_pi_system`. -/ open measurable_space set open_locale classical measure_theory /-- A π-system is a collection of subsets of `α` that is closed under binary intersection of non-disjoint sets. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space lemma is_pi_system_measurable_set {α:Type*} [measurable_space α] : is_pi_system {s : set α | measurable_set s} := λ s hs t ht _, hs.inter ht end measurable_space lemma is_pi_system.singleton {α} (S : set α) : is_pi_system ({S} : set (set α)) := begin intros s h_s t h_t h_ne, rw [set.mem_singleton_iff.1 h_s, set.mem_singleton_iff.1 h_t, set.inter_self, set.mem_singleton_iff], end lemma is_pi_system.insert_empty {α} {S : set (set α)} (h_pi : is_pi_system S) : is_pi_system (insert ∅ S) := begin intros s hs t ht hst, cases hs, { simp [hs], }, { cases ht, { simp [ht], }, { exact set.mem_insert_of_mem _ (h_pi s hs t ht hst), }, }, end lemma is_pi_system.insert_univ {α} {S : set (set α)} (h_pi : is_pi_system S) : is_pi_system (insert set.univ S) := begin intros s hs t ht hst, cases hs, { cases ht; simp [hs, ht], }, { cases ht, { simp [hs, ht], }, { exact set.mem_insert_of_mem _ (h_pi s hs t ht hst), }, }, end lemma is_pi_system.comap {α β} {S : set (set β)} (h_pi : is_pi_system S) (f : α → β) : is_pi_system {s : set α | ∃ t ∈ S, f ⁻¹' t = s} := begin rintros _ ⟨s, hs_mem, rfl⟩ _ ⟨t, ht_mem, rfl⟩ hst, rw ← set.preimage_inter at hst ⊢, refine ⟨s ∩ t, h_pi s hs_mem t ht_mem _, rfl⟩, by_contra, rw set.not_nonempty_iff_eq_empty at h, rw h at hst, simpa using hst, end section order variables {α : Type*} {ι ι' : Sort*} [linear_order α] lemma is_pi_system_image_Iio (s : set α) : is_pi_system (Iio '' s) := begin rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ -, exact ⟨a ⊓ b, inf_ind a b ha hb, Iio_inter_Iio.symm⟩ end lemma is_pi_system_Iio : is_pi_system (range Iio : set (set α)) := @image_univ α _ Iio ▸ is_pi_system_image_Iio univ lemma is_pi_system_image_Ioi (s : set α) : is_pi_system (Ioi '' s) := @is_pi_system_image_Iio αᵒᵈ _ s lemma is_pi_system_Ioi : is_pi_system (range Ioi : set (set α)) := @image_univ α _ Ioi ▸ is_pi_system_image_Ioi univ lemma is_pi_system_Ixx_mem {Ixx : α → α → set α} {p : α → α → Prop} (Hne : ∀ {a b}, (Ixx a b).nonempty → p a b) (Hi : ∀ {a₁ b₁ a₂ b₂}, Ixx a₁ b₁ ∩ Ixx a₂ b₂ = Ixx (max a₁ a₂) (min b₁ b₂)) (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (hlu : p l u), Ixx l u = S} := begin rintro _ ⟨l₁, hls₁, u₁, hut₁, hlu₁, rfl⟩ _ ⟨l₂, hls₂, u₂, hut₂, hlu₂, rfl⟩, simp only [Hi, ← sup_eq_max, ← inf_eq_min], exact λ H, ⟨l₁ ⊔ l₂, sup_ind l₁ l₂ hls₁ hls₂, u₁ ⊓ u₂, inf_ind u₁ u₂ hut₁ hut₂, Hne H, rfl⟩ end lemma is_pi_system_Ixx {Ixx : α → α → set α} {p : α → α → Prop} (Hne : ∀ {a b}, (Ixx a b).nonempty → p a b) (Hi : ∀ {a₁ b₁ a₂ b₂}, Ixx a₁ b₁ ∩ Ixx a₂ b₂ = Ixx (max a₁ a₂) (min b₁ b₂)) (f : ι → α) (g : ι' → α) : @is_pi_system α ({S | ∃ i j (h : p (f i) (g j)), Ixx (f i) (g j) = S}) := by simpa only [exists_range_iff] using is_pi_system_Ixx_mem @Hne @Hi (range f) (range g) lemma is_pi_system_Ioo_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ioo l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans hxb) (λ _ _ _ _, Ioo_inter_Ioo) s t lemma is_pi_system_Ioo (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ l u (h : f l < g u), Ioo (f l) (g u) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans hxb) (λ _ _ _ _, Ioo_inter_Ioo) f g lemma is_pi_system_Ioc_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ioc l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans_le hxb) (λ _ _ _ _, Ioc_inter_Ioc) s t lemma is_pi_system_Ioc (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i < g j), Ioc (f i) (g j) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans_le hxb) (λ _ _ _ _, Ioc_inter_Ioc) f g lemma is_pi_system_Ico_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ico l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans_lt hxb) (λ _ _ _ _, Ico_inter_Ico) s t lemma is_pi_system_Ico (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i < g j), Ico (f i) (g j) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans_lt hxb) (λ _ _ _ _, Ico_inter_Ico) f g lemma is_pi_system_Icc_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l ≤ u), Icc l u = S} := is_pi_system_Ixx_mem (λ a b, nonempty_Icc.1) (λ _ _ _ _, Icc_inter_Icc) s t lemma is_pi_system_Icc (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i ≤ g j), Icc (f i) (g j) = S} := is_pi_system_Ixx (λ a b, nonempty_Icc.1) (λ _ _ _ _, Icc_inter_Icc) f g end order /-- Given a collection `S` of subsets of `α`, then `generate_pi_system S` is the smallest π-system containing `S`. -/ inductive generate_pi_system {α} (S : set (set α)) : set (set α) | base {s : set α} (h_s : s ∈ S) : generate_pi_system s | inter {s t : set α} (h_s : generate_pi_system s) (h_t : generate_pi_system t) (h_nonempty : (s ∩ t).nonempty) : generate_pi_system (s ∩ t) lemma is_pi_system_generate_pi_system {α} (S : set (set α)) : is_pi_system (generate_pi_system S) := λ s h_s t h_t h_nonempty, generate_pi_system.inter h_s h_t h_nonempty lemma subset_generate_pi_system_self {α} (S : set (set α)) : S ⊆ generate_pi_system S := λ s, generate_pi_system.base lemma generate_pi_system_subset_self {α} {S : set (set α)} (h_S : is_pi_system S) : generate_pi_system S ⊆ S := begin intros x h, induction h with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { exact h_s, }, { exact h_S _ h_s _ h_u h_nonempty, }, end lemma generate_pi_system_eq {α} {S : set (set α)} (h_pi : is_pi_system S) : generate_pi_system S = S := set.subset.antisymm (generate_pi_system_subset_self h_pi) (subset_generate_pi_system_self S) lemma generate_pi_system_mono {α} {S T : set (set α)} (hST : S ⊆ T) : generate_pi_system S ⊆ generate_pi_system T := begin intros t ht, induction ht with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { exact generate_pi_system.base (set.mem_of_subset_of_mem hST h_s),}, { exact is_pi_system_generate_pi_system T _ h_s _ h_u h_nonempty, }, end lemma generate_pi_system_measurable_set {α} [M : measurable_space α] {S : set (set α)} (h_meas_S : ∀ s ∈ S, measurable_set s) (t : set α) (h_in_pi : t ∈ generate_pi_system S) : measurable_set t := begin induction h_in_pi with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { apply h_meas_S _ h_s, }, { apply measurable_set.inter h_s h_u, }, end lemma generate_from_measurable_set_of_generate_pi_system {α} {g : set (set α)} (t : set α) (ht : t ∈ generate_pi_system g) : measurable_set[generate_from g] t := @generate_pi_system_measurable_set α (generate_from g) g (λ s h_s_in_g, measurable_set_generate_from h_s_in_g) t ht lemma generate_from_generate_pi_system_eq {α} {g : set (set α)} : generate_from (generate_pi_system g) = generate_from g := begin apply le_antisymm; apply generate_from_le, { exact λ t h_t, generate_from_measurable_set_of_generate_pi_system t h_t, }, { exact λ t h_t, measurable_set_generate_from (generate_pi_system.base h_t), }, end /- Every element of the π-system generated by the union of a family of π-systems is a finite intersection of elements from the π-systems. For an indexed union version, see `mem_generate_pi_system_Union_elim'`. -/ lemma mem_generate_pi_system_Union_elim {α β} {g : β → set (set α)} (h_pi : ∀ b, is_pi_system (g b)) (t : set α) (h_t : t ∈ generate_pi_system (⋃ b, g b)) : ∃ (T : finset β) (f : β → set α), (t = ⋂ b ∈ T, f b) ∧ (∀ b ∈ T, f b ∈ g b) := begin induction h_t with s h_s s t' h_gen_s h_gen_t' h_nonempty h_s h_t', { rcases h_s with ⟨t', ⟨⟨b, rfl⟩, h_s_in_t'⟩⟩, refine ⟨{b}, (λ _, s), _⟩, simpa using h_s_in_t', }, { rcases h_t' with ⟨T_t', ⟨f_t', ⟨rfl, h_t'⟩⟩⟩, rcases h_s with ⟨T_s, ⟨f_s, ⟨rfl, h_s⟩ ⟩ ⟩, use [(T_s ∪ T_t'), (λ (b:β), if (b ∈ T_s) then (if (b ∈ T_t') then (f_s b ∩ (f_t' b)) else (f_s b)) else (if (b ∈ T_t') then (f_t' b) else (∅ : set α)))], split, { ext a, simp_rw [set.mem_inter_iff, set.mem_Inter, finset.mem_union, or_imp_distrib], rw ← forall_and_distrib, split; intros h1 b; by_cases hbs : b ∈ T_s; by_cases hbt : b ∈ T_t'; specialize h1 b; simp only [hbs, hbt, if_true, if_false, true_implies_iff, and_self, false_implies_iff, and_true, true_and] at h1 ⊢, all_goals { exact h1, }, }, intros b h_b, split_ifs with hbs hbt hbt, { refine h_pi b (f_s b) (h_s b hbs) (f_t' b) (h_t' b hbt) (set.nonempty.mono _ h_nonempty), exact set.inter_subset_inter (set.bInter_subset_of_mem hbs) (set.bInter_subset_of_mem hbt), }, { exact h_s b hbs, }, { exact h_t' b hbt, }, { rw finset.mem_union at h_b, apply false.elim (h_b.elim hbs hbt), }, }, end /- Every element of the π-system generated by an indexed union of a family of π-systems is a finite intersection of elements from the π-systems. For a total union version, see `mem_generate_pi_system_Union_elim`. -/ lemma mem_generate_pi_system_Union_elim' {α β} {g : β → set (set α)} {s : set β} (h_pi : ∀ b ∈ s, is_pi_system (g b)) (t : set α) (h_t : t ∈ generate_pi_system (⋃ b ∈ s, g b)) : ∃ (T : finset β) (f : β → set α), (↑T ⊆ s) ∧ (t = ⋂ b ∈ T, f b) ∧ (∀ b ∈ T, f b ∈ g b) := begin have : t ∈ generate_pi_system (⋃ (b : subtype s), (g ∘ subtype.val) b), { suffices h1 : (⋃ (b : subtype s), (g ∘ subtype.val) b) = (⋃ b ∈ s, g b), by rwa h1, ext x, simp only [exists_prop, set.mem_Union, function.comp_app, subtype.exists, subtype.coe_mk], refl }, rcases @mem_generate_pi_system_Union_elim α (subtype s) (g ∘ subtype.val) (λ b, h_pi b.val b.property) t this with ⟨T, ⟨f, ⟨rfl, h_t'⟩⟩⟩, refine ⟨T.image subtype.val, function.extend subtype.val f (λ b : β, (∅ : set α)), by simp, _, _⟩, { ext a, split; { simp only [set.mem_Inter, subtype.forall, finset.set_bInter_finset_image], intros h1 b h_b h_b_in_T, have h2 := h1 b h_b h_b_in_T, revert h2, rw function.extend_apply subtype.val_injective, apply id } }, { intros b h_b, simp_rw [finset.mem_image, exists_prop, subtype.exists, exists_and_distrib_right, exists_eq_right] at h_b, cases h_b, have h_b_alt : b = (subtype.mk b h_b_w).val := rfl, rw [h_b_alt, function.extend_apply subtype.val_injective], apply h_t', apply h_b_h }, end section Union_Inter /-! ### π-system generated by finite intersections of sets of a π-system family -/ /-- From a set of finsets `S : set (finset ι)` and a family of sets of sets `π : ι → set (set α)`, define the set of sets that can be written as `⋂ x ∈ t, f x` for some `t ∈ S` and sets `f x ∈ π x`. If `S` is union-closed and `π` is a family of π-systems, then it is a π-system. The π-systems used to prove Kolmogorov's 0-1 law are of that form. -/ def pi_Union_Inter {α ι} (π : ι → set (set α)) (S : set (finset ι)) : set (set α) := {s : set α | ∃ (t : finset ι) (htS : t ∈ S) (f : ι → set α) (hf : ∀ x, x ∈ t → f x ∈ π x), s = ⋂ x ∈ t, f x} /-- If `S` is union-closed and `π` is a family of π-systems, then `pi_Union_Inter π S` is a π-system. -/ lemma is_pi_system_pi_Union_Inter {α ι} (π : ι → set (set α)) (hpi : ∀ x, is_pi_system (π x)) (S : set (finset ι)) (h_sup : sup_closed S) : is_pi_system (pi_Union_Inter π S) := begin rintros t1 ⟨p1, hp1S, f1, hf1m, ht1_eq⟩ t2 ⟨p2, hp2S, f2, hf2m, ht2_eq⟩ h_nonempty, simp_rw [pi_Union_Inter, set.mem_set_of_eq], let g := λ n, (ite (n ∈ p1) (f1 n) set.univ) ∩ (ite (n ∈ p2) (f2 n) set.univ), use [p1 ∪ p2, h_sup p1 p2 hp1S hp2S, g], have h_inter_eq : t1 ∩ t2 = ⋂ i ∈ p1 ∪ p2, g i, { rw [ht1_eq, ht2_eq], simp_rw [← set.inf_eq_inter, g], ext1 x, simp only [inf_eq_inter, mem_inter_eq, mem_Inter, finset.mem_union], refine ⟨λ h i hi_mem_union, _, λ h, ⟨λ i hi1, _, λ i hi2, _⟩⟩, { split_ifs, exacts [⟨h.1 i h_1, h.2 i h_2⟩, ⟨h.1 i h_1, set.mem_univ _⟩, ⟨set.mem_univ _, h.2 i h_2⟩, ⟨set.mem_univ _, set.mem_univ _⟩], }, { specialize h i (or.inl hi1), rw if_pos hi1 at h, exact h.1, }, { specialize h i (or.inr hi2), rw if_pos hi2 at h, exact h.2, }, }, refine ⟨λ n hn, _, h_inter_eq⟩, simp_rw g, split_ifs with hn1 hn2, { refine hpi n (f1 n) (hf1m n hn1) (f2 n) (hf2m n hn2) (set.ne_empty_iff_nonempty.mp (λ h, _)), rw h_inter_eq at h_nonempty, suffices h_empty : (⋂ i ∈ p1 ∪ p2, g i) = ∅, from (set.not_nonempty_iff_eq_empty.mpr h_empty) h_nonempty, refine le_antisymm (set.Inter_subset_of_subset n _) (set.empty_subset _), refine set.Inter_subset_of_subset hn _, simp_rw [g, if_pos hn1, if_pos hn2], exact h.subset, }, { simp [hf1m n hn1], }, { simp [hf2m n h], }, { exact absurd hn (by simp [hn1, h]), }, end lemma pi_Union_Inter_mono_left {α ι} {π π' : ι → set (set α)} (h_le : ∀ i, π i ⊆ π' i) (S : set (finset ι)) : pi_Union_Inter π S ⊆ pi_Union_Inter π' S := begin rintros s ⟨t, ht_mem, ft, hft_mem_pi, rfl⟩, exact ⟨t, ht_mem, ft, λ x hxt, h_le x (hft_mem_pi x hxt), rfl⟩, end lemma generate_from_pi_Union_Inter_le {α ι} {m : measurable_space α} (π : ι → set (set α)) (h : ∀ n, generate_from (π n) ≤ m) (S : set (finset ι)) : generate_from (pi_Union_Inter π S) ≤ m := begin refine generate_from_le _, rintros t ⟨ht_p, ht_p_mem, ft, hft_mem_pi, rfl⟩, refine finset.measurable_set_bInter _ (λ x hx_mem, (h x) _ _), exact measurable_set_generate_from (hft_mem_pi x hx_mem), end lemma subset_pi_Union_Inter {α ι} {π : ι → set (set α)} {S : set (finset ι)} (h_univ : ∀ i, set.univ ∈ π i) {i : ι} {s : finset ι} (hsS : s ∈ S) (his : i ∈ s) : π i ⊆ pi_Union_Inter π S := begin refine λ t ht_pii, ⟨s, hsS, (λ j, ite (j = i) t set.univ), ⟨λ m h_pm, _, _⟩⟩, { split_ifs, { rwa h, }, { exact h_univ m, }, }, { ext1 x, simp_rw set.mem_Inter, split; intro hx, { intros j h_p_j, split_ifs, { exact hx, }, { exact set.mem_univ _, }, }, { simpa using hx i his, }, }, end lemma mem_pi_Union_Inter_of_measurable_set {α ι} (m : ι → measurable_space α) {S : set (finset ι)} {i : ι} {t : finset ι} (htS : t ∈ S) (hit : i ∈ t) (s : set α) (hs : measurable_set[m i] s) : s ∈ pi_Union_Inter (λ n, {s | measurable_set[m n] s}) S := subset_pi_Union_Inter (λ i, measurable_set.univ) htS hit hs lemma le_generate_from_pi_Union_Inter {α ι} {π : ι → set (set α)} (S : set (finset ι)) (h_univ : ∀ n, set.univ ∈ π n) {x : ι} {t : finset ι} (htS : t ∈ S) (hxt : x ∈ t) : generate_from (π x) ≤ generate_from (pi_Union_Inter π S) := generate_from_mono (subset_pi_Union_Inter h_univ htS hxt) lemma measurable_set_supr_of_mem_pi_Union_Inter {α ι} (m : ι → measurable_space α) (S : set (finset ι)) (t : set α) (ht : t ∈ pi_Union_Inter (λ n, {s | measurable_set[m n] s}) S) : measurable_set[⨆ i (hi : ∃ s ∈ S, i ∈ s), m i] t := begin rcases ht with ⟨pt, hpt, ft, ht_m, rfl⟩, refine pt.measurable_set_bInter (λ i hi, _), suffices h_le : m i ≤ (⨆ i (hi : ∃ s ∈ S, i ∈ s), m i), from h_le (ft i) (ht_m i hi), have hi' : ∃ s ∈ S, i ∈ s, from ⟨pt, hpt, hi⟩, exact le_supr₂ i hi', end lemma generate_from_pi_Union_Inter_measurable_space {α ι} (m : ι → measurable_space α) (S : set (finset ι)) : generate_from (pi_Union_Inter (λ n, {s | measurable_set[m n] s}) S) = ⨆ i (hi : ∃ p ∈ S, i ∈ p), m i := begin refine le_antisymm _ _, { rw ← @generate_from_measurable_set α (⨆ i (hi : ∃ p ∈ S, i ∈ p), m i), exact generate_from_mono (measurable_set_supr_of_mem_pi_Union_Inter m S), }, { refine supr₂_le (λ i hi, _), rcases hi with ⟨p, hpS, hpi⟩, rw ← @generate_from_measurable_set α (m i), exact generate_from_mono (mem_pi_Union_Inter_of_measurable_set m hpS hpi), }, end end Union_Inter namespace measurable_space variable {α : Type*} /-! ## Dynkin systems and Π-λ theorem -/ /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by a collection of sets which is stable under intersection. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀ {a}, has a → has aᶜ) (has_Union_nat : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, has (f i)) → has (⋃ i, f i)) namespace dynkin_system @[ext] lemma ext : ∀ {d₁ d₂ : dynkin_system α}, (∀ s : set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty lemma has_Union {β} [countable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀ i, d.has (f i)) : d.has (⋃ i, f i) := by { casesI nonempty_encodable β, rw ← encodable.Union_decode₂, exact d.has_Union_nat (encodable.Union_decode₂_disjoint_on hd) (λ n, encodable.Union_decode₂_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : has_le (dynkin_system α) := { le := λ m₁ m₂, m₁.has ≤ m₂.has } lemma le_def {α} {a b : dynkin_system α} : a ≤ b ↔ a.has ≤ b.has := iff.rfl instance : partial_order (dynkin_system α) := { le_refl := assume a b, le_rfl, le_trans := assume a b c hab hbc, le_def.mpr (le_trans hab hbc), le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩, ..dynkin_system.has_le } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.measurable_set', has_empty := m.measurable_set_empty, has_compl := m.measurable_set_compl, has_Union_nat := assume f _ hf, m.measurable_set_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀ t ∈ s, generate_has t | empty : generate_has ∅ | compl : ∀ {a}, generate_has a → generate_has aᶜ | Union : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, generate_has (f i)) → generate_has (⋃ i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . measurable_set' := d.has, measurable_set_empty := d.has_empty, measurable_set_compl := assume s h, d.has_compl h, measurable_set_Union := λ f hf, begin rw ←Union_disjointed, exact d.has_Union (disjoint_disjointed _) (λ n, disjointed_rec (λ t i h, h_inter _ _ h $ d.has_compl $ hf i) (hf n)), end } lemma of_measurable_space_to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λ t, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀ t ∈ s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : measurable_set[generate_from C] s := generate_le (of_measurable_space (generate_from C)) (λ t, measurable_set_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ $ hs _ hs₂ _ hs₁ h), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- **Dynkin's π-λ theorem**: Given a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a π-system (often requiring additionnally that is is non-empty, but we drop this condition in the formalization). -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (λ t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, measurable_set_generate_from ht) }) end dynkin_system theorem induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀ t ∈ s, C t) (h_compl : ∀ t, measurable_set t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, measurable_set (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, measurable_set t → C t := have eq : measurable_set = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space
fcda1711f81f7386529835e9ccd0adef29fb7963
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/mutwf1.lean
cc140cdd6c79e14a7f04f69d33cc38158691aa3c
[ "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
587
lean
mutual def f : Nat → Bool → Nat | n, true => 2 * f n false | 0, false => 1 | n, false => n + g n def g (n : Nat) : Nat := if h : n ≠ 0 then f (n-1) true else n end termination_by invImage (fun | Sum.inl ⟨n, true⟩ => (n, 2) | Sum.inl ⟨n, false⟩ => (n, 1) | Sum.inr n => (n, 0)) $ Prod.lex sizeOfWFRel sizeOfWFRel decreasing_by simp [invImage, InvImage, Prod.lex, sizeOfWFRel, measure, Nat.lt_wfRel] first | apply Prod.Lex.left apply Nat.pred_lt | apply Prod.Lex.right decide done -- should fail
869c81b36db361e9e633a0827ac5c2e23c79f28b
05b503addd423dd68145d68b8cde5cd595d74365
/src/analysis/normed_space/basic.lean
de2442d40c07d65a4a01a821eb9483254b16c6e9
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,269
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.basic import topology.instances.nnreal topology.instances.complex import topology.algebra.module import topology.metric_space.lipschitz import topology.metric_space.antilipschitz /-! # Normed spaces -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e section prio set_option default_priority 100 -- see Note [default priority] /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) end prio /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by simp [sub_eq_add_neg] ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := dist_add_right _ _ _ /-- Triangle inequality for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _ lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥s.sum f∥ ≤ s.sum n := by { haveI := classical.dec_eq β, exact le_trans (norm_sum_le s f) (finset.sum_le_sum h) } lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] section nnnorm /-- Version of the norm taking values in nonnegative reals. -/ def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } end nnnorm lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add' (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul'], apply le_div_of_mul_le (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end /-- A submodule of a normed group is also a normed group, with the restriction of the norm. As all instances can be inferred from the submodule `s`, they are put as implicit instead of typeclasses. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := by simp [norm, le_max_left] lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := by simp [norm, le_max_right] lemma norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl } lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) := have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto.comp continuous_norm.continuous_at h lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) := tendsto.comp continuous_nnnorm.continuous_at h /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end /-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm, sub_eq_add_neg]; abel ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _ ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : topological_add_monoid α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference end normed_group section normed_ring section prio set_option default_priority 100 -- see Note [default priority] /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) end prio @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_add_le }, { rw ←zero_add (0 : ℝ), apply tendsto.add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto.mul, { apply continuous_iff_continuous_at.1, apply continuous_norm.comp continuous_fst }, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto.mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ /-- A normed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) end prio @[priority 100] -- see Note [lower instance priority] instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul'], ..i } namespace normed_field @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul' ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt (norm_pos_iff.2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (s.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := begin classical, by_cases hb : b = 0, {simp [hb]}, apply eq_div_of_mul_eq, { apply ne_of_gt, apply norm_pos_iff.mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α] (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α] {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ lemma punctured_nhds_ne_bot {α : Type*} [nondiscrete_normed_field α] (x : α) : nhds_within x (-{x}) ≠ ⊥ := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := begin refine (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _), let δ := min (ε/2 * ∥r∥^2) (∥r∥/2), have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0, have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos' (half_pos εpos) (pow_pos norm_r_pos 2), have δpos : 0 < δ, by simp [half_pos norm_r_pos, A], refine ⟨δ, δpos, λ x hx, _⟩, have rx : ∥r∥/2 ≤ ∥x∥ := calc ∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring ... ≤ ∥r∥ - ∥r - x∥ : begin apply sub_le_sub (le_refl _), rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_right _ _) end ... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x) ... = ∥x∥ : by simp [sub_sub_cancel], have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx, have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹, by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm, ← mul_assoc, inv_mul_cancel r0, one_mul], calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _ ... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv] ... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, inv_nonneg.2, mul_nonneg, (inv_le_inv norm_x_pos norm_r_pos).2, le_refl], show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2, by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) }, show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹, { convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx, rw [inv_div, div_eq_inv_mul', mul_comm] }, show (0 : ℝ) ≤ 2, by norm_num end ... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring } ... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp } end lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} := begin assume x hx, apply continuous_at.continuous_within_at, exact (tendsto_inv hx) end instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } end normed_field /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological groups. -/ lemma filter.tendsto.inv' [normed_field α] {l : filter β} {f : β → α} {y : α} (hy : y ≠ 0) (h : tendsto f l (𝓝 y)) : tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) := (normed_field.tendsto_inv hy).comp h lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) : tendsto (λa, f a / g a) l (𝓝 (x / y)) := hf.mul (hg.inv' hy) lemma real.norm_eq_abs (r : ℝ) : norm r = abs r := rfl @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] @[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] instance : normed_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] } @[elim_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[elim_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[elim_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section normed_space section prio set_option default_priority 100 -- see Note [default priority] -- see Note[vector space definition] for why we extend `module`. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends module α β := (norm_smul : ∀ (a:α) (b:β), norm (a • b) = has_norm.norm a * norm b) end prio variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul := normed_field.norm_mul } set_option class.instance_max_depth 43 lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul s x lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = nnnorm s * nndist x y := nnreal.eq $ dist_smul s x y variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] @[priority 100] -- see Note [lower instance priority] instance normed_space.topological_vector_space : topological_vector_space α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end /-- In a normed space over a nondiscrete normed field, only `⊤` submodule has a nonempty interior. See also `submodule.eq_top_of_nonempty_interior'` for a `topological_module` version. -/ lemma submodule.eq_top_of_nonempty_interior {α E : Type*} [nondiscrete_normed_field α] [normed_group E] [normed_space α E] (s : submodule α E) (hs : (interior (s:set E)).nonempty) : s = ⊤ := begin refine s.eq_top_of_nonempty_interior' _ hs, simp only [is_unit_iff_ne_zero, @ne.def α, set.mem_singleton_iff.symm], exact normed_field.punctured_nhds_ne_bot _ end open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos (norm_pos_iff.2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul', div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul', le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul'], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, change max (∥s • x₁∥) (∥s • x₂∥) = ∥s∥ * max (∥x₁∥) (∥x₂∥), rw [norm_smul, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg _)] end, add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.module } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s := { norm_smul := λc x, norm_smul c (x : E) } end normed_space section normed_algebra section prio set_option default_priority 100 -- see Note [default priority] /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜' x∥ = ∥x∥) end prio @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜' x∥ = ∥x∥ := normed_algebra.norm_algebra_map_eq _ _ end normed_algebra section restrict_scalars set_option class.instance_max_depth 40 variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] /-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul := λc x, begin change ∥(algebra_map 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..module.restrict_scalars 𝕜 𝕜' E } end restrict_scalars section summable open_locale classical open finset filter variables [normed_group α] @[nolint ge_or_gt] -- see Note [nolint_ge] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, s.sum f) ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε := begin simp only [cauchy_seq_finset_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, s.sum f) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, s.sum f) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : β → finset ι} {p : filter β} (hp : p ≠ ⊥) (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, (s b).sum f) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hp hs ha /-- If `∑ i, ∥f i∥` is summable, then `∥(∑ i, f i)∥ ≤ (∑ i, ∥f i∥)`. Note that we do not assume that `∑ i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑i, f i)∥ ≤ (∑ i, ∥f i∥) := begin by_cases h : summable f, { have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (𝓝 ∥(∑ i, f i)∥) := (continuous_norm.tendsto _).comp h.has_sum, have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (𝓝 (∑ i, ∥f i∥)) := hf.has_sum, exact le_of_tendsto_of_tendsto' at_top_ne_bot h₁ h₂ (assume s, norm_sum_le _ _) }, { rw tsum_eq_zero_of_not_summable h, simp [tsum_nonneg] } end variable [complete_space α] lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g) (h : ∀i, nnnorm (f i) ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable
3fd43b7a13134cf7a03d68ffc711f988303a373f
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/associated.lean
5484fe1d002be1a519b92ca630b817f61314f98e
[ "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
24,801
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker -/ import data.multiset.basic /-! # Associated, prime, and irreducible elements. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} @[simp] theorem is_unit_zero_iff [semiring α] : is_unit (0 : α) ↔ (0:α) = 1 := ⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0, λ h, begin haveI := subsingleton_of_zero_eq_one _ h, refine ⟨⟨0, 0, _, _⟩, rfl⟩; apply subsingleton.elim end⟩ @[simp] theorem not_is_unit_zero [semiring α] [nonzero α] : ¬ is_unit (0 : α) := mt is_unit_zero_iff.1 zero_ne_one lemma is_unit_pow [monoid α] {a : α} (n : ℕ) : is_unit a → is_unit (a ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ theorem is_unit_iff_dvd_one [comm_semiring α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_semiring α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩ theorem mul_dvd_of_is_unit_left [comm_semiring α] {x y z : α} (h : is_unit x) : x * y ∣ z ↔ y ∣ z := ⟨dvd_trans (dvd_mul_left _ _), dvd_trans $ by simpa using mul_dvd_mul_right (is_unit_iff_dvd_one.1 h) y⟩ theorem mul_dvd_of_is_unit_right [comm_semiring α] {x y z : α} (h : is_unit y) : x * y ∣ z ↔ x ∣ z := by rw [mul_comm, mul_dvd_of_is_unit_left h] @[simp] lemma unit_mul_dvd_iff [comm_semiring α] {a b : α} {u : units α} : (u : α) * a ∣ b ↔ a ∣ b := mul_dvd_of_is_unit_left (is_unit_unit _) lemma mul_unit_dvd_iff [comm_semiring α] {a b : α} {u : units α} : a * u ∣ b ↔ a ∣ b := units.coe_mul_dvd _ _ _ theorem is_unit_of_dvd_unit {α} [comm_semiring α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu theorem is_unit_int {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := ⟨begin rintro ⟨u, rfl⟩, exact (int.units_eq_one_or u).elim (by simp) (by simp) end, λ h, is_unit_iff_dvd_one.2 ⟨n, by rw [← int.nat_abs_mul_self, h]; refl⟩⟩ lemma is_unit_of_dvd_one [comm_semiring α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [integral_domain α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ x ≠ 0 ∧ ∃ d : α, ¬ is_unit d ∧ y = x * d := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, (domain.mul_right_inj hx0).1 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ lemma pow_dvd_pow_iff [integral_domain α] {x : α} {n m : ℕ} (h0 : x ≠ 0) (h1 : ¬ is_unit x) : x ^ n ∣ x ^ m ↔ n ≤ m := begin split, { intro h, rw [← not_lt], intro hmn, apply h1, have : x * x ^ m ∣ 1 * x ^ m, { rw [← pow_succ, one_mul], exact dvd_trans (pow_dvd_pow _ (nat.succ_le_of_lt hmn)) h }, rwa [mul_dvd_mul_iff_right, ← is_unit_iff_dvd_one] at this, apply pow_ne_zero m h0 }, { apply pow_dvd_pow } end /-- prime element of a semiring -/ def prime [comm_semiring α] (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) namespace prime lemma ne_zero [comm_semiring α] {p : α} (hp : prime p) : p ≠ 0 := hp.1 lemma not_unit [comm_semiring α] {p : α} (hp : prime p) : ¬ is_unit p := hp.2.1 lemma div_or_div [comm_semiring α] {p : α} (hp : prime p) {a b : α} (h : p ∣ a * b) : p ∣ a ∨ p ∣ b := hp.2.2 a b h end prime @[simp] lemma not_prime_zero [comm_semiring α] : ¬ prime (0 : α) := λ h, h.ne_zero rfl @[simp] lemma not_prime_one [comm_semiring α] : ¬ prime (1 : α) := λ h, h.not_unit is_unit_one lemma exists_mem_multiset_dvd_of_prime [comm_semiring α] {s : multiset α} {p : α} (hp : prime p) : p ∣ s.prod → ∃a∈s, p ∣ a := multiset.induction_on s (assume h, (hp.not_unit $ is_unit_of_dvd_one _ h).elim) $ assume a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.div_or_div this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ @[class] def irreducible [monoid α] (p : α) : Prop := ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b namespace irreducible lemma not_unit [monoid α] {p : α} (hp : irreducible p) : ¬ is_unit p := hp.1 lemma is_unit_or_is_unit [monoid α] {p : α} (hp : irreducible p) {a b : α} (h : p = a * b) : is_unit a ∨ is_unit b := hp.2 a b h end irreducible @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible] @[simp] theorem not_irreducible_zero [semiring α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem irreducible.ne_zero [semiring α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end lemma irreducible_of_prime [integral_domain α] {p : α} (hp : prime p) : irreducible p := ⟨hp.not_unit, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.div_or_div (hab ▸ (dvd_refl _))).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show a ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show b ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [integral_domain α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, _root_.pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.ne_zero, have hpd : p ∣ x * y, from ⟨z, by rwa [domain.mul_right_inj hp0] at h⟩, (hp.div_or_div hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) /-- Two elements of a `monoid` are `associated` if one of them is another one multiplied by a unit on the right. -/ def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, (one_mul _).symm⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [comm_semiring α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ theorem associated_of_dvd_dvd [integral_domain α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin haveI := classical.dec_eq α, rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have : a * 1 = a * (c * d), { simpa [mul_assoc] using a_eq }, have : 1 = (c * d), from eq_of_mul_eq_mul_left ha0 this, exact ⟨units.mk_of_mul_eq_one c d (this.symm), by rw [units.mk_of_mul_eq_one, units.val_coe]⟩ end lemma exists_associated_mem_of_dvd_prod [integral_domain α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.not_unit]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.div_or_div hps with h h, { use [a, by simp], cases h with u hu, cases ((irreducible_of_prime (hs a (multiset.mem_cons.2 (or.inl rfl)))).2 p u hu).resolve_left hp.not_unit with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma dvd_iff_dvd_of_rel_left [comm_semiring α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ mul_unit_dvd_iff.symm lemma dvd_mul_unit_iff [comm_semiring α] {a b : α} {u : units α} : a ∣ b * u ↔ a ∣ b := units.dvd_coe_mul _ _ _ lemma dvd_iff_dvd_of_rel_right [comm_semiring α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ dvd_mul_unit_iff.symm lemma eq_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma ne_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := by haveI := classical.dec; exact not_iff_not.2 (eq_zero_iff_of_associated h) lemma prime_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨(ne_zero_iff_of_associated h).1 hp.ne_zero, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.not_unit ⟨v * u⁻¹, by simp [hv, hu.symm]⟩, hu ▸ by { simp [mul_unit_dvd_iff], intros a b, exact hp.div_or_div }⟩⟩ lemma prime_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨prime_of_associated h, prime_of_associated h.symm⟩ lemma is_unit_iff_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩, let ⟨u, hu⟩ := h.symm in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩⟩ lemma irreducible_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt (is_unit_iff_of_associated h).2 hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.2 _ _ hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv]⟩)⟩ lemma irreducible_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨irreducible_of_associated h, irreducible_of_associated h.symm⟩ lemma associated_mul_left_cancel [integral_domain α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), (domain.mul_right_inj ha).1 begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated_mul_right_cancel [integral_domain α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated_mul_left_cancel def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ instance [monoid α] : inhabited (associates α) := ⟨⟦1⟧⟩ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := λa b, ∃c, a * c = b, le_refl := assume a, ⟨1, by simp⟩, le_trans := assume a b c ⟨f₁, h₁⟩ ⟨f₂, h₂⟩, ⟨f₁ * f₂, h₂ ▸ h₁ ▸ (mul_assoc _ _ _).symm⟩} instance : has_dvd (associates α) := ⟨(≤)⟩ @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by rw [← multiset.rel_eq]; simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated] theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem coe_unit_eq_one : ∀u:units (associates α), (u : associates α) = 1 | ⟨u, v, huv, hvu⟩ := by rw [mul_eq_one_iff] at huv; exact huv.1 theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx.symm, hy.symm, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := ⟨a, one_mul a⟩ theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_semiring variables [comm_semiring α] @[simp] theorem mk_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ instance : mul_zero_class (associates α) := { mul := (*), zero := 0, zero_mul := by { rintro ⟨a⟩, show associates.mk (0 * a) = associates.mk 0, rw [zero_mul] }, mul_zero := by { rintro ⟨a⟩, show associates.mk (a * 0) = associates.mk 0, rw [mul_zero] } } theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d⁻¹) * c, calc b = (a * c) * ↑d⁻¹ : by rw [← hd, mul_assoc, units.mul_inv, mul_one] ... = a * (↑d⁻¹ * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd def prime (p : associates α) : Prop := p ≠ 0 ∧ p ≠ 1 ∧ (∀a b, p ≤ a * b → p ≤ a ∨ p ≤ b) lemma prime.ne_zero {p : associates α} (hp : prime p) : p ≠ 0 := hp.1 lemma prime.ne_one {p : associates α} (hp : prime p) : p ≠ 1 := hp.2.1 lemma prime.le_or_le {p : associates α} (hp : prime p) {a b : associates α} (h : p ≤ a * b) : p ≤ a ∨ p ≤ b := hp.2.2 a b h lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.ne_one (mul_eq_one_iff.1 eq).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match hp.le_or_le this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [associates.prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_eq_zero] }, apply and_congr, { rw [(≠), ← is_unit_iff_eq_one, is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff] end end comm_semiring section integral_domain variable [integral_domain α] instance : partial_order (associates α) := { le_antisymm := assume a' b', quotient.induction_on₂ a' b' $ assume a b ⟨f₁', h₁⟩ ⟨f₂', h₂⟩, (quotient.induction_on₂ f₁' f₂' $ assume f₁ f₂ h₁ h₂, let ⟨c₁, h₁⟩ := quotient.exact h₁, ⟨c₂, h₂⟩ := quotient.exact h₂ in quotient.sound $ associated_of_dvd_dvd (h₁ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) (h₂ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)) h₁ h₂ .. associates.preorder } instance : order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : order_top (associates α) := { top := 0, le_top := assume a, ⟨0, mul_zero a⟩, .. associates.partial_order } instance : nonzero (associates α) := ⟨ assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this ⟩ instance : no_zero_divisors (associates α) := ⟨λ x y, (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl))⟩ theorem prod_eq_zero_iff {s : multiset (associates α)} : s.prod = 0 ↔ (0 : associates α) ∈ s := multiset.induction_on s (by simp; exact zero_ne_one.symm) $ assume a s, by simp [mul_eq_zero, @eq_comm _ 0 a] {contextual := tt} theorem irreducible_mk_iff (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp [irreducible, is_unit_mk], apply and_congr iff.rfl, split, { assume h x y eq, have : is_unit (associates.mk x) ∨ is_unit (associates.mk y), from h _ _ (by rw [eq]; refl), simpa [is_unit_mk] }, { refine assume h x y, quotient.induction_on₂ x y (assume x y eq, _), rcases quotient.exact eq.symm with ⟨u, eq⟩, have : a = x * (y * u), by rwa [mul_assoc, eq_comm] at eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ this } end lemma eq_of_mul_eq_mul_left : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, eq_of_mul_eq_mul_left (mt mk_eq_zero.2 ha) hu⟩ end lemma le_of_mul_le_mul_left (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d (le_refl _) with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end end integral_domain end associates
752ce7ef7f078974452faeae300315ee62adb280
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/noncomm_pi_coprod.lean
5dd7f2871e239878117e72f6c87545545be38b96
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
9,645
lean
/- Copyright (c) 2022 Joachim Breitner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joachim Breitner -/ import group_theory.order_of_element import data.finset.noncomm_prod import data.fintype.card /-! # Canonical homomorphism from a finite family of monoids This file defines the construction of the canonical homomorphism from a family of monoids. Given a family of morphisms `ϕ i : N i →* M` for each `i : ι` where elements in the images of different morphisms commute, we obtain a canonical morphism `monoid_hom.noncomm_pi_coprod : (Π i, N i) →* M` that coincides with `ϕ` ## Main definitions * `monoid_hom.noncomm_pi_coprod : (Π i, N i) →* M` is the main homomorphism * `subgroup.noncomm_pi_coprod : (Π i, H i) →* G` is the specialization to `H i : subgroup G` and the subgroup embedding. ## Main theorems * `monoid_hom.noncomm_pi_coprod` coincides with `ϕ i` when restricted to `N i` * `monoid_hom.noncomm_pi_coprod_mrange`: The range of `monoid_hom.noncomm_pi_coprod` is `⨆ (i : ι), (ϕ i).mrange` * `monoid_hom.noncomm_pi_coprod_range`: The range of `monoid_hom.noncomm_pi_coprod` is `⨆ (i : ι), (ϕ i).range` * `subgroup.noncomm_pi_coprod_range`: The range of `subgroup.noncomm_pi_coprod` is `⨆ (i : ι), H i`. * `monoid_hom.injective_noncomm_pi_coprod_of_independent`: in the case of groups, `pi_hom.hom` is injective if the `ϕ` are injective and the ranges of the `ϕ` are independent. * `monoid_hom.independent_range_of_coprime_order`: If the `N i` have coprime orders, then the ranges of the `ϕ` are independent. * `subgroup.independent_of_coprime_order`: If commuting normal subgroups `H i` have coprime orders, they are independent. -/ open_locale big_operators section family_of_monoids variables {M : Type*} [monoid M] -- We have a family of monoids -- The fintype assumption is not always used, but declared here, to keep things in order variables {ι : Type*} [hdec : decidable_eq ι] [fintype ι] variables {N : ι → Type*} [∀ i, monoid (N i)] -- And morphisms ϕ into G variables (ϕ : Π (i : ι), N i →* M) -- We assume that the elements of different morphism commute variables (hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : N i) (y : N j), commute (ϕ i x) (ϕ j y)) include hcomm -- We use `f` and `g` to denote elements of `Π (i : ι), N i` variables (f g : Π (i : ι), N i) namespace monoid_hom /-- The canonical homomorphism from a family of monoids. -/ @[to_additive "The canonical homomorphism from a family of additive monoids. See also `linear_map.lsum` for a linear version without the commutativity assumption."] def noncomm_pi_coprod : (Π (i : ι), N i) →* M := { to_fun := λ f, finset.univ.noncomm_prod (λ i, ϕ i (f i)) $ by { rintros i - j -, by_cases h : i = j, { subst h }, { exact hcomm _ _ h _ _ } }, map_one' := by {apply (finset.noncomm_prod_eq_pow_card _ _ _ _ _).trans (one_pow _), simp}, map_mul' := λ f g, begin classical, convert @finset.noncomm_prod_mul_distrib _ _ _ _ (λ i, ϕ i (f i)) (λ i, ϕ i (g i)) _ _ _, { ext i, exact map_mul (ϕ i) (f i) (g i), }, { rintros i - j - h, exact hcomm _ _ h _ _ }, end } variable {hcomm} include hdec @[simp, to_additive] lemma noncomm_pi_coprod_mul_single (i : ι) (y : N i): noncomm_pi_coprod ϕ hcomm (pi.mul_single i y) = ϕ i y := begin change finset.univ.noncomm_prod (λ j, ϕ j (pi.mul_single i y j)) _ = ϕ i y, simp only [←finset.insert_erase (finset.mem_univ i)] {single_pass := tt}, rw finset.noncomm_prod_insert_of_not_mem _ _ _ _ (finset.not_mem_erase i _), rw pi.mul_single_eq_same, rw finset.noncomm_prod_eq_pow_card, { rw one_pow, exact mul_one _ }, { intros j hj, simp only [finset.mem_erase] at hj, simp [hj], }, end omit hcomm /-- The universal property of `noncomm_pi_coprod` -/ @[to_additive "The universal property of `noncomm_pi_coprod`"] def noncomm_pi_coprod_equiv : {ϕ : Π i, N i →* M // pairwise (λ i j, ∀ x y, commute (ϕ i x) (ϕ j y)) } ≃ ((Π i, N i) →* M) := { to_fun := λ ϕ, noncomm_pi_coprod ϕ.1 ϕ.2, inv_fun := λ f, ⟨ λ i, f.comp (monoid_hom.single N i), λ i j hij x y, commute.map (pi.mul_single_commute i j hij x y) f ⟩, left_inv := λ ϕ, by { ext, simp, }, right_inv := λ f, pi_ext (λ i x, by simp) } omit hdec include hcomm @[to_additive] lemma noncomm_pi_coprod_mrange : (noncomm_pi_coprod ϕ hcomm).mrange = ⨆ i : ι, (ϕ i).mrange := begin classical, apply le_antisymm, { rintro x ⟨f, rfl⟩, refine submonoid.noncomm_prod_mem _ _ _ _ _, intros i hi, apply submonoid.mem_Sup_of_mem, { use i }, simp, }, { refine supr_le _, rintro i x ⟨y, rfl⟩, refine ⟨pi.mul_single i y, noncomm_pi_coprod_mul_single _ _ _⟩, }, end end monoid_hom end family_of_monoids section family_of_groups variables {G : Type*} [group G] variables {ι : Type*} [hdec : decidable_eq ι] [hfin : fintype ι] variables {H : ι → Type*} [∀ i, group (H i)] variables (ϕ : Π (i : ι), H i →* G) variables {hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), commute (ϕ i x) (ϕ j y)} include hcomm -- We use `f` and `g` to denote elements of `Π (i : ι), H i` variables (f g : Π (i : ι), H i) include hfin namespace monoid_hom -- The subgroup version of `noncomm_pi_coprod_mrange` @[to_additive] lemma noncomm_pi_coprod_range : (noncomm_pi_coprod ϕ hcomm).range = ⨆ i : ι, (ϕ i).range := begin classical, apply le_antisymm, { rintro x ⟨f, rfl⟩, refine subgroup.noncomm_prod_mem _ _ _, intros i hi, apply subgroup.mem_Sup_of_mem, { use i }, simp, }, { refine supr_le _, rintro i x ⟨y, rfl⟩, refine ⟨pi.mul_single i y, noncomm_pi_coprod_mul_single _ _ _⟩, }, end @[to_additive] lemma injective_noncomm_pi_coprod_of_independent (hind : complete_lattice.independent (λ i, (ϕ i).range)) (hinj : ∀ i, function.injective (ϕ i)) : function.injective (noncomm_pi_coprod ϕ hcomm):= begin classical, apply (monoid_hom.ker_eq_bot_iff _).mp, apply eq_bot_iff.mpr, intros f heq1, change finset.univ.noncomm_prod (λ i, ϕ i (f i)) _ = 1 at heq1, change f = 1, have : ∀ i, i ∈ finset.univ → ϕ i (f i) = 1 := subgroup.eq_one_of_noncomm_prod_eq_one_of_independent _ _ _ _ hind (by simp) heq1, ext i, apply hinj, simp [this i (finset.mem_univ i)], end variable (hcomm) @[to_additive] lemma independent_range_of_coprime_order [∀ i, fintype (H i)] (hcoprime : ∀ i j, i ≠ j → nat.coprime (fintype.card (H i)) (fintype.card (H j))) : complete_lattice.independent (λ i, (ϕ i).range) := begin classical, rintros i f ⟨hxi, hxp⟩, dsimp at hxi hxp, rw [supr_subtype', ← noncomm_pi_coprod_range] at hxp, rotate, { intros _ _ hj, apply hcomm, exact hj ∘ subtype.ext }, cases hxp with g hgf, cases hxi with g' hg'f, have hxi : order_of f ∣ fintype.card (H i), { rw ← hg'f, exact (order_of_map_dvd _ _).trans order_of_dvd_card_univ }, have hxp : order_of f ∣ ∏ j : {j // j ≠ i}, fintype.card (H j), { rw [← hgf, ← fintype.card_pi], exact (order_of_map_dvd _ _).trans order_of_dvd_card_univ }, change f = 1, rw [← pow_one f, ← order_of_dvd_iff_pow_eq_one], convert ← nat.dvd_gcd hxp hxi, rw ← nat.coprime_iff_gcd_eq_one, apply nat.coprime_prod_left, intros j _, apply hcoprime, exact j.2, end end monoid_hom end family_of_groups namespace subgroup -- We have an family of subgroups variables {G : Type*} [group G] variables {ι : Type*} [hdec : decidable_eq ι] [hfin : fintype ι] {H : ι → subgroup G} -- Elements of `Π (i : ι), H i` are called `f` and `g` here variables (f g : Π (i : ι), H i) section commuting_subgroups -- We assume that the elements of different subgroups commute variables (hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → commute x y) include hcomm @[to_additive] lemma commute_subtype_of_commute (i j : ι) (hne : i ≠ j) : ∀ (x : H i) (y : H j), commute ((H i).subtype x) ((H j).subtype y) := by { rintros ⟨x, hx⟩ ⟨y, hy⟩, exact hcomm i j hne x y hx hy } include hfin /-- The canonical homomorphism from a family of subgroups where elements from different subgroups commute -/ @[to_additive "The canonical homomorphism from a family of additive subgroups where elements from different subgroups commute"] def noncomm_pi_coprod : (Π (i : ι), H i) →* G := monoid_hom.noncomm_pi_coprod (λ i, (H i).subtype) (commute_subtype_of_commute hcomm) variable {hcomm} include hdec @[simp, to_additive] lemma noncomm_pi_coprod_mul_single (i : ι) (y : H i) : noncomm_pi_coprod hcomm (pi.mul_single i y) = y := by apply monoid_hom.noncomm_pi_coprod_mul_single omit hdec @[to_additive] lemma noncomm_pi_coprod_range : (noncomm_pi_coprod hcomm).range = ⨆ i : ι, H i := by simp [noncomm_pi_coprod, monoid_hom.noncomm_pi_coprod_range] @[to_additive] lemma injective_noncomm_pi_coprod_of_independent (hind : complete_lattice.independent H) : function.injective (noncomm_pi_coprod hcomm) := begin apply monoid_hom.injective_noncomm_pi_coprod_of_independent, { simpa using hind }, { intro i, exact subtype.coe_injective } end variable (hcomm) @[to_additive] lemma independent_of_coprime_order [∀ i, fintype (H i)] (hcoprime : ∀ i j, i ≠ j → nat.coprime (fintype.card (H i)) (fintype.card (H j))) : complete_lattice.independent H := begin simpa using monoid_hom.independent_range_of_coprime_order (λ i, (H i).subtype) (commute_subtype_of_commute hcomm) hcoprime, end end commuting_subgroups end subgroup
db7fcc563c478f36d002314d4c4ebb04923c3969
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/monoid_algebra/support.lean
9d94e76b6fb2a61d017ec59e6721a618f2be70a7
[ "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
6,080
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.monoid_algebra.basic /-! # Lemmas about the support of a finitely supported function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes u₁ u₂ u₃ namespace monoid_algebra open finset finsupp variables {k : Type u₁} {G : Type u₂} [semiring k] lemma support_single_mul_subset [decidable_eq G] [has_mul G] (f : monoid_algebra k G) (r : k) (a : G) : (single a r * f : monoid_algebra k G).support ⊆ finset.image ((*) a) f.support := begin intros x hx, contrapose hx, have : ∀ y, a * y = x → f y = 0, { simpa only [not_and', mem_image, mem_support_iff, exists_prop, not_exists, not_not] using hx }, simp only [mem_support_iff, mul_apply, sum_single_index, zero_mul, if_t_t, sum_zero, not_not], exact finset.sum_eq_zero (by simp only [this, mem_support_iff, mul_zero, ne.def, ite_eq_right_iff, eq_self_iff_true, implies_true_iff] {contextual := tt}), end lemma support_mul_single_subset [decidable_eq G] [has_mul G] (f : monoid_algebra k G) (r : k) (a : G) : (f * single a r).support ⊆ finset.image (* a) f.support := begin intros x hx, contrapose hx, have : ∀ y, y * a = x → f y = 0, { simpa only [not_and', mem_image, mem_support_iff, exists_prop, not_exists, not_not] using hx }, simp only [mem_support_iff, mul_apply, sum_single_index, zero_mul, if_t_t, sum_zero, not_not], exact finset.sum_eq_zero (by simp only [this, sum_single_index, ite_eq_right_iff, eq_self_iff_true, implies_true_iff, zero_mul] {contextual := tt}), end lemma support_single_mul_eq_image [decidable_eq G] [has_mul G] (f : monoid_algebra k G) {r : k} (hr : ∀ y, r * y = 0 ↔ y = 0) {x : G} (lx : is_left_regular x) : (single x r * f : monoid_algebra k G).support = finset.image ((*) x) f.support := begin refine subset_antisymm (support_single_mul_subset f _ _) (λ y hy, _), obtain ⟨y, yf, rfl⟩ : ∃ (a : G), a ∈ f.support ∧ x * a = y, { simpa only [finset.mem_image, exists_prop] using hy }, simp only [mul_apply, mem_support_iff.mp yf, hr, mem_support_iff, sum_single_index, finsupp.sum_ite_eq', ne.def, not_false_iff, if_true, zero_mul, if_t_t, sum_zero, lx.eq_iff] end lemma support_mul_single_eq_image [decidable_eq G] [has_mul G] (f : monoid_algebra k G) {r : k} (hr : ∀ y, y * r = 0 ↔ y = 0) {x : G} (rx : is_right_regular x) : (f * single x r).support = finset.image (* x) f.support := begin refine subset_antisymm (support_mul_single_subset f _ _) (λ y hy, _), obtain ⟨y, yf, rfl⟩ : ∃ (a : G), a ∈ f.support ∧ a * x = y, { simpa only [finset.mem_image, exists_prop] using hy }, simp only [mul_apply, mem_support_iff.mp yf, hr, mem_support_iff, sum_single_index, finsupp.sum_ite_eq', ne.def, not_false_iff, if_true, mul_zero, if_t_t, sum_zero, rx.eq_iff] end lemma support_mul [has_mul G] [decidable_eq G] (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bUnion_mono $ assume a₁ _, subset.trans support_sum $ bUnion_mono $ assume a₂ _, support_single_subset lemma support_mul_single [right_cancel_semigroup G] (f : monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) : (f * single x r).support = f.support.map (mul_right_embedding x) := begin classical, ext, simp only [support_mul_single_eq_image f hr (is_right_regular_of_right_cancel_semigroup x), mem_image, mem_map, mul_right_embedding_apply], end lemma support_single_mul [left_cancel_semigroup G] (f : monoid_algebra k G) (r : k) (hr : ∀ y, r * y = 0 ↔ y = 0) (x : G) : (single x r * f : monoid_algebra k G).support = f.support.map (mul_left_embedding x) := begin classical, ext, simp only [support_single_mul_eq_image f hr (is_left_regular_of_left_cancel_semigroup x), mem_image, mem_map, mul_left_embedding_apply], end section span variables [mul_one_class G] /-- An element of `monoid_algebra k G` is in the subalgebra generated by its support. -/ lemma mem_span_support (f : monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span end monoid_algebra namespace add_monoid_algebra open finset finsupp mul_opposite variables {k : Type u₁} {G : Type u₂} [semiring k] lemma support_mul [decidable_eq G] [has_add G] (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ + a₂}) := @monoid_algebra.support_mul k (multiplicative G) _ _ _ _ _ lemma support_mul_single [add_right_cancel_semigroup G] (f : add_monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) : (f * single x r : add_monoid_algebra k G).support = f.support.map (add_right_embedding x) := @monoid_algebra.support_mul_single k (multiplicative G) _ _ _ _ hr _ lemma support_single_mul [add_left_cancel_semigroup G] (f : add_monoid_algebra k G) (r : k) (hr : ∀ y, r * y = 0 ↔ y = 0) (x : G) : (single x r * f : add_monoid_algebra k G).support = f.support.map (add_left_embedding x) := @monoid_algebra.support_single_mul k (multiplicative G) _ _ _ _ hr _ section span /-- An element of `add_monoid_algebra k G` is in the submodule generated by its support. -/ lemma mem_span_support [add_zero_class G] (f : add_monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] /-- An element of `add_monoid_algebra k G` is in the subalgebra generated by its support, using unbundled inclusion. -/ lemma mem_span_support' (f : add_monoid_algebra k G) : f ∈ submodule.span k (of' k G '' (f.support : set G)) := by rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span end add_monoid_algebra
2cd375e8fb1d62ff86d466678d667379c28dd026
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/locally_convex/polar.lean
fbabe99e3fd6ae44ba4b6692c88e22f46093b6fe
[ "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
4,694
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll, Kalle Kytölä -/ import analysis.normed.field.basic import analysis.convex.basic import linear_algebra.sesquilinear_form import topology.algebra.module.weak_dual /-! # Polar set In this file we define the polar set. There are different notions of the polar, we will define the *absolute polar*. The advantage over the real polar is that we can define the absolute polar for any bilinear form `B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜`, where `𝕜` is a normed commutative ring and `E` and `F` are modules over `𝕜`. ## Main definitions * `linear_map.polar`: The polar of a bilinear form `B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜`. ## Main statements * `linear_map.polar_eq_Inter`: The polar as an intersection. * `linear_map.subset_bipolar`: The polar is a subset of the bipolar. * `linear_map.polar_weak_closed`: The polar is closed in the weak topology induced by `B.flip`. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags polar -/ variables {𝕜 E F : Type*} namespace linear_map section normed_ring variables [normed_comm_ring 𝕜] [add_comm_monoid E] [add_comm_monoid F] variables [module 𝕜 E] [module 𝕜 F] variables (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) /-- The (absolute) polar of `s : set E` is given by the set of all `y : F` such that `∥B x y∥ ≤ 1` for all `x ∈ s`.-/ def polar (s : set E) : set F := {y : F | ∀ x ∈ s, ∥B x y∥ ≤ 1 } lemma polar_mem_iff (s : set E) (y : F) : y ∈ B.polar s ↔ ∀ x ∈ s, ∥B x y∥ ≤ 1 := iff.rfl lemma polar_mem (s : set E) (y : F) (hy : y ∈ B.polar s) : ∀ x ∈ s, ∥B x y∥ ≤ 1 := hy @[simp] lemma zero_mem_polar (s : set E) : (0 : F) ∈ B.polar s := λ _ _, by simp only [map_zero, norm_zero, zero_le_one] lemma polar_eq_Inter {s : set E} : B.polar s = ⋂ x ∈ s, {y : F | ∥B x y∥ ≤ 1} := by { ext, simp only [polar_mem_iff, set.mem_Inter, set.mem_set_of_eq] } /-- The map `B.polar : set E → set F` forms an order-reversing Galois connection with `B.flip.polar : set F → set E`. We use `order_dual.to_dual` and `order_dual.of_dual` to express that `polar` is order-reversing. -/ lemma polar_gc : galois_connection (order_dual.to_dual ∘ B.polar) (B.flip.polar ∘ order_dual.of_dual) := λ s t, ⟨λ h _ hx _ hy, h hy _ hx, λ h _ hx _ hy, h hy _ hx⟩ @[simp] lemma polar_Union {ι} {s : ι → set E} : B.polar (⋃ i, s i) = ⋂ i, B.polar (s i) := B.polar_gc.l_supr @[simp] lemma polar_union {s t : set E} : B.polar (s ∪ t) = B.polar s ∩ B.polar t := B.polar_gc.l_sup lemma polar_antitone : antitone (B.polar : set E → set F) := B.polar_gc.monotone_l @[simp] lemma polar_empty : B.polar ∅ = set.univ := B.polar_gc.l_bot @[simp] lemma polar_zero : B.polar ({0} : set E) = set.univ := begin refine set.eq_univ_iff_forall.mpr (λ y x hx, _), rw [set.mem_singleton_iff.mp hx, map_zero, linear_map.zero_apply, norm_zero], exact zero_le_one, end lemma subset_bipolar (s : set E) : s ⊆ B.flip.polar (B.polar s) := λ x hx y hy, by { rw B.flip_apply, exact hy x hx } @[simp] lemma tripolar_eq_polar (s : set E) : B.polar (B.flip.polar (B.polar s)) = B.polar s := begin refine (B.polar_antitone (B.subset_bipolar s)).antisymm _, convert subset_bipolar B.flip (B.polar s), exact B.flip_flip.symm, end /-- The polar set is closed in the weak topology induced by `B.flip`. -/ lemma polar_weak_closed (s : set E) : @is_closed _ (weak_bilin.topological_space B.flip) (B.polar s) := begin rw polar_eq_Inter, refine is_closed_Inter (λ x, is_closed_Inter (λ _, _)), exact is_closed_le (weak_bilin.eval_continuous B.flip x).norm continuous_const, end end normed_ring section nondiscrete_normed_field variables [nondiscrete_normed_field 𝕜] [add_comm_monoid E] [add_comm_monoid F] variables [module 𝕜 E] [module 𝕜 F] variables (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) lemma polar_univ (h : separating_right B) : B.polar set.univ = {(0 : F)} := begin rw set.eq_singleton_iff_unique_mem, refine ⟨by simp only [zero_mem_polar], λ y hy, h _ (λ x, _)⟩, refine norm_le_zero_iff.mp (le_of_forall_le_of_dense $ λ ε hε, _), rcases normed_field.exists_norm_lt 𝕜 hε with ⟨c, hc, hcε⟩, calc ∥B x y∥ = ∥c∥ * ∥B (c⁻¹ • x) y∥ : by rw [B.map_smul, linear_map.smul_apply, algebra.id.smul_eq_mul, norm_mul, norm_inv, mul_inv_cancel_left₀ hc.ne'] ... ≤ ε * 1 : mul_le_mul hcε.le (hy _ trivial) (norm_nonneg _) hε.le ... = ε : mul_one _ end end nondiscrete_normed_field end linear_map
964f32d388523fd0769288b96ee9994899d085c9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/pi/basic.lean
6e4591392d83e93d60fd36d347449f205768a285
[ "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
5,070
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import category_theory.natural_isomorphism import category_theory.eq_to_hom /-! # Categories of indexed families of objects. We define the pointwise category structure on indexed families of objects in a category (and also the dependent generalization). -/ namespace category_theory universes w₀ w₁ w₂ v₁ v₂ u₁ u₂ variables {I : Type w₀} (C : I → Type u₁) [Π i, category.{v₁} (C i)] /-- `pi C` gives the cartesian product of an indexed family of categories. -/ instance pi : category.{max w₀ v₁} (Π i, C i) := { hom := λ X Y, Π i, X i ⟶ Y i, id := λ X i, 𝟙 (X i), comp := λ X Y Z f g i, f i ≫ g i } /-- This provides some assistance to typeclass search in a common situation, which otherwise fails. (Without this `category_theory.pi.has_limit_of_has_limit_comp_eval` fails.) -/ abbreviation pi' {I : Type v₁} (C : I → Type u₁) [Π i, category.{v₁} (C i)] : category.{v₁} (Π i, C i) := category_theory.pi C attribute [instance] pi' namespace pi @[simp] lemma id_apply (X : Π i, C i) (i) : (𝟙 X : Π i, X i ⟶ X i) i = 𝟙 (X i) := rfl @[simp] lemma comp_apply {X Y Z : Π i, C i} (f : X ⟶ Y) (g : Y ⟶ Z) (i) : (f ≫ g : Π i, X i ⟶ Z i) i = f i ≫ g i := rfl /-- The evaluation functor at `i : I`, sending an `I`-indexed family of objects to the object over `i`. -/ @[simps] def eval (i : I) : (Π i, C i) ⥤ C i := { obj := λ f, f i, map := λ f g α, α i, } section variables {J : Type w₁} /-- Pull back an `I`-indexed family of objects to an `J`-indexed family, along a function `J → I`. -/ @[simps] def comap (h : J → I) : (Π i, C i) ⥤ (Π j, C (h j)) := { obj := λ f i, f (h i), map := λ f g α i, α (h i), } variables (I) /-- The natural isomorphism between pulling back a grading along the identity function, and the identity functor. -/ @[simps] def comap_id : comap C (id : I → I) ≅ 𝟭 (Π i, C i) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } }. variables {I} variables {K : Type w₂} /-- The natural isomorphism comparing between pulling back along two successive functions, and pulling back along their composition -/ @[simps] def comap_comp (f : K → J) (g : J → I) : comap C g ⋙ comap (C ∘ g) f ≅ comap C (g ∘ f) := { hom := { app := λ X b, 𝟙 (X (g (f b))) }, inv := { app := λ X b, 𝟙 (X (g (f b))) } } /-- The natural isomorphism between pulling back then evaluating, and just evaluating. -/ @[simps] def comap_eval_iso_eval (h : J → I) (j : J) : comap C h ⋙ eval (C ∘ h) j ≅ eval C (h j) := nat_iso.of_components (λ f, iso.refl _) (by tidy) end section variables {J : Type w₀} {D : J → Type u₁} [Π j, category.{v₁} (D j)] instance sum_elim_category : Π (s : I ⊕ J), category.{v₁} (sum.elim C D s) | (sum.inl i) := by { dsimp, apply_instance, } | (sum.inr j) := by { dsimp, apply_instance, } /-- The bifunctor combining an `I`-indexed family of objects with a `J`-indexed family of objects to obtain an `I ⊕ J`-indexed family of objects. -/ @[simps] def sum : (Π i, C i) ⥤ (Π j, D j) ⥤ (Π s : I ⊕ J, sum.elim C D s) := { obj := λ f, { obj := λ g s, sum.rec f g s, map := λ g g' α s, sum.rec (λ i, 𝟙 (f i)) α s }, map := λ f f' α, { app := λ g s, sum.rec α (λ j, 𝟙 (g j)) s, }} end variables {C} /-- An isomorphism between `I`-indexed objects gives an isomorphism between each pair of corresponding components. -/ @[simps] def iso_app {X Y : Π i, C i} (f : X ≅ Y) (i : I) : X i ≅ Y i := ⟨f.hom i, f.inv i, by { dsimp, rw [← comp_apply, iso.hom_inv_id, id_apply] }, by { dsimp, rw [← comp_apply, iso.inv_hom_id, id_apply] }⟩ @[simp] lemma iso_app_refl (X : Π i, C i) (i : I) : iso_app (iso.refl X) i = iso.refl (X i) := rfl @[simp] lemma iso_app_symm {X Y : Π i, C i} (f : X ≅ Y) (i : I) : iso_app f.symm i = (iso_app f i).symm := rfl @[simp] lemma iso_app_trans {X Y Z : Π i, C i} (f : X ≅ Y) (g : Y ≅ Z) (i : I) : iso_app (f ≪≫ g) i = iso_app f i ≪≫ iso_app g i := rfl end pi namespace functor variables {C} variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)] /-- Assemble an `I`-indexed family of functors into a functor between the pi types. -/ @[simps] def pi (F : Π i, C i ⥤ D i) : (Π i, C i) ⥤ (Π i, D i) := { obj := λ f i, (F i).obj (f i), map := λ f g α i, (F i).map (α i) } -- One could add some natural isomorphisms showing -- how `functor.pi` commutes with `pi.eval` and `pi.comap`. end functor namespace nat_trans variables {C} variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)] variables {F G : Π i, C i ⥤ D i} /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ @[simps] def pi (α : Π i, F i ⟶ G i) : functor.pi F ⟶ functor.pi G := { app := λ f i, (α i).app (f i), } end nat_trans end category_theory
a608731aa49ea11050324c52a92aa11798261942
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/sum.lean
7953f2e8694916cb9a3622e456350f2b25443e5e
[ "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
9,463
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury G. Kudryashov -/ import logic.function.basic /-! # More theorems about the sum type -/ universes u v w x variables {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} open sum /-- Check if a sum is `inl` and if so, retrieve its contents. -/ @[simp] def sum.get_left {α β} : α ⊕ β → option α | (inl a) := some a | (inr _) := none /-- Check if a sum is `inr` and if so, retrieve its contents. -/ @[simp] def sum.get_right {α β} : α ⊕ β → option β | (inr b) := some b | (inl _) := none /-- Check if a sum is `inl`. -/ @[simp] def sum.is_left {α β} : α ⊕ β → bool | (inl _) := tt | (inr _) := ff /-- Check if a sum is `inr`. -/ @[simp] def sum.is_right {α β} : α ⊕ β → bool | (inl _) := ff | (inr _) := tt attribute [derive decidable_eq] sum @[simp] theorem sum.forall {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ (∀ b, p (inr b)) := ⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩ @[simp] theorem sum.exists {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) := ⟨λ h, match h with | ⟨inl a, h⟩ := or.inl ⟨a, h⟩ | ⟨inr b, h⟩ := or.inr ⟨b, h⟩ end, λ h, match h with | or.inl ⟨a, h⟩ := ⟨inl a, h⟩ | or.inr ⟨b, h⟩ := ⟨inr b, h⟩ end⟩ namespace sum lemma inl_injective : function.injective (sum.inl : α → α ⊕ β) := λ x y, sum.inl.inj lemma inr_injective : function.injective (sum.inr : β → α ⊕ β) := λ x y, sum.inr.inj /-- Map `α ⊕ β` to `α' ⊕ β'` sending `α` to `α'` and `β` to `β'`. -/ protected def map (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β' | (sum.inl x) := sum.inl (f x) | (sum.inr x) := sum.inr (g x) @[simp] lemma map_inl (f : α → α') (g : β → β') (x : α) : (inl x).map f g = inl (f x) := rfl @[simp] lemma map_inr (f : α → α') (g : β → β') (x : β) : (inr x).map f g = inr (g x) := rfl @[simp] lemma map_map {α'' β''} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : ∀ x : α ⊕ β, (x.map f g).map f' g' = x.map (f' ∘ f) (g' ∘ g) | (inl a) := rfl | (inr b) := rfl @[simp] lemma map_comp_map {α'' β''} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : (sum.map f' g') ∘ (sum.map f g) = sum.map (f' ∘ f) (g' ∘ g) := funext $ map_map f' g' f g @[simp] lemma map_id_id (α β) : sum.map (@id α) (@id β) = id := funext $ λ x, sum.rec_on x (λ _, rfl) (λ _, rfl) theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b := ⟨inl.inj, congr_arg _⟩ theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b := ⟨inr.inj, congr_arg _⟩ theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b. theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a. /-- Define a function on `α ⊕ β` by giving separate definitions on `α` and `β`. -/ protected def elim {α β γ : Sort*} (f : α → γ) (g : β → γ) : α ⊕ β → γ := λ x, sum.rec_on x f g @[simp] lemma elim_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : α) : sum.elim f g (inl x) = f x := rfl @[simp] lemma elim_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : β) : sum.elim f g (inr x) = g x := rfl @[simp] lemma elim_comp_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inl = f := rfl @[simp] lemma elim_comp_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inr = g := rfl @[simp] lemma elim_inl_inr {α β : Sort*} : @sum.elim α β _ inl inr = id := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) lemma comp_elim {α β γ δ : Sort*} (f : γ → δ) (g : α → γ) (h : β → γ): f ∘ sum.elim g h = sum.elim (f ∘ g) (f ∘ h) := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) @[simp] lemma elim_comp_inl_inr {α β γ : Sort*} (f : α ⊕ β → γ) : sum.elim (f ∘ inl) (f ∘ inr) = f := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) open function (update update_eq_iff update_comp_eq_of_injective update_comp_eq_of_forall_ne) @[simp] lemma update_elim_inl {α β γ} [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : α} {x : γ} : update (sum.elim f g) (inl i) x = sum.elim (update f i x) g := update_eq_iff.2 ⟨by simp, by simp { contextual := tt }⟩ @[simp] lemma update_elim_inr {α β γ} [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : β} {x : γ} : update (sum.elim f g) (inr i) x = sum.elim f (update g i x) := update_eq_iff.2 ⟨by simp, by simp { contextual := tt }⟩ @[simp] lemma update_inl_comp_inl {α β γ} [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inl = update (f ∘ inl) i x := update_comp_eq_of_injective _ inl_injective _ _ @[simp] lemma update_inl_apply_inl {α β γ} [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i j : α} {x : γ} : update f (inl i) x (inl j) = update (f ∘ inl) i x j := by rw ← update_inl_comp_inl @[simp] lemma update_inl_comp_inr {α β γ} [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inr = f ∘ inr := update_comp_eq_of_forall_ne _ _ $ λ _, inr_ne_inl @[simp] lemma update_inl_apply_inr {α β γ} [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inl i) x (inr j) = f (inr j) := function.update_noteq inr_ne_inl _ _ @[simp] lemma update_inr_comp_inl {α β γ} [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inl = f ∘ inl := update_comp_eq_of_forall_ne _ _ $ λ _, inl_ne_inr @[simp] lemma update_inr_apply_inl {α β γ} [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inr j) x (inl i) = f (inl i) := function.update_noteq inl_ne_inr _ _ @[simp] lemma update_inr_comp_inr {α β γ} [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inr = update (f ∘ inr) i x := update_comp_eq_of_injective _ inr_injective _ _ @[simp] lemma update_inr_apply_inr {α β γ} [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i j : β} {x : γ} : update f (inr i) x (inr j) = update (f ∘ inr) i x j := by rw ← update_inr_comp_inr section variables (ra : α → α → Prop) (rb : β → β → Prop) /-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`, otherwise use the respective order on `α` or `β`. -/ inductive lex : α ⊕ β → α ⊕ β → Prop | inl {a₁ a₂} (h : ra a₁ a₂) : lex (inl a₁) (inl a₂) | inr {b₁ b₂} (h : rb b₁ b₂) : lex (inr b₁) (inr b₂) | sep (a b) : lex (inl a) (inr b) variables {ra rb} @[simp] theorem lex_inl_inl {a₁ a₂} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ := ⟨λ h, by cases h; assumption, lex.inl⟩ @[simp] theorem lex_inr_inr {b₁ b₂} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ := ⟨λ h, by cases h; assumption, lex.inr⟩ @[simp] theorem lex_inr_inl {b a} : ¬ lex ra rb (inr b) (inl a) := λ h, by cases h attribute [simp] lex.sep theorem lex_acc_inl {a} (aca : acc ra a) : acc (lex ra rb) (inl a) := begin induction aca with a H IH, constructor, intros y h, cases h with a' _ h', exact IH _ h' end theorem lex_acc_inr (aca : ∀ a, acc (lex ra rb) (inl a)) {b} (acb : acc rb b) : acc (lex ra rb) (inr b) := begin induction acb with b H IH, constructor, intros y h, cases h with _ _ _ b' _ h' a, { exact IH _ h' }, { exact aca _ } end theorem lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) := have aca : ∀ a, acc (lex ra rb) (inl a), from λ a, lex_acc_inl (ha.apply a), ⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩ end /-- Swap the factors of a sum type -/ @[simp] def swap : α ⊕ β → β ⊕ α | (inl a) := inr a | (inr b) := inl b @[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x := by cases x; refl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) := funext $ swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap end sum namespace function open sum lemma injective.sum_elim {γ} {f : α → γ} {g : β → γ} (hf : injective f) (hg : injective g) (hfg : ∀ a b, f a ≠ g b) : injective (sum.elim f g) | (inl x) (inl y) h := congr_arg inl $ hf h | (inl x) (inr y) h := (hfg x y h).elim | (inr x) (inl y) h := (hfg y x h.symm).elim | (inr x) (inr y) h := congr_arg inr $ hg h lemma injective.sum_map {f : α → β} {g : α' → β'} (hf : injective f) (hg : injective g) : injective (sum.map f g) | (inl x) (inl y) h := congr_arg inl $ hf $ inl.inj h | (inr x) (inr y) h := congr_arg inr $ hg $ inr.inj h lemma surjective.sum_map {f : α → β} {g : α' → β'} (hf : surjective f) (hg : surjective g) : surjective (sum.map f g) | (inl y) := let ⟨x, hx⟩ := hf y in ⟨inl x, congr_arg inl hx⟩ | (inr y) := let ⟨x, hx⟩ := hg y in ⟨inr x, congr_arg inr hx⟩ end function
1befbf3b0ec0846cbebb1d46a52a857b91f2bddf
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/ring/divisibility.lean
21dcb248c7b1cc7ec1a019fbc94d7d56cac2408f
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
4,204
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland -/ import algebra.divisibility.basic import algebra.ring.defs /-! # Lemmas about divisibility in rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α β : Type*} section distrib_semigroup variables [has_add α] [semigroup α] theorem dvd_add [left_distrib_class α] {a b c : α} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) end distrib_semigroup @[simp] theorem two_dvd_bit0 [semiring α] {a : α} : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩ section non_unital_comm_semiring variables [non_unital_comm_semiring α] [non_unital_comm_semiring β] {a b c : α} lemma has_dvd.dvd.linear_comb {d x y : α} (hdx : d ∣ x) (hdy : d ∣ y) (a b : α) : d ∣ (a * x + b * y) := dvd_add (hdx.mul_left a) (hdy.mul_left b) end non_unital_comm_semiring section semigroup variables [semigroup α] [has_distrib_neg α] {a b c : α} theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := let ⟨c, hc⟩ := h in ⟨-c, by simp [hc]⟩ theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t /-- An element a of a semigroup with a distributive negation divides the negation of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := let ⟨c, hc⟩ := h in ⟨-c, by simp [hc]⟩ theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t /-- The negation of an element a of a semigroup with a distributive negation divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ end semigroup section non_unital_ring variables [non_unital_ring α] {a b c : α} theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := by { rw sub_eq_add_neg, exact dvd_add h₁ (dvd_neg_of_dvd h₂) } theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end non_unital_ring section ring variables [ring α] {a b c : α} theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) end ring section non_unital_comm_ring variables [non_unital_comm_ring α] {a b c : α} lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (hxy.mul_left a) (hab.mul_right y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end end non_unital_comm_ring
da3dc6ea17a28df955a9b446d67fa42661bb6815
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/module/projective.lean
0114317b3d8976c24b06cf2db650781c8c25b5a2
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,893
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import algebra.module.basic import linear_algebra.finsupp import linear_algebra.free_module /-! # Projective modules This file contains a definition of a projective module, the proof that our definition is equivalent to a lifting property, and the proof that all free modules are projective. ## Main definitions Let `R` be a ring (or a semiring) and let `M` be an `R`-module. * `is_projective R M` : the proposition saying that `M` is a projective `R`-module. ## Main theorems * `is_projective.lifting_property` : a map from a projective module can be lifted along a surjection. * `is_projective.of_lifting_property` : If for all R-module surjections `A →ₗ B`, all maps `M →ₗ B` lift to `M →ₗ A`, then `M` is projective. * `is_projective.of_free` : Free modules are projective ## Implementation notes The actual definition of projective we use is that the natural R-module map from the free R-module on the type M down to M splits. This is more convenient than certain other definitions which involve quantifying over universes, and also universe-polymorphic (the ring and module can be in different universes). We require that the module sits in at least as high a universe as the ring: without this, free modules don't even exist, and it's unclear if projective modules are even a useful notion. ## References https://en.wikipedia.org/wiki/Projective_module ## TODO - Direct sum of two projective modules is projective. - Arbitrary sum of projective modules is projective. - Any module admits a surjection from a projective module. All of these should be relatively straightforward. ## Tags projective module -/ universes u v /- The actual implementation we choose: `P` is projective if the natural surjection from the free `R`-module on `P` to `P` splits. -/ /-- An R-module is projective if it is a direct summand of a free module, or equivalently if maps from the module lift along surjections. There are several other equivalent definitions. -/ class module.projective (R : Type u) [semiring R] (P : Type (max u v)) [add_comm_monoid P] [module R P] : Prop := (out : ∃ s : P →ₗ[R] (P →₀ R), function.left_inverse (finsupp.total P P R id) s) namespace module lemma projective_def {R : Type u} [semiring R] {P : Type (max u v)} [add_comm_monoid P] [module R P] : projective R P ↔ (∃ s : P →ₗ[R] (P →₀ R), function.left_inverse (finsupp.total P P R id) s) := ⟨λ h, h.1, λ h, ⟨h⟩⟩ section semiring variables {R : Type u} [semiring R] {P : Type (max u v)} [add_comm_monoid P] [module R P] {M : Type (max u v)} [add_comm_group M] [module R M] {N : Type*} [add_comm_group N] [module R N] /-- A projective R-module has the property that maps from it lift along surjections. -/ theorem projective_lifting_property [h : projective R P] (f : M →ₗ[R] N) (g : P →ₗ[R] N) (hf : function.surjective f) : ∃ (h : P →ₗ[R] M), f.comp h = g := begin /- Here's the first step of the proof. Recall that `X →₀ R` is Lean's way of talking about the free `R`-module on a type `X`. The universal property `finsupp.total` says that to a map `X → N` from a type to an `R`-module, we get an associated R-module map `(X →₀ R) →ₗ N`. Apply this to a (noncomputable) map `P → M` coming from the map `P →ₗ N` and a random splitting of the surjection `M →ₗ N`, and we get a map `φ : (P →₀ R) →ₗ M`. -/ let φ : (P →₀ R) →ₗ[R] M := finsupp.total _ _ _ (λ p, function.surj_inv hf (g p)), -- By projectivity we have a map `P →ₗ (P →₀ R)`; cases h.out with s hs, -- Compose to get `P →ₗ M`. This works. use φ.comp s, ext p, conv_rhs {rw ← hs p}, simp [φ, finsupp.total_apply, function.surj_inv_eq hf], end /-- A module which satisfies the universal property is projective. Note that the universe variables in `huniv` are somewhat restricted. -/ theorem projective_of_lifting_property' -- If for all surjections of `R`-modules `M →ₗ N`, all maps `P →ₗ N` lift to `P →ₗ M`, (huniv : ∀ {M : Type (max v u)} {N : Type (max u v)} [add_comm_monoid M] [add_comm_monoid N], by exactI ∀ [module R M] [module R N], by exactI ∀ (f : M →ₗ[R] N) (g : P →ₗ[R] N), function.surjective f → ∃ (h : P →ₗ[R] M), f.comp h = g) : -- then `P` is projective. projective R P := begin -- let `s` be the universal map `(P →₀ R) →ₗ P` coming from the identity map `P →ₗ P`. obtain ⟨s, hs⟩ : ∃ (s : P →ₗ[R] P →₀ R), (finsupp.total P P R id).comp s = linear_map.id := huniv (finsupp.total P P R (id : P → P)) (linear_map.id : P →ₗ[R] P) _, -- This `s` works. { use s, rwa linear_map.ext_iff at hs }, { intro p, use finsupp.single p 1, simp }, end end semiring section ring variables {R : Type u} [ring R] {P : Type (max u v)} [add_comm_group P] [module R P] /-- A variant of `of_lifting_property'` when we're working over a `[ring R]`, which only requires quantifying over modules with an `add_comm_group` instance. -/ theorem projective_of_lifting_property -- If for all surjections of `R`-modules `M →ₗ N`, all maps `P →ₗ N` lift to `P →ₗ M`, (huniv : ∀ {M : Type (max v u)} {N : Type (max u v)} [add_comm_group M] [add_comm_group N], by exactI ∀ [module R M] [module R N], by exactI ∀ (f : M →ₗ[R] N) (g : P →ₗ[R] N), function.surjective f → ∃ (h : P →ₗ[R] M), f.comp h = g) : -- then `P` is projective. projective R P := -- We could try and prove this *using* `of_lifting_property`, -- but this quickly leads to typeclass hell, -- so we just prove it over again. begin -- let `s` be the universal map `(P →₀ R) →ₗ P` coming from the identity map `P →ₗ P`. obtain ⟨s, hs⟩ : ∃ (s : P →ₗ[R] P →₀ R), (finsupp.total P P R id).comp s = linear_map.id := huniv (finsupp.total P P R (id : P → P)) (linear_map.id : P →ₗ[R] P) _, -- This `s` works. { use s, rwa linear_map.ext_iff at hs }, { intro p, use finsupp.single p 1, simp }, end /-- Free modules are projective. -/ theorem projective_of_basis {ι : Type*} (b : basis ι R P) : projective R P := begin -- need P →ₗ (P →₀ R) for definition of projective. -- get it from `ι → (P →₀ R)` coming from `b`. use b.constr ℕ (λ i, finsupp.single (b i) (1 : R)), intro m, simp only [b.constr_apply, mul_one, id.def, finsupp.smul_single', finsupp.total_single, linear_map.map_finsupp_sum], exact b.total_repr m, end @[priority 100] instance projective_of_free [module.free R P] : module.projective R P := projective_of_basis $ module.free.choose_basis R P end ring end module
aabaafc50c7a36ae32115d2b1433f7b971e225c8
359199d7253811b032ab92108191da7336eba86e
/src/instructor/lectures/lecture_4.lean
b7681ef1afea1c51466cd7bb466a81a0ac59ed5b
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
3,995
lean
/- We've seen that logics start with axioms that can then be combined (with other information) using *inference rules* to derive theorems. In this file we review what we've covered so far and then we introduce: (1) The concept of introduction and elimination rules for a given logical construct. (2) We distinguish the reflexivity axiom as an *introduction* rule (one that produces a proof of an equality), and the substitutability of equals as an *elimination* rule (one that uses, or consumes) a proof of an equality to produce some other kind of result. (3) We explicitly identity the introduction rules for ∀ and for →. To produce a proof of ∀ (x : T), P x (where T is a type and P is a predicate that asserts some property of x), we *assume* that we're given an arbitrary but specific (x : T) ["x of type T"], and then we prove (P x) *for that x*. Because we made no assumptions whatsoever about x, if we can show that (P x) is true, then it must be true *for all* (x : T). -/ /- Introduction rule for equality. -/ axiom eq_refl : ∀ (T : Type) -- if T is any type (of thing) (t : T), -- and t is thing of that type, T t = t -- the result type: proof of t = t /- Elimination rule for equality. -/ axiom eq_subst : ∀ (T : Type) -- if T is a type (P : T → Prop) -- and P is a property of T objects (x y : T) -- and x and y are T objects (e : x = y) -- and you have a proof that x = y (you can tell it's an elimination rule bc a proof is taken as an arg.) (px : P x), -- and you have a proof that x has property P P y -- then you can deduce (and get a proof) of P y /- The Lean versions of these axioms are called eq.refl and eq.subst. They're defined in ways that allow (and require) one not to give the T, P, x, or y parameters explicitly when applying eq_subst. More details come later. -/ /- CONJECTURES (review) -/ -- A conjecture: equality is symmetric. def eq_symm : Prop := ∀ (T : Type) (x y : T), x = y → y = x -- A conjecture: equality is transitive. def eq_trans : Prop := ∀ (T : Type) (x y z : T), x = y → y = z → x = z /- PROOFS: From conjectures to theorems -/ example : eq_symm := begin unfold eq_symm, -- replace name with definition assume T x y e, -- Introduction rule for ∀ rw e, -- Elimination rule for = -- QED. end /- A different proof, now using eq.subst explicitly. Any proof of a proposition is as good as any other for showing the truth of a proposition. We do not care what proofs you give, as long as they're correct (unless stated otherwise). -/ example : eq_symm := begin unfold eq_symm, -- replace name with definition assume T x y e, -- introduction rule for ∀ apply eq.subst e, -- elimination rule for = exact eq.refl x, -- introduction rule for = -- QED. end /- Review: Proof: equality is transitive. -/ example : eq_trans := begin unfold eq_trans, assume T x y z e1 e2, -- introduction rule for ∀ rw e1, -- elimination rule for = exact e2, end /- Note: Lean defines these rules as - eq.refl - eq.subst - eq.symm - eq.trans -/ /- Practice -/ /-top level logical construct: it's a for-all prop./statement, for all types T something, (1) assume I'm given some type T, assume I'm given objects of T, show yada yada, below is not quite a transitivity prop.-/ example : ∀ (T : Type) (x y z : T), x = y → y = z → z = x := begin assume T x y z h1 h2, -- introduction rule for ∀ apply eq.symm _, -- application of symm *theorem* apply eq.trans h1 h2, -- application of trans theorem end /- INTRODUCTION and ELIMINATION RULES -/ /- For = - introduction rule: eq.refl - elimination rule: eq.subst -/ /- For ∀ x, P x - introduction rule: assume arbitrary x, then show P x - elimination rule: next time! -/ /- For P → Q - introduction rule: assume arbitrary P, then show Q - elimination rule: next time. -/
36956ffe490c6ea85f759cc884753d7b01c1f31d
bb31430994044506fa42fd667e2d556327e18dfe
/src/combinatorics/simple_graph/basic.lean
2434050c024213d1cb056322000d0bd52709dc42
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
55,303
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov, Hunter Monroe -/ import data.rel import data.set.finite import data.sym.sym2 /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `simple_graph.neighbor_set` is the `set` of vertices adjacent to a given vertex * `simple_graph.common_neighbors` is the intersection of the neighbor sets of two given vertices * `simple_graph.neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite * `simple_graph.incidence_set` is the `set` of edges containing a given vertex * `simple_graph.incidence_finset` is the `finset` of edges containing a given vertex, if `incidence_set` is finite * `simple_graph.dart` is an ordered pair of adjacent vertices, thought of as being an orientated edge. These are also known as "half-edges" or "bonds." * `simple_graph.hom`, `simple_graph.embedding`, and `simple_graph.iso` for graph homomorphisms, graph embeddings, and graph isomorphisms. Note that a graph embedding is a stronger notion than an injective graph homomorphism, since its image is an induced subgraph. * `boolean_algebra` instance: Under the subgraph relation, `simple_graph` forms a `boolean_algebra`. In other words, this is the lattice of spanning subgraphs of the complete graph. ## Notations * `→g`, `↪g`, and `≃g` for graph homomorphisms, graph embeddings, and graph isomorphisms, respectively. ## Implementation notes * A locally finite graph is one with instances `Π v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. * Morphisms of graphs are abbreviations for `rel_hom`, `rel_embedding`, and `rel_iso`. To make use of pre-existing simp lemmas, definitions involving morphisms are abbreviations as well. ## Naming Conventions * If the vertex type of a graph is finite, we refer to its cardinality as `card_verts`. ## Todo * Upgrade `simple_graph.boolean_algebra` to a `complete_boolean_algebra`. * This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. -/ open finset function universes u v w /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent vertices; see `simple_graph.edge_set` for the corresponding edge set. -/ @[ext] structure simple_graph (V : Type u) := (adj : V → V → Prop) (symm : symmetric adj . obviously) (loopless : irreflexive adj . obviously) noncomputable instance {V : Type u} [fintype V] : fintype (simple_graph V) := by { classical, exact fintype.of_injective simple_graph.adj simple_graph.ext } /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V := { adj := λ a b, (a ≠ b) ∧ (r a b ∨ r b a), symm := λ a b ⟨hn, hr⟩, ⟨hn.symm, hr.symm⟩, loopless := λ a ⟨hn, _⟩, hn rfl } @[simp] lemma simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v w : V) : (simple_graph.from_rel r).adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) := iff.rfl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. In `mathlib`, this is usually referred to as `⊤`. -/ def complete_graph (V : Type u) : simple_graph V := { adj := ne } /-- The graph with no edges on a given vertex type `V`. `mathlib` prefers the notation `⊥`. -/ def empty_graph (V : Type u) : simple_graph V := { adj := λ i j, false } /-- Two vertices are adjacent in the complete bipartite graph on two vertex types if and only if they are not from the same side. Bipartite graphs in general may be regarded as being subgraphs of one of these. TODO also introduce complete multi-partite graphs, where the vertex type is a sigma type of an indexed family of vertex types -/ @[simps] def complete_bipartite_graph (V W : Type*) : simple_graph (V ⊕ W) := { adj := λ v w, (v.is_left ∧ w.is_right) ∨ (v.is_right ∧ w.is_left), symm := begin intros v w, cases v; cases w; simp, end, loopless := begin intro v, cases v; simp, end } namespace simple_graph variables {𝕜 : Type*} {V : Type u} {W : Type v} {X : Type w} (G : simple_graph V) (G' : simple_graph W) {a b c u v w : V} {e : sym2 V} @[simp] protected lemma irrefl {v : V} : ¬G.adj v v := G.loopless v lemma adj_comm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.symm x, λ x, G.symm x⟩ @[symm] lemma adj_symm (h : G.adj u v) : G.adj v u := G.symm h lemma adj.symm {G : simple_graph V} {u v : V} (h : G.adj u v) : G.adj v u := G.symm h lemma ne_of_adj (h : G.adj a b) : a ≠ b := by { rintro rfl, exact G.irrefl h } protected lemma adj.ne {G : simple_graph V} {a b : V} (h : G.adj a b) : a ≠ b := G.ne_of_adj h protected lemma adj.ne' {G : simple_graph V} {a b : V} (h : G.adj a b) : b ≠ a := h.ne.symm lemma ne_of_adj_of_not_adj {v w x : V} (h : G.adj v x) (hn : ¬ G.adj w x) : v ≠ w := λ h', hn (h' ▸ h) section order /-- The relation that one `simple_graph` is a subgraph of another. Note that this should be spelled `≤`. -/ def is_subgraph (x y : simple_graph V) : Prop := ∀ ⦃v w : V⦄, x.adj v w → y.adj v w instance : has_le (simple_graph V) := ⟨is_subgraph⟩ @[simp] lemma is_subgraph_eq_le : (is_subgraph : simple_graph V → simple_graph V → Prop) = (≤) := rfl /-- The supremum of two graphs `x ⊔ y` has edges where either `x` or `y` have edges. -/ instance : has_sup (simple_graph V) := ⟨λ x y, { adj := x.adj ⊔ y.adj, symm := λ v w h, by rwa [pi.sup_apply, pi.sup_apply, x.adj_comm, y.adj_comm] }⟩ @[simp] lemma sup_adj (x y : simple_graph V) (v w : V) : (x ⊔ y).adj v w ↔ x.adj v w ∨ y.adj v w := iff.rfl /-- The infimum of two graphs `x ⊓ y` has edges where both `x` and `y` have edges. -/ instance : has_inf (simple_graph V) := ⟨λ x y, { adj := x.adj ⊓ y.adj, symm := λ v w h, by rwa [pi.inf_apply, pi.inf_apply, x.adj_comm, y.adj_comm] }⟩ @[simp] lemma inf_adj (x y : simple_graph V) (v w : V) : (x ⊓ y).adj v w ↔ x.adj v w ∧ y.adj v w := iff.rfl /-- We define `Gᶜ` to be the `simple_graph V` such that no two adjacent vertices in `G` are adjacent in the complement, and every nonadjacent pair of vertices is adjacent (still ensuring that vertices are not adjacent to themselves). -/ instance : has_compl (simple_graph V) := ⟨λ G, { adj := λ v w, v ≠ w ∧ ¬G.adj v w, symm := λ v w ⟨hne, _⟩, ⟨hne.symm, by rwa adj_comm⟩, loopless := λ v ⟨hne, _⟩, (hne rfl).elim }⟩ @[simp] lemma compl_adj (G : simple_graph V) (v w : V) : Gᶜ.adj v w ↔ v ≠ w ∧ ¬G.adj v w := iff.rfl /-- The difference of two graphs `x \ y` has the edges of `x` with the edges of `y` removed. -/ instance : has_sdiff (simple_graph V) := ⟨λ x y, { adj := x.adj \ y.adj, symm := λ v w h, by change x.adj w v ∧ ¬ y.adj w v; rwa [x.adj_comm, y.adj_comm] }⟩ @[simp] lemma sdiff_adj (x y : simple_graph V) (v w : V) : (x \ y).adj v w ↔ (x.adj v w ∧ ¬ y.adj v w) := iff.rfl instance : boolean_algebra (simple_graph V) := { le := (≤), sup := (⊔), inf := (⊓), compl := has_compl.compl, sdiff := (\), top := complete_graph V, bot := empty_graph V, le_top := λ x v w h, x.ne_of_adj h, bot_le := λ x v w h, h.elim, sup_le := λ x y z hxy hyz v w h, h.cases_on (λ h, hxy h) (λ h, hyz h), sdiff_eq := λ x y, by { ext v w, refine ⟨λ h, ⟨h.1, ⟨_, h.2⟩⟩, λ h, ⟨h.1, h.2.2⟩⟩, rintro rfl, exact x.irrefl h.1 }, le_sup_left := λ x y v w h, or.inl h, le_sup_right := λ x y v w h, or.inr h, le_inf := λ x y z hxy hyz v w h, ⟨hxy h, hyz h⟩, le_sup_inf := λ a b c v w h, or.dcases_on h.2 or.inl $ or.dcases_on h.1 (λ h _, or.inl h) $ λ hb hc, or.inr ⟨hb, hc⟩, inf_compl_le_bot := λ a v w h, false.elim $ h.2.2 h.1, top_le_sup_compl := λ a v w ne, by { by_cases a.adj v w, exact or.inl h, exact or.inr ⟨ne, h⟩ }, inf_le_left := λ x y v w h, h.1, inf_le_right := λ x y v w h, h.2, .. partial_order.lift adj ext } @[simp] lemma top_adj (v w : V) : (⊤ : simple_graph V).adj v w ↔ v ≠ w := iff.rfl @[simp] lemma bot_adj (v w : V) : (⊥ : simple_graph V).adj v w ↔ false := iff.rfl @[simp] lemma complete_graph_eq_top (V : Type u) : complete_graph V = ⊤ := rfl @[simp] lemma empty_graph_eq_bot (V : Type u) : empty_graph V = ⊥ := rfl @[simps] instance (V : Type u) : inhabited (simple_graph V) := ⟨⊥⟩ section decidable variables (V) (H : simple_graph V) [decidable_rel G.adj] [decidable_rel H.adj] instance bot.adj_decidable : decidable_rel (⊥ : simple_graph V).adj := λ v w, decidable.false instance sup.adj_decidable : decidable_rel (G ⊔ H).adj := λ v w, or.decidable instance inf.adj_decidable : decidable_rel (G ⊓ H).adj := λ v w, and.decidable instance sdiff.adj_decidable : decidable_rel (G \ H).adj := λ v w, and.decidable variable [decidable_eq V] instance top.adj_decidable : decidable_rel (⊤ : simple_graph V).adj := λ v w, not.decidable instance compl.adj_decidable : decidable_rel Gᶜ.adj := λ v w, and.decidable end decidable end order /-- `G.support` is the set of vertices that form edges in `G`. -/ def support : set V := rel.dom G.adj lemma mem_support {v : V} : v ∈ G.support ↔ ∃ w, G.adj v w := iff.rfl lemma support_mono {G G' : simple_graph V} (h : G ≤ G') : G.support ⊆ G'.support := rel.dom_mono h /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set (v : V) : set V := set_of (G.adj v) instance neighbor_set.mem_decidable (v : V) [decidable_rel G.adj] : decidable_pred (∈ G.neighbor_set v) := by { unfold neighbor_set, apply_instance } section edge_set variables {G₁ G₂ : simple_graph V} /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. The way `edge_set` is defined is such that `mem_edge_set` is proved by `refl`. (That is, `⟦(v, w)⟧ ∈ G.edge_set` is definitionally equal to `G.adj v w`.) -/ def edge_set : simple_graph V ↪o set (sym2 V) := order_embedding.of_map_le_iff (λ G, sym2.from_rel G.symm) $ λ G G', ⟨λ h a b, @h ⟦(a, b)⟧, λ h e, sym2.ind @h e⟩ @[simp] lemma mem_edge_set : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w := iff.rfl lemma not_is_diag_of_mem_edge_set : e ∈ G.edge_set → ¬ e.is_diag := sym2.ind (λ v w, adj.ne) e @[simp] lemma edge_set_inj : G₁.edge_set = G₂.edge_set ↔ G₁ = G₂ := (edge_set : simple_graph V ↪o set (sym2 V)).eq_iff_eq @[simp] lemma edge_set_subset_edge_set : G₁.edge_set ⊆ G₂.edge_set ↔ G₁ ≤ G₂ := (edge_set : simple_graph V ↪o set (sym2 V)).le_iff_le @[simp] lemma edge_set_ssubset_edge_set : G₁.edge_set ⊂ G₂.edge_set ↔ G₁ < G₂ := (edge_set : simple_graph V ↪o set (sym2 V)).lt_iff_lt lemma edge_set_injective : injective (edge_set : simple_graph V → set (sym2 V)) := edge_set.injective alias edge_set_subset_edge_set ↔ _ edge_set_mono alias edge_set_ssubset_edge_set ↔ _ edge_set_strict_mono attribute [mono] edge_set_mono edge_set_strict_mono variables (G₁ G₂) @[simp] lemma edge_set_bot : (⊥ : simple_graph V).edge_set = ∅ := sym2.from_rel_bot @[simp] lemma edge_set_sup : (G₁ ⊔ G₂).edge_set = G₁.edge_set ∪ G₂.edge_set := by { ext ⟨x, y⟩, refl } @[simp] lemma edge_set_inf : (G₁ ⊓ G₂).edge_set = G₁.edge_set ∩ G₂.edge_set := by { ext ⟨x, y⟩, refl } @[simp] lemma edge_set_sdiff : (G₁ \ G₂).edge_set = G₁.edge_set \ G₂.edge_set := by { ext ⟨x, y⟩, refl } /-- This lemma, combined with `edge_set_sdiff` and `edge_set_from_edge_set`, allows proving `(G \ from_edge_set s).edge_set = G.edge_set \ s` by `simp`. -/ @[simp] lemma edge_set_sdiff_sdiff_is_diag (G : simple_graph V) (s : set (sym2 V)) : G.edge_set \ (s \ {e | e.is_diag}) = G.edge_set \ s := begin ext e, simp only [set.mem_diff, set.mem_set_of_eq, not_and, not_not, and.congr_right_iff], intro h, simp only [G.not_is_diag_of_mem_edge_set h, imp_false], end /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ lemma adj_iff_exists_edge {v w : V} : G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e := begin refine ⟨λ _, ⟨G.ne_of_adj ‹_›, ⟦(v,w)⟧, _⟩, _⟩, { simpa }, { rintro ⟨hne, e, he, hv⟩, rw sym2.mem_and_mem_iff hne at hv, subst e, rwa mem_edge_set at he } end lemma adj_iff_exists_edge_coe : G.adj a b ↔ ∃ (e : G.edge_set), ↑e = ⟦(a, b)⟧ := by simp only [mem_edge_set, exists_prop, set_coe.exists, exists_eq_right, subtype.coe_mk] lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v := begin erw [← sym2.other_spec h, sym2.eq_swap] at he, exact G.ne_of_adj he, end instance decidable_mem_edge_set [decidable_rel G.adj] : decidable_pred (∈ G.edge_set) := sym2.from_rel.decidable_pred _ instance fintype_edge_set [decidable_eq V] [fintype V] [decidable_rel G.adj] : fintype G.edge_set := subtype.fintype _ instance fintype_edge_set_bot : fintype (⊥ : simple_graph V).edge_set := by { rw edge_set_bot, apply_instance } instance fintype_edge_set_sup [decidable_eq V] [fintype G₁.edge_set] [fintype G₂.edge_set] : fintype (G₁ ⊔ G₂).edge_set := by { rw edge_set_sup, apply_instance } instance fintype_edge_set_inf [decidable_eq V] [fintype G₁.edge_set] [fintype G₂.edge_set] : fintype (G₁ ⊓ G₂).edge_set := by { rw edge_set_inf, exact set.fintype_inter _ _ } instance fintype_edge_set_sdiff [decidable_eq V] [fintype G₁.edge_set] [fintype G₂.edge_set] : fintype (G₁ \ G₂).edge_set := by { rw edge_set_sdiff, exact set.fintype_diff _ _ } end edge_set section from_edge_set variable (s : set (sym2 V)) /-- `from_edge_set` constructs a `simple_graph` from a set of edges, without loops. -/ def from_edge_set : simple_graph V := { adj := sym2.to_rel s ⊓ ne, symm := λ v w h, ⟨sym2.to_rel_symmetric s h.1, h.2.symm⟩} @[simp] lemma from_edge_set_adj : (from_edge_set s).adj v w ↔ ⟦(v, w)⟧ ∈ s ∧ v ≠ w := iff.rfl -- Note: we need to make sure `from_edge_set_adj` and this lemma are confluent. -- In particular, both yield `⟦(u, v)⟧ ∈ (from_edge_set s).edge_set` ==> `⟦(v, w)⟧ ∈ s ∧ v ≠ w`. @[simp] lemma edge_set_from_edge_set : (from_edge_set s).edge_set = s \ {e | e.is_diag} := by { ext e, exact sym2.ind (by simp) e } @[simp] lemma from_edge_set_edge_set : from_edge_set G.edge_set = G := by { ext v w, exact ⟨λ h, h.1, λ h, ⟨h, G.ne_of_adj h⟩⟩ } @[simp] lemma from_edge_set_empty : from_edge_set (∅ : set (sym2 V)) = ⊥ := by { ext v w, simp only [from_edge_set_adj, set.mem_empty_iff_false, false_and, bot_adj] } @[simp] lemma from_edge_set_univ : from_edge_set (set.univ : set (sym2 V)) = ⊤ := by { ext v w, simp only [from_edge_set_adj, set.mem_univ, true_and, top_adj] } @[simp] lemma from_edge_set_inf (s t : set (sym2 V)) : from_edge_set s ⊓ from_edge_set t = from_edge_set (s ∩ t) := by { ext v w, simp only [from_edge_set_adj, set.mem_inter_iff, ne.def, inf_adj], tauto, } @[simp] lemma from_edge_set_sup (s t : set (sym2 V)) : from_edge_set s ⊔ from_edge_set t = from_edge_set (s ∪ t) := by { ext v w, simp [set.mem_union, or_and_distrib_right], } @[simp] lemma from_edge_set_sdiff (s t : set (sym2 V)) : from_edge_set s \ from_edge_set t = from_edge_set (s \ t) := by { ext v w, split; simp { contextual := tt }, } @[mono] lemma from_edge_set_mono {s t : set (sym2 V)} (h : s ⊆ t) : from_edge_set s ≤ from_edge_set t := begin rintro v w, simp only [from_edge_set_adj, ne.def, not_false_iff, and_true, and_imp] {contextual := tt}, exact λ vws _, h vws, end instance [decidable_eq V] [fintype s] : fintype (from_edge_set s).edge_set := by { rw edge_set_from_edge_set s, apply_instance } end from_edge_set /-! ## Darts -/ /-- A `dart` is an oriented edge, implemented as an ordered pair of adjacent vertices. This terminology comes from combinatorial maps, and they are also known as "half-edges" or "bonds." -/ @[ext, derive decidable_eq] structure dart extends V × V := (is_adj : G.adj fst snd) section darts variables {G} /-- The first vertex for the dart. -/ abbreviation dart.fst (d : G.dart) : V := d.fst /-- The second vertex for the dart. -/ abbreviation dart.snd (d : G.dart) : V := d.snd lemma dart.to_prod_injective : function.injective (dart.to_prod : G.dart → V × V) := dart.ext instance dart.fintype [fintype V] [decidable_rel G.adj] : fintype G.dart := fintype.of_equiv (Σ v, G.neighbor_set v) { to_fun := λ s, ⟨(s.fst, s.snd), s.snd.property⟩, inv_fun := λ d, ⟨d.fst, d.snd, d.is_adj⟩, left_inv := λ s, by ext; simp, right_inv := λ d, by ext; simp } /-- The edge associated to the dart. -/ def dart.edge (d : G.dart) : sym2 V := ⟦d.to_prod⟧ @[simp] lemma dart.edge_mk {p : V × V} (h : G.adj p.1 p.2) : (dart.mk p h).edge = ⟦p⟧ := rfl @[simp] lemma dart.edge_mem (d : G.dart) : d.edge ∈ G.edge_set := d.is_adj /-- The dart with reversed orientation from a given dart. -/ @[simps] def dart.symm (d : G.dart) : G.dart := ⟨d.to_prod.swap, G.symm d.is_adj⟩ @[simp] lemma dart.symm_mk {p : V × V} (h : G.adj p.1 p.2) : (dart.mk p h).symm = dart.mk p.swap h.symm := rfl @[simp] lemma dart.edge_symm (d : G.dart) : d.symm.edge = d.edge := sym2.mk_prod_swap_eq @[simp] lemma dart.edge_comp_symm : dart.edge ∘ dart.symm = (dart.edge : G.dart → sym2 V) := funext dart.edge_symm @[simp] lemma dart.symm_symm (d : G.dart) : d.symm.symm = d := dart.ext _ _ $ prod.swap_swap _ @[simp] lemma dart.symm_involutive : function.involutive (dart.symm : G.dart → G.dart) := dart.symm_symm lemma dart.symm_ne (d : G.dart) : d.symm ≠ d := ne_of_apply_ne (prod.snd ∘ dart.to_prod) d.is_adj.ne lemma dart_edge_eq_iff : Π (d₁ d₂ : G.dart), d₁.edge = d₂.edge ↔ d₁ = d₂ ∨ d₁ = d₂.symm := by { rintros ⟨p, hp⟩ ⟨q, hq⟩, simp [sym2.mk_eq_mk_iff] } lemma dart_edge_eq_mk_iff : Π {d : G.dart} {p : V × V}, d.edge = ⟦p⟧ ↔ d.to_prod = p ∨ d.to_prod = p.swap := by { rintro ⟨p, h⟩, apply sym2.mk_eq_mk_iff } lemma dart_edge_eq_mk_iff' : Π {d : G.dart} {u v : V}, d.edge = ⟦(u, v)⟧ ↔ d.fst = u ∧ d.snd = v ∨ d.fst = v ∧ d.snd = u := by { rintro ⟨⟨a, b⟩, h⟩ u v, rw dart_edge_eq_mk_iff, simp } variables (G) /-- Two darts are said to be adjacent if they could be consecutive darts in a walk -- that is, the first dart's second vertex is equal to the second dart's first vertex. -/ def dart_adj (d d' : G.dart) : Prop := d.snd = d'.fst /-- For a given vertex `v`, this is the bijective map from the neighbor set at `v` to the darts `d` with `d.fst = v`. -/ @[simps] def dart_of_neighbor_set (v : V) (w : G.neighbor_set v) : G.dart := ⟨(v, w), w.property⟩ lemma dart_of_neighbor_set_injective (v : V) : function.injective (G.dart_of_neighbor_set v) := λ e₁ e₂ h, subtype.ext $ by { injection h with h', convert congr_arg prod.snd h' } instance nonempty_dart_top [nontrivial V] : nonempty (⊤ : simple_graph V).dart := by { obtain ⟨v, w, h⟩ := exists_pair_ne V, exact ⟨⟨(v, w), h⟩⟩ } end darts /-! ### Incidence set -/ /-- Set of edges incident to a given vertex, aka incidence set. -/ def incidence_set (v : V) : set (sym2 V) := {e ∈ G.edge_set | v ∈ e} lemma incidence_set_subset (v : V) : G.incidence_set v ⊆ G.edge_set := λ _ h, h.1 lemma mk_mem_incidence_set_iff : ⟦(b, c)⟧ ∈ G.incidence_set a ↔ G.adj b c ∧ (a = b ∨ a = c) := and_congr_right' sym2.mem_iff lemma mk_mem_incidence_set_left_iff : ⟦(a, b)⟧ ∈ G.incidence_set a ↔ G.adj a b := and_iff_left $ sym2.mem_mk_left _ _ lemma mk_mem_incidence_set_right_iff : ⟦(a, b)⟧ ∈ G.incidence_set b ↔ G.adj a b := and_iff_left $ sym2.mem_mk_right _ _ lemma edge_mem_incidence_set_iff {e : G.edge_set} : ↑e ∈ G.incidence_set a ↔ a ∈ (e : sym2 V) := and_iff_right e.2 lemma incidence_set_inter_incidence_set_subset (h : a ≠ b) : G.incidence_set a ∩ G.incidence_set b ⊆ {⟦(a, b)⟧} := λ e he, (sym2.mem_and_mem_iff h).1 ⟨he.1.2, he.2.2⟩ lemma incidence_set_inter_incidence_set_of_adj (h : G.adj a b) : G.incidence_set a ∩ G.incidence_set b = {⟦(a, b)⟧} := begin refine (G.incidence_set_inter_incidence_set_subset $ h.ne).antisymm _, rintro _ (rfl : _ = ⟦(a, b)⟧), exact ⟨G.mk_mem_incidence_set_left_iff.2 h, G.mk_mem_incidence_set_right_iff.2 h⟩, end lemma adj_of_mem_incidence_set (h : a ≠ b) (ha : e ∈ G.incidence_set a) (hb : e ∈ G.incidence_set b) : G.adj a b := by rwa [←mk_mem_incidence_set_left_iff, ←set.mem_singleton_iff.1 $ G.incidence_set_inter_incidence_set_subset h ⟨ha, hb⟩] lemma incidence_set_inter_incidence_set_of_not_adj (h : ¬ G.adj a b) (hn : a ≠ b) : G.incidence_set a ∩ G.incidence_set b = ∅ := begin simp_rw [set.eq_empty_iff_forall_not_mem, set.mem_inter_iff, not_and], intros u ha hb, exact h (G.adj_of_mem_incidence_set hn ha hb), end instance decidable_mem_incidence_set [decidable_eq V] [decidable_rel G.adj] (v : V) : decidable_pred (∈ G.incidence_set v) := λ e, and.decidable section edge_finset variables {G₁ G₂ : simple_graph V} [fintype G.edge_set] [fintype G₁.edge_set] [fintype G₂.edge_set] /-- The `edge_set` of the graph as a `finset`. -/ @[reducible] def edge_finset : finset (sym2 V) := set.to_finset G.edge_set @[simp, norm_cast] lemma coe_edge_finset : (G.edge_finset : set (sym2 V)) = G.edge_set := set.coe_to_finset _ variables {G} @[simp] lemma mem_edge_finset : e ∈ G.edge_finset ↔ e ∈ G.edge_set := set.mem_to_finset lemma not_is_diag_of_mem_edge_finset : e ∈ G.edge_finset → ¬ e.is_diag := not_is_diag_of_mem_edge_set _ ∘ mem_edge_finset.1 @[simp] lemma edge_finset_inj : G₁.edge_finset = G₂.edge_finset ↔ G₁ = G₂ := by simp [edge_finset] @[simp] lemma edge_finset_subset_edge_finset : G₁.edge_finset ⊆ G₂.edge_finset ↔ G₁ ≤ G₂ := by simp [edge_finset] @[simp] lemma edge_finset_ssubset_edge_finset : G₁.edge_finset ⊂ G₂.edge_finset ↔ G₁ < G₂ := by simp [edge_finset] alias edge_finset_subset_edge_finset ↔ _ edge_finset_mono alias edge_finset_ssubset_edge_finset ↔ _ edge_finset_strict_mono attribute [mono] edge_finset_mono edge_finset_strict_mono @[simp] lemma edge_finset_bot : (⊥ : simple_graph V).edge_finset = ∅ := by simp [edge_finset] @[simp] lemma edge_finset_sup : (G₁ ⊔ G₂).edge_finset = G₁.edge_finset ∪ G₂.edge_finset := by simp [edge_finset] @[simp] lemma edge_finset_inf : (G₁ ⊓ G₂).edge_finset = G₁.edge_finset ∩ G₂.edge_finset := by simp [edge_finset] @[simp] lemma edge_finset_sdiff : (G₁ \ G₂).edge_finset = G₁.edge_finset \ G₂.edge_finset := by simp [edge_finset] lemma edge_finset_card : G.edge_finset.card = fintype.card G.edge_set := set.to_finset_card _ @[simp] lemma edge_set_univ_card : (univ : finset G.edge_set).card = G.edge_finset.card := fintype.card_of_subtype G.edge_finset $ λ _, mem_edge_finset end edge_finset @[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := iff.rfl @[simp] lemma mem_incidence_set (v w : V) : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ G.adj v w := by simp [incidence_set] lemma mem_incidence_iff_neighbor {v w : V} : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ w ∈ G.neighbor_set v := by simp only [mem_incidence_set, mem_neighbor_set] lemma adj_incidence_set_inter {v : V} {e : sym2 V} (he : e ∈ G.edge_set) (h : v ∈ e) : G.incidence_set v ∩ G.incidence_set h.other = {e} := begin ext e', simp only [incidence_set, set.mem_sep_iff, set.mem_inter_iff, set.mem_singleton_iff], refine ⟨λ h', _, _⟩, { rw ←sym2.other_spec h, exact (sym2.mem_and_mem_iff (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩ }, { rintro rfl, exact ⟨⟨he, h⟩, he, sym2.other_mem _⟩ } end lemma compl_neighbor_set_disjoint (G : simple_graph V) (v : V) : disjoint (G.neighbor_set v) (Gᶜ.neighbor_set v) := begin rw set.disjoint_iff, rintro w ⟨h, h'⟩, rw [mem_neighbor_set, compl_adj] at h', exact h'.2 h, end lemma neighbor_set_union_compl_neighbor_set_eq (G : simple_graph V) (v : V) : G.neighbor_set v ∪ Gᶜ.neighbor_set v = {v}ᶜ := begin ext w, have h := @ne_of_adj _ G, simp_rw [set.mem_union, mem_neighbor_set, compl_adj, set.mem_compl_iff, set.mem_singleton_iff], tauto, end -- TODO find out why TC inference has `h` failing a defeq check for `to_finset` lemma card_neighbor_set_union_compl_neighbor_set [fintype V] (G : simple_graph V) (v : V) [h : fintype (G.neighbor_set v ∪ Gᶜ.neighbor_set v : set V)] : (@set.to_finset _ (G.neighbor_set v ∪ Gᶜ.neighbor_set v) h).card = fintype.card V - 1 := begin classical, simp_rw [neighbor_set_union_compl_neighbor_set_eq, set.to_finset_compl, finset.card_compl, set.to_finset_card, set.card_singleton], end lemma neighbor_set_compl (G : simple_graph V) (v : V) : Gᶜ.neighbor_set v = (G.neighbor_set v)ᶜ \ {v} := by { ext w, simp [and_comm, eq_comm] } /-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the intersection of the neighbor sets of `v` and `w`. -/ def common_neighbors (v w : V) : set V := G.neighbor_set v ∩ G.neighbor_set w lemma common_neighbors_eq (v w : V) : G.common_neighbors v w = G.neighbor_set v ∩ G.neighbor_set w := rfl lemma mem_common_neighbors {u v w : V} : u ∈ G.common_neighbors v w ↔ G.adj v u ∧ G.adj w u := iff.rfl lemma common_neighbors_symm (v w : V) : G.common_neighbors v w = G.common_neighbors w v := set.inter_comm _ _ lemma not_mem_common_neighbors_left (v w : V) : v ∉ G.common_neighbors v w := λ h, ne_of_adj G h.1 rfl lemma not_mem_common_neighbors_right (v w : V) : w ∉ G.common_neighbors v w := λ h, ne_of_adj G h.2 rfl lemma common_neighbors_subset_neighbor_set_left (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set v := set.inter_subset_left _ _ lemma common_neighbors_subset_neighbor_set_right (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set w := set.inter_subset_right _ _ instance decidable_mem_common_neighbors [decidable_rel G.adj] (v w : V) : decidable_pred (∈ G.common_neighbors v w) := λ a, and.decidable lemma common_neighbors_top_eq {v w : V} : (⊤ : simple_graph V).common_neighbors v w = set.univ \ {v, w} := by { ext u, simp [common_neighbors, eq_comm, not_or_distrib.symm] } section incidence variable [decidable_eq V] /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def other_vertex_of_incident {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : V := h.2.other' lemma edge_other_incident_set {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : e ∈ G.incidence_set (G.other_vertex_of_incident h) := by { use h.1, simp [other_vertex_of_incident, sym2.other_mem'] } lemma incidence_other_prop {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : G.other_vertex_of_incident h ∈ G.neighbor_set v := by { cases h with he hv, rwa [←sym2.other_spec' hv, mem_edge_set] at he } @[simp] lemma incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighbor_set v) : G.other_vertex_of_incident (G.mem_incidence_iff_neighbor.mpr h) = w := sym2.congr_right.mp (sym2.other_spec' (G.mem_incidence_iff_neighbor.mpr h).right) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ @[simps] def incidence_set_equiv_neighbor_set (v : V) : G.incidence_set v ≃ G.neighbor_set v := { to_fun := λ e, ⟨G.other_vertex_of_incident e.2, G.incidence_other_prop e.2⟩, inv_fun := λ w, ⟨⟦(v, w.1)⟧, G.mem_incidence_iff_neighbor.mpr w.2⟩, left_inv := λ x, by simp [other_vertex_of_incident], right_inv := λ ⟨w, hw⟩, by simp } end incidence /-! ## Edge deletion -/ /-- Given a set of vertex pairs, remove all of the corresponding edges from the graph's edge set, if present. See also: `simple_graph.subgraph.delete_edges`. -/ def delete_edges (s : set (sym2 V)) : simple_graph V := { adj := G.adj \ sym2.to_rel s, symm := λ a b, by simp [adj_comm, sym2.eq_swap] } @[simp] lemma delete_edges_adj (s : set (sym2 V)) (v w : V) : (G.delete_edges s).adj v w ↔ G.adj v w ∧ ¬ ⟦(v, w)⟧ ∈ s := iff.rfl lemma sdiff_eq_delete_edges (G G' : simple_graph V) : G \ G' = G.delete_edges G'.edge_set := by { ext, simp } lemma delete_edges_eq_sdiff_from_edge_set (s : set (sym2 V)) : G.delete_edges s = G \ from_edge_set s := by { ext, exact ⟨λ h, ⟨h.1, not_and_of_not_left _ h.2⟩, λ h, ⟨h.1, not_and'.mp h.2 h.ne⟩⟩ } lemma compl_eq_delete_edges : Gᶜ = (⊤ : simple_graph V).delete_edges G.edge_set := by { ext, simp } @[simp] lemma delete_edges_delete_edges (s s' : set (sym2 V)) : (G.delete_edges s).delete_edges s' = G.delete_edges (s ∪ s') := by { ext, simp [and_assoc, not_or_distrib] } @[simp] lemma delete_edges_empty_eq : G.delete_edges ∅ = G := by { ext, simp } @[simp] lemma delete_edges_univ_eq : G.delete_edges set.univ = ⊥ := by { ext, simp } lemma delete_edges_le (s : set (sym2 V)) : G.delete_edges s ≤ G := by { intro, simp { contextual := tt } } lemma delete_edges_le_of_le {s s' : set (sym2 V)} (h : s ⊆ s') : G.delete_edges s' ≤ G.delete_edges s := λ v w, begin simp only [delete_edges_adj, and_imp, true_and] { contextual := tt }, exact λ ha hn hs, hn (h hs), end lemma delete_edges_eq_inter_edge_set (s : set (sym2 V)) : G.delete_edges s = G.delete_edges (s ∩ G.edge_set) := by { ext, simp [imp_false] { contextual := tt } } lemma delete_edges_sdiff_eq_of_le {H : simple_graph V} (h : H ≤ G) : G.delete_edges (G.edge_set \ H.edge_set) = H := by { ext v w, split; simp [@h v w] { contextual := tt } } lemma edge_set_delete_edges (s : set (sym2 V)) : (G.delete_edges s).edge_set = G.edge_set \ s := by { ext e, refine sym2.ind _ e, simp } lemma edge_finset_delete_edges [fintype V] [decidable_eq V] [decidable_rel G.adj] (s : finset (sym2 V)) [decidable_rel (G.delete_edges s).adj] : (G.delete_edges s).edge_finset = G.edge_finset \ s := by { ext e, simp [edge_set_delete_edges] } section delete_far variables (G) [ordered_ring 𝕜] [fintype V] [decidable_eq V] [decidable_rel G.adj] {p : simple_graph V → Prop} {r r₁ r₂ : 𝕜} /-- A graph is `r`-*delete-far* from a property `p` if we must delete at least `r` edges from it to get a graph with the property `p`. -/ def delete_far (p : simple_graph V → Prop) (r : 𝕜) : Prop := ∀ ⦃s⦄, s ⊆ G.edge_finset → p (G.delete_edges s) → r ≤ s.card open_locale classical variables {G} lemma delete_far_iff : G.delete_far p r ↔ ∀ ⦃H⦄, H ≤ G → p H → r ≤ G.edge_finset.card - H.edge_finset.card := begin refine ⟨λ h H hHG hH, _, λ h s hs hG, _⟩, { have := h (sdiff_subset G.edge_finset H.edge_finset), simp only [delete_edges_sdiff_eq_of_le _ hHG, edge_finset_mono hHG, card_sdiff, card_le_of_subset, coe_sdiff, coe_edge_finset, nat.cast_sub] at this, exact this hH }, { simpa [card_sdiff hs, edge_finset_delete_edges, -set.to_finset_card, nat.cast_sub, card_le_of_subset hs] using h (G.delete_edges_le s) hG } end alias delete_far_iff ↔ delete_far.le_card_sub_card _ lemma delete_far.mono (h : G.delete_far p r₂) (hr : r₁ ≤ r₂) : G.delete_far p r₁ := λ s hs hG, hr.trans $ h hs hG end delete_far /-! ## Map and comap -/ /-- Given an injective function, there is an covariant induced map on graphs by pushing forward the adjacency relation. This is injective (see `simple_graph.map_injective`). -/ protected def map (f : V ↪ W) (G : simple_graph V) : simple_graph W := { adj := relation.map G.adj f f } @[simp] lemma map_adj (f : V ↪ W) (G : simple_graph V) (u v : W) : (G.map f).adj u v ↔ ∃ (u' v' : V), G.adj u' v' ∧ f u' = u ∧ f v' = v := iff.rfl lemma map_monotone (f : V ↪ W) : monotone (simple_graph.map f) := by { rintros G G' h _ _ ⟨u, v, ha, rfl, rfl⟩, exact ⟨_, _, h ha, rfl, rfl⟩ } /-- Given a function, there is a contravariant induced map on graphs by pulling back the adjacency relation. This is one of the ways of creating induced graphs. See `simple_graph.induce` for a wrapper. This is surjective when `f` is injective (see `simple_graph.comap_surjective`).-/ @[simps] protected def comap (f : V → W) (G : simple_graph W) : simple_graph V := { adj := λ u v, G.adj (f u) (f v) } lemma comap_monotone (f : V ↪ W) : monotone (simple_graph.comap f) := by { intros G G' h _ _ ha, exact h ha } @[simp] lemma comap_map_eq (f : V ↪ W) (G : simple_graph V) : (G.map f).comap f = G := by { ext, simp } lemma left_inverse_comap_map (f : V ↪ W) : function.left_inverse (simple_graph.comap f) (simple_graph.map f) := comap_map_eq f lemma map_injective (f : V ↪ W) : function.injective (simple_graph.map f) := (left_inverse_comap_map f).injective lemma comap_surjective (f : V ↪ W) : function.surjective (simple_graph.comap f) := (left_inverse_comap_map f).surjective lemma map_le_iff_le_comap (f : V ↪ W) (G : simple_graph V) (G' : simple_graph W) : G.map f ≤ G' ↔ G ≤ G'.comap f := ⟨λ h u v ha, h ⟨_, _, ha, rfl, rfl⟩, by { rintros h _ _ ⟨u, v, ha, rfl, rfl⟩, exact h ha, }⟩ lemma map_comap_le (f : V ↪ W) (G : simple_graph W) : (G.comap f).map f ≤ G := by { rw map_le_iff_le_comap, exact le_refl _ } /-! ## Induced graphs -/ /- Given a set `s` of vertices, we can restrict a graph to those vertices by restricting its adjacency relation. This gives a map between `simple_graph V` and `simple_graph s`. There is also a notion of induced subgraphs (see `simple_graph.subgraph.induce`). -/ /-- Restrict a graph to the vertices in the set `s`, deleting all edges incident to vertices outside the set. This is a wrapper around `simple_graph.comap`. -/ @[reducible] def induce (s : set V) (G : simple_graph V) : simple_graph s := G.comap (function.embedding.subtype _) /-- Given a graph on a set of vertices, we can make it be a `simple_graph V` by adding in the remaining vertices without adding in any additional edges. This is a wrapper around `simple_graph.map`. -/ @[reducible] def spanning_coe {s : set V} (G : simple_graph s) : simple_graph V := G.map (function.embedding.subtype _) lemma induce_spanning_coe {s : set V} {G : simple_graph s} : G.spanning_coe.induce s = G := comap_map_eq _ _ lemma spanning_coe_induce_le (s : set V) : (G.induce s).spanning_coe ≤ G := map_comap_le _ _ section finite_at /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ variables (v) [fintype (G.neighbor_set v)] /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset : finset V := (G.neighbor_set v).to_finset lemma neighbor_finset_def : G.neighbor_finset v = (G.neighbor_set v).to_finset := rfl @[simp] lemma mem_neighbor_finset (w : V) : w ∈ G.neighbor_finset v ↔ G.adj v w := set.mem_to_finset @[simp] lemma not_mem_neighbor_finset_self : v ∉ G.neighbor_finset v := (mem_neighbor_finset _ _ _).not.mpr $ G.loopless _ lemma neighbor_finset_disjoint_singleton : disjoint (G.neighbor_finset v) {v} := finset.disjoint_singleton_right.mpr $ not_mem_neighbor_finset_self _ _ lemma singleton_disjoint_neighbor_finset : disjoint {v} (G.neighbor_finset v) := finset.disjoint_singleton_left.mpr $ not_mem_neighbor_finset_self _ _ /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighbor_finset v).card @[simp] lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v := (set.to_finset_card _).symm lemma degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.adj v w := by simp only [degree, card_pos, finset.nonempty, mem_neighbor_finset] lemma degree_compl [fintype (Gᶜ.neighbor_set v)] [fintype V] : Gᶜ.degree v = fintype.card V - 1 - G.degree v := begin classical, rw [← card_neighbor_set_union_compl_neighbor_set G v, set.to_finset_union], simp [card_disjoint_union (set.disjoint_to_finset.mpr (compl_neighbor_set_disjoint G v))], end instance incidence_set_fintype [decidable_eq V] : fintype (G.incidence_set v) := fintype.of_equiv (G.neighbor_set v) (G.incidence_set_equiv_neighbor_set v).symm /-- This is the `finset` version of `incidence_set`. -/ def incidence_finset [decidable_eq V] : finset (sym2 V) := (G.incidence_set v).to_finset @[simp] lemma card_incidence_set_eq_degree [decidable_eq V] : fintype.card (G.incidence_set v) = G.degree v := by { rw fintype.card_congr (G.incidence_set_equiv_neighbor_set v), simp } @[simp] lemma card_incidence_finset_eq_degree [decidable_eq V] : (G.incidence_finset v).card = G.degree v := by { rw ← G.card_incidence_set_eq_degree, apply set.to_finset_card } @[simp] lemma mem_incidence_finset [decidable_eq V] (e : sym2 V) : e ∈ G.incidence_finset v ↔ e ∈ G.incidence_set v := set.mem_to_finset lemma incidence_finset_eq_filter [decidable_eq V] [fintype G.edge_set] : G.incidence_finset v = G.edge_finset.filter (has_mem.mem v) := begin ext e, refine sym2.ind (λ x y, _) e, simp [mk_mem_incidence_set_iff], end end finite_at section locally_finite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ @[reducible] def locally_finite := Π (v : V), fintype (G.neighbor_set v) variable [locally_finite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d variables {G} lemma is_regular_of_degree.degree_eq {d : ℕ} (h : G.is_regular_of_degree d) (v : V) : G.degree v = d := h v lemma is_regular_of_degree.compl [fintype V] [decidable_eq V] {G : simple_graph V} [decidable_rel G.adj] {k : ℕ} (h : G.is_regular_of_degree k) : Gᶜ.is_regular_of_degree (fintype.card V - 1 - k) := by { intro v, rw [degree_compl, h v] } end locally_finite section finite variable [fintype V] instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) := @subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _ lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] : G.neighbor_finset v = finset.univ.filter (G.adj v) := by { ext, simp } lemma neighbor_finset_compl [decidable_eq V] [decidable_rel G.adj] (v : V) : Gᶜ.neighbor_finset v = (G.neighbor_finset v)ᶜ \ {v} := by simp only [neighbor_finset, neighbor_set_compl, set.to_finset_diff, set.to_finset_compl, set.to_finset_singleton] @[simp] lemma complete_graph_degree [decidable_eq V] (v : V) : (⊤ : simple_graph V).degree v = fintype.card V - 1 := by erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v), card_univ] lemma bot_degree (v : V) : (⊥ : simple_graph V).degree v = 0 := begin erw [degree, neighbor_finset_eq_filter, filter_false], exact finset.card_empty, end lemma is_regular_of_degree.top [decidable_eq V] : (⊤ : simple_graph V).is_regular_of_degree (fintype.card V - 1) := by { intro v, simp } /-- The minimum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_minimal_degree_vertex`, `min_degree_le_degree` and `le_min_degree_of_forall_le_degree`. -/ def min_degree [decidable_rel G.adj] : ℕ := with_top.untop' 0 (univ.image (λ v, G.degree v)).min /-- There exists a vertex of minimal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_minimal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.min_degree = G.degree v := begin obtain ⟨t, ht : _ = _⟩ := min_of_nonempty (univ_nonempty.image (λ v, G.degree v)), obtain ⟨v, _, rfl⟩ := mem_image.mp (mem_of_min ht), refine ⟨v, by simp [min_degree, ht]⟩, end /-- The minimum degree in the graph is at most the degree of any particular vertex. -/ lemma min_degree_le_degree [decidable_rel G.adj] (v : V) : G.min_degree ≤ G.degree v := begin obtain ⟨t, ht⟩ := finset.min_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.min_le_of_eq (mem_image_of_mem _ (mem_univ v)) ht, rwa [min_degree, ht] end /-- In a nonempty graph, if `k` is at most the degree of every vertex, it is at most the minimum degree. Note the assumption that the graph is nonempty is necessary as long as `G.min_degree` is defined to be a natural. -/ lemma le_min_degree_of_forall_le_degree [decidable_rel G.adj] [nonempty V] (k : ℕ) (h : ∀ v, k ≤ G.degree v) : k ≤ G.min_degree := by { rcases G.exists_minimal_degree_vertex with ⟨v, hv⟩, rw hv, apply h } /-- The maximum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_maximal_degree_vertex`, `degree_le_max_degree` and `max_degree_le_of_forall_degree_le`. -/ def max_degree [decidable_rel G.adj] : ℕ := option.get_or_else (univ.image (λ v, G.degree v)).max 0 /-- There exists a vertex of maximal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_maximal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.max_degree = G.degree v := begin obtain ⟨t, ht⟩ := max_of_nonempty (univ_nonempty.image (λ v, G.degree v)), have ht₂ := mem_of_max ht, simp only [mem_image, mem_univ, exists_prop_of_true] at ht₂, rcases ht₂ with ⟨v, rfl⟩, refine ⟨v, _⟩, rw [max_degree, ht], refl end /-- The maximum degree in the graph is at least the degree of any particular vertex. -/ lemma degree_le_max_degree [decidable_rel G.adj] (v : V) : G.degree v ≤ G.max_degree := begin obtain ⟨t, ht : _ = _⟩ := finset.max_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.le_max_of_eq (mem_image_of_mem _ (mem_univ v)) ht, rwa [max_degree, ht], end /-- In a graph, if `k` is at least the degree of every vertex, then it is at least the maximum degree. -/ lemma max_degree_le_of_forall_degree_le [decidable_rel G.adj] (k : ℕ) (h : ∀ v, G.degree v ≤ k) : G.max_degree ≤ k := begin by_cases hV : (univ : finset V).nonempty, { haveI : nonempty V := univ_nonempty_iff.mp hV, obtain ⟨v, hv⟩ := G.exists_maximal_degree_vertex, rw hv, apply h }, { rw not_nonempty_iff_eq_empty at hV, rw [max_degree, hV, image_empty], exact zero_le k }, end lemma degree_lt_card_verts [decidable_rel G.adj] (v : V) : G.degree v < fintype.card V := begin classical, apply finset.card_lt_card, rw finset.ssubset_iff, exact ⟨v, by simp, finset.subset_univ _⟩, end /-- The maximum degree of a nonempty graph is less than the number of vertices. Note that the assumption that `V` is nonempty is necessary, as otherwise this would assert the existence of a natural number less than zero. -/ lemma max_degree_lt_card_verts [decidable_rel G.adj] [nonempty V] : G.max_degree < fintype.card V := begin cases G.exists_maximal_degree_vertex with v hv, rw hv, apply G.degree_lt_card_verts v, end lemma card_common_neighbors_le_degree_left [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree v := begin rw [←card_neighbor_set_eq_degree], exact set.card_le_of_subset (set.inter_subset_left _ _), end lemma card_common_neighbors_le_degree_right [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree w := by simp_rw [common_neighbors_symm _ v w, card_common_neighbors_le_degree_left] lemma card_common_neighbors_lt_card_verts [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) < fintype.card V := nat.lt_of_le_of_lt (G.card_common_neighbors_le_degree_left _ _) (G.degree_lt_card_verts v) /-- If the condition `G.adj v w` fails, then `card_common_neighbors_le_degree` is the best we can do in general. -/ lemma adj.card_common_neighbors_lt_degree {G : simple_graph V} [decidable_rel G.adj] {v w : V} (h : G.adj v w) : fintype.card (G.common_neighbors v w) < G.degree v := begin classical, erw [←set.to_finset_card], apply finset.card_lt_card, rw finset.ssubset_iff, use w, split, { rw set.mem_to_finset, apply not_mem_common_neighbors_right }, { rw finset.insert_subset, split, { simpa, }, { rw [neighbor_finset, set.to_finset_subset_to_finset], exact G.common_neighbors_subset_neighbor_set_left _ _ } } end lemma card_common_neighbors_top [decidable_eq V] {v w : V} (h : v ≠ w) : fintype.card ((⊤ : simple_graph V).common_neighbors v w) = fintype.card V - 2 := begin simp only [common_neighbors_top_eq, ← set.to_finset_card, set.to_finset_diff], rw finset.card_sdiff, { simp [finset.card_univ, h], }, { simp only [set.to_finset_subset_to_finset, set.subset_univ] }, end end finite section maps /-- A graph homomorphism is a map on vertex sets that respects adjacency relations. The notation `G →g G'` represents the type of graph homomorphisms. -/ abbreviation hom := rel_hom G.adj G'.adj /-- A graph embedding is an embedding `f` such that for vertices `v w : V`, `G.adj f(v) f(w) ↔ G.adj v w `. Its image is an induced subgraph of G'. The notation `G ↪g G'` represents the type of graph embeddings. -/ abbreviation embedding := rel_embedding G.adj G'.adj /-- A graph isomorphism is an bijective map on vertex sets that respects adjacency relations. The notation `G ≃g G'` represents the type of graph isomorphisms. -/ abbreviation iso := rel_iso G.adj G'.adj infix ` →g ` : 50 := hom infix ` ↪g ` : 50 := embedding infix ` ≃g ` : 50 := iso namespace hom variables {G G'} (f : G →g G') /-- The identity homomorphism from a graph to itself. -/ abbreviation id : G →g G := rel_hom.id _ lemma map_adj {v w : V} (h : G.adj v w) : G'.adj (f v) (f w) := f.map_rel' h lemma map_mem_edge_set {e : sym2 V} (h : e ∈ G.edge_set) : e.map f ∈ G'.edge_set := quotient.ind (λ e h, sym2.from_rel_prop.mpr (f.map_rel' h)) e h lemma apply_mem_neighbor_set {v w : V} (h : w ∈ G.neighbor_set v) : f w ∈ G'.neighbor_set (f v) := map_adj f h /-- The map between edge sets induced by a homomorphism. The underlying map on edges is given by `sym2.map`. -/ @[simps] def map_edge_set (e : G.edge_set) : G'.edge_set := ⟨sym2.map f e, f.map_mem_edge_set e.property⟩ /-- The map between neighbor sets induced by a homomorphism. -/ @[simps] def map_neighbor_set (v : V) (w : G.neighbor_set v) : G'.neighbor_set (f v) := ⟨f w, f.apply_mem_neighbor_set w.property⟩ /-- The map between darts induced by a homomorphism. -/ def map_dart (d : G.dart) : G'.dart := ⟨d.1.map f f, f.map_adj d.2⟩ @[simp] lemma map_dart_apply (d : G.dart) : f.map_dart d = ⟨d.1.map f f, f.map_adj d.2⟩ := rfl /-- The induced map for spanning subgraphs, which is the identity on vertices. -/ @[simps] def map_spanning_subgraphs {G G' : simple_graph V} (h : G ≤ G') : G →g G' := { to_fun := λ x, x, map_rel' := h } lemma map_edge_set.injective (hinj : function.injective f) : function.injective f.map_edge_set := begin rintros ⟨e₁, h₁⟩ ⟨e₂, h₂⟩, dsimp [hom.map_edge_set], repeat { rw subtype.mk_eq_mk }, apply sym2.map.injective hinj, end /-- Every graph homomomorphism from a complete graph is injective. -/ lemma injective_of_top_hom (f : (⊤ : simple_graph V) →g G') : function.injective f := begin intros v w h, contrapose! h, exact G'.ne_of_adj (map_adj _ ((top_adj _ _).mpr h)), end /-- There is a homomorphism to a graph from a comapped graph. When the function is injective, this is an embedding (see `simple_graph.embedding.comap`). -/ @[simps] protected def comap (f : V → W) (G : simple_graph W) : G.comap f →g G := { to_fun := f, map_rel' := by simp } variable {G'' : simple_graph X} /-- Composition of graph homomorphisms. -/ abbreviation comp (f' : G' →g G'') (f : G →g G') : G →g G'' := f'.comp f @[simp] lemma coe_comp (f' : G' →g G'') (f : G →g G') : ⇑(f'.comp f) = f' ∘ f := rfl end hom namespace embedding variables {G G'} (f : G ↪g G') /-- The identity embedding from a graph to itself. -/ abbreviation refl : G ↪g G := rel_embedding.refl _ /-- An embedding of graphs gives rise to a homomorphism of graphs. -/ abbreviation to_hom : G →g G' := f.to_rel_hom lemma map_adj_iff {v w : V} : G'.adj (f v) (f w) ↔ G.adj v w := f.map_rel_iff lemma map_mem_edge_set_iff {e : sym2 V} : e.map f ∈ G'.edge_set ↔ e ∈ G.edge_set := quotient.ind (λ ⟨v, w⟩, f.map_adj_iff) e lemma apply_mem_neighbor_set_iff {v w : V} : f w ∈ G'.neighbor_set (f v) ↔ w ∈ G.neighbor_set v := map_adj_iff f /-- A graph embedding induces an embedding of edge sets. -/ @[simps] def map_edge_set : G.edge_set ↪ G'.edge_set := { to_fun := hom.map_edge_set f, inj' := hom.map_edge_set.injective f f.inj' } /-- A graph embedding induces an embedding of neighbor sets. -/ @[simps] def map_neighbor_set (v : V) : G.neighbor_set v ↪ G'.neighbor_set (f v) := { to_fun := λ w, ⟨f w, f.apply_mem_neighbor_set_iff.mpr w.2⟩, inj' := begin rintros ⟨w₁, h₁⟩ ⟨w₂, h₂⟩ h, rw subtype.mk_eq_mk at h ⊢, exact f.inj' h, end } /-- Given an injective function, there is an embedding from the comapped graph into the original graph. -/ @[simps] protected def comap (f : V ↪ W) (G : simple_graph W) : G.comap f ↪g G := { map_rel_iff' := by simp, ..f } /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ @[simps] protected def map (f : V ↪ W) (G : simple_graph V) : G ↪g G.map f := { map_rel_iff' := by simp, ..f } /-- Induced graphs embed in the original graph. Note that if `G.induce s = ⊤` (i.e., if `s` is a clique) then this gives the embedding of a complete graph. -/ @[reducible] protected def induce (s : set V) : G.induce s ↪g G := simple_graph.embedding.comap (function.embedding.subtype _) G /-- Graphs on a set of vertices embed in their `spanning_coe`. -/ @[reducible] protected def spanning_coe {s : set V} (G : simple_graph s) : G ↪g G.spanning_coe := simple_graph.embedding.map (function.embedding.subtype _) G /-- Embeddings of types induce embeddings of complete graphs on those types. -/ protected def complete_graph {α β : Type*} (f : α ↪ β) : (⊤ : simple_graph α) ↪g (⊤ : simple_graph β) := { map_rel_iff' := by simp, ..f } variables {G'' : simple_graph X} /-- Composition of graph embeddings. -/ abbreviation comp (f' : G' ↪g G'') (f : G ↪g G') : G ↪g G'' := f.trans f' @[simp] lemma coe_comp (f' : G' ↪g G'') (f : G ↪g G') : ⇑(f'.comp f) = f' ∘ f := rfl end embedding namespace iso variables {G G'} (f : G ≃g G') /-- The identity isomorphism of a graph with itself. -/ abbreviation refl : G ≃g G := rel_iso.refl _ /-- An isomorphism of graphs gives rise to an embedding of graphs. -/ abbreviation to_embedding : G ↪g G' := f.to_rel_embedding /-- An isomorphism of graphs gives rise to a homomorphism of graphs. -/ abbreviation to_hom : G →g G' := f.to_embedding.to_hom /-- The inverse of a graph isomorphism. -/ abbreviation symm : G' ≃g G := f.symm lemma map_adj_iff {v w : V} : G'.adj (f v) (f w) ↔ G.adj v w := f.map_rel_iff lemma map_mem_edge_set_iff {e : sym2 V} : e.map f ∈ G'.edge_set ↔ e ∈ G.edge_set := quotient.ind (λ ⟨v, w⟩, f.map_adj_iff) e lemma apply_mem_neighbor_set_iff {v w : V} : f w ∈ G'.neighbor_set (f v) ↔ w ∈ G.neighbor_set v := map_adj_iff f /-- An isomorphism of graphs induces an equivalence of edge sets. -/ @[simps] def map_edge_set : G.edge_set ≃ G'.edge_set := { to_fun := hom.map_edge_set f, inv_fun := hom.map_edge_set f.symm, left_inv := begin rintro ⟨e, h⟩, simp only [hom.map_edge_set, sym2.map_map, rel_iso.coe_coe_fn, rel_embedding.coe_coe_fn, subtype.mk_eq_mk, subtype.coe_mk, coe_coe], apply congr_fun, convert sym2.map_id, exact funext (λ _, rel_iso.symm_apply_apply _ _), end, right_inv := begin rintro ⟨e, h⟩, simp only [hom.map_edge_set, sym2.map_map, rel_iso.coe_coe_fn, rel_embedding.coe_coe_fn, subtype.mk_eq_mk, subtype.coe_mk, coe_coe], apply congr_fun, convert sym2.map_id, exact funext (λ _, rel_iso.apply_symm_apply _ _), end } /-- A graph isomorphism induces an equivalence of neighbor sets. -/ @[simps] def map_neighbor_set (v : V) : G.neighbor_set v ≃ G'.neighbor_set (f v) := { to_fun := λ w, ⟨f w, f.apply_mem_neighbor_set_iff.mpr w.2⟩, inv_fun := λ w, ⟨f.symm w, begin convert f.symm.apply_mem_neighbor_set_iff.mpr w.2, simp only [rel_iso.symm_apply_apply], end⟩, left_inv := λ w, by simp, right_inv := λ w, by simp } lemma card_eq_of_iso [fintype V] [fintype W] (f : G ≃g G') : fintype.card V = fintype.card W := by convert (fintype.of_equiv_card f.to_equiv).symm /-- Given a bijection, there is an embedding from the comapped graph into the original graph. -/ @[simps] protected def comap (f : V ≃ W) (G : simple_graph W) : G.comap f.to_embedding ≃g G := { map_rel_iff' := by simp, ..f } /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ @[simps] protected def map (f : V ≃ W) (G : simple_graph V) : G ≃g G.map f.to_embedding := { map_rel_iff' := by simp, ..f } /-- Equivalences of types induce isomorphisms of complete graphs on those types. -/ protected def complete_graph {α β : Type*} (f : α ≃ β) : (⊤ : simple_graph α) ≃g (⊤ : simple_graph β) := { map_rel_iff' := by simp, ..f } lemma to_embedding_complete_graph {α β : Type*} (f : α ≃ β) : (iso.complete_graph f).to_embedding = embedding.complete_graph f.to_embedding := rfl variables {G'' : simple_graph X} /-- Composition of graph isomorphisms. -/ abbreviation comp (f' : G' ≃g G'') (f : G ≃g G') : G ≃g G'' := f.trans f' @[simp] lemma coe_comp (f' : G' ≃g G'') (f : G ≃g G') : ⇑(f'.comp f) = f' ∘ f := rfl end iso end maps end simple_graph
e59a40642ef6d76182455c609daad9d1120bb669
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/algebra/ac.lean
5da51c6f4560676c38d923a1ababd96c22c80a7f
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
412
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.logic universe u class is_associative (α : Type u) (op : α → α → α) := (assoc : ∀ a b c, op (op a b) c = op a (op b c)) class is_commutative (α : Type u) (op : α → α → α) := (comm : ∀ a b, op a b = op b a)
f1744a63c34dc8e486130583df20c31f05671486
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Ring/colimits.lean
f786d20f28eb3e2e7add23764a22273b1f549cd5
[ "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
12,904
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Ring.basic import category_theory.limits.has_limits import category_theory.limits.concrete_category /-! # The category of commutative rings has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `comm_ring` and `ring_hom`. -/ universes u v open category_theory open category_theory.limits -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. /- `#print comm_ring` says: structure comm_ring : Type u → Type u fields: comm_ring.zero : Π (α : Type u) [c : comm_ring α], α comm_ring.one : Π (α : Type u) [c : comm_ring α], α comm_ring.neg : Π {α : Type u} [c : comm_ring α], α → α comm_ring.add : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.mul : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.zero_add : ∀ {α : Type u} [c : comm_ring α] (a : α), 0 + a = a comm_ring.add_zero : ∀ {α : Type u} [c : comm_ring α] (a : α), a + 0 = a comm_ring.one_mul : ∀ {α : Type u} [c : comm_ring α] (a : α), 1 * a = a comm_ring.mul_one : ∀ {α : Type u} [c : comm_ring α] (a : α), a * 1 = a comm_ring.add_left_neg : ∀ {α : Type u} [c : comm_ring α] (a : α), -a + a = 0 comm_ring.add_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a + b = b + a comm_ring.mul_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a * b = b * a comm_ring.add_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a + b + c_1 = a + (b + c_1) comm_ring.mul_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) comm_ring.left_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * (b + c_1) = a * b + a * c_1 comm_ring.right_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), (a + b) * c_1 = a * c_1 + b * c_1 -/ namespace CommRing.colimits /-! We build the colimit of a diagram in `CommRing` by constructing the free commutative ring on the disjoint union of all the commutative rings in the diagram, then taking the quotient by the commutative ring laws within each commutative ring, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ CommRing.{v}) /-- An inductive type representing all commutative ring expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero : prequotient | one : prequotient | neg : prequotient → prequotient | add : prequotient → prequotient → prequotient | mul : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.zero⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the commutative ring laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Π (j), relation (of j 0) zero | one : Π (j), relation (of j 1) one | neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) -- Then one relation per argument of each operation | neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y') | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | zero_add : Π (x), relation (add zero x) x | add_zero : Π (x), relation (add x zero) x | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x | add_left_neg : Π (x), relation (add (neg x) x) zero | add_comm : Π (x y), relation (add x y) (add y x) | mul_comm : Π (x y), relation (mul x y) (mul y x) | add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z)) | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | left_distrib : Π (x y z), relation (mul x (add y z)) (add (mul x y) (mul x z)) | right_distrib : Π (x y z), relation (mul (add x y) z) (add (mul x z) (mul y z)) /-- The setoid corresponding to commutative expressions modulo monoid relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `CommRing`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance : comm_ring (colimit_type F) := { zero := begin exact quot.mk _ zero end, one := begin exact quot.mk _ one end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, zero_add := λ x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end, add_left_neg := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, mul_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.mul_comm, refl, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, left_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.left_distrib, refl, refl, refl, end, right_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.right_distrib, refl, refl, refl, end, } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled commutative ring giving the colimit of a diagram. -/ def colimit : CommRing := CommRing.of (colimit_type F) /-- The function from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The ring homomorphism from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := by apply quot.sound; apply relation.one, map_mul' := by intros; apply quot.sound; apply relation.mul, map_zero' := by apply quot.sound; apply relation.zero, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit commutative ring. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F } }. /-- The function from the free commutative ring on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | zero := 0 | one := 1 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y | (mul x y) := desc_fun_lift x * desc_fun_lift y /-- The function from the colimit commutative ring to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- zero { simp, }, -- one { simp, }, -- neg { simp, }, -- add { simp, }, -- mul { simp, }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- mul_comm { rw mul_comm, }, -- add_assoc { rw add_assoc, }, -- mul_assoc { rw mul_assoc, }, -- left_distrib { rw left_distrib, }, -- right_distrib { rw right_distrib, } } end /-- The ring homomorphism from the colimit commutative ring to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_zero' := rfl, map_add' := λ x y, by { induction x; induction y; refl }, map_mul' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp, }, { simp, }, { simp *, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_CommRing : has_colimits CommRing := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end CommRing.colimits
c91cd06dc542e509ab8f2f766ea6427c59227816
e22cb3c96cab3b1635ab1f31bcc6f998a4cab507
/src/advice/default.lean
a4d93a401c38590b34c27460d1eef0a4703a2fb4
[ "Apache-2.0" ]
permissive
jroesch/advice
455909b7fed462b70f60e6f2d8a8809d97baa311
f8b12ee428a128b191f02c4435462ecdd6479812
refs/heads/master
1,610,346,401,725
1,497,946,648,000
1,497,946,716,000
94,866,826
0
0
null
null
null
null
UTF-8
Lean
false
false
297
lean
meta def advice_action : list pexpr → tactic (list (string × string)) := fun ps, tactic.trace_state >> pure [] @[hole_command] meta def advice_type_cmd : hole_command := { name := "Advice", descr := "Provide advice about how to procede with the current goal", action := advice_action }
c90dfb0b895fa6a7423b472e7d5121c40c515753
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/DoubleMonoid.lean
7d46138dc976ef92ebe5ee8a6c094dd444c2f59c
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
11,978
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section DoubleMonoid structure DoubleMonoid (A : Type) : Type := (zero : A) (plus : (A → (A → A))) (lunit_zero : (∀ {x : A} , (plus zero x) = x)) (runit_zero : (∀ {x : A} , (plus x zero) = x)) (associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z)))) (one : A) (times : (A → (A → A))) (lunit_one : (∀ {x : A} , (times one x) = x)) (runit_one : (∀ {x : A} , (times x one) = x)) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) open DoubleMonoid structure Sig (AS : Type) : Type := (zeroS : AS) (plusS : (AS → (AS → AS))) (oneS : AS) (timesS : (AS → (AS → AS))) structure Product (A : Type) : Type := (zeroP : (Prod A A)) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (oneP : (Prod A A)) (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (lunit_0P : (∀ {xP : (Prod A A)} , (plusP zeroP xP) = xP)) (runit_0P : (∀ {xP : (Prod A A)} , (plusP xP zeroP) = xP)) (associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP)))) (lunit_1P : (∀ {xP : (Prod A A)} , (timesP oneP xP) = xP)) (runit_1P : (∀ {xP : (Prod A A)} , (timesP xP oneP) = xP)) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) structure Hom {A1 : Type} {A2 : Type} (Do1 : (DoubleMonoid A1)) (Do2 : (DoubleMonoid A2)) : Type := (hom : (A1 → A2)) (pres_zero : (hom (zero Do1)) = (zero Do2)) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Do1) x1 x2)) = ((plus Do2) (hom x1) (hom x2)))) (pres_one : (hom (one Do1)) = (one Do2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Do1) x1 x2)) = ((times Do2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Do1 : (DoubleMonoid A1)) (Do2 : (DoubleMonoid A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_zero : (interp (zero Do1) (zero Do2))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Do1) x1 x2) ((plus Do2) y1 y2)))))) (interp_one : (interp (one Do1) (one Do2))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Do1) x1 x2) ((times Do2) y1 y2)))))) inductive DoubleMonoidTerm : Type | zeroL : DoubleMonoidTerm | plusL : (DoubleMonoidTerm → (DoubleMonoidTerm → DoubleMonoidTerm)) | oneL : DoubleMonoidTerm | timesL : (DoubleMonoidTerm → (DoubleMonoidTerm → DoubleMonoidTerm)) open DoubleMonoidTerm inductive ClDoubleMonoidTerm (A : Type) : Type | sing : (A → ClDoubleMonoidTerm) | zeroCl : ClDoubleMonoidTerm | plusCl : (ClDoubleMonoidTerm → (ClDoubleMonoidTerm → ClDoubleMonoidTerm)) | oneCl : ClDoubleMonoidTerm | timesCl : (ClDoubleMonoidTerm → (ClDoubleMonoidTerm → ClDoubleMonoidTerm)) open ClDoubleMonoidTerm inductive OpDoubleMonoidTerm (n : ℕ) : Type | v : ((fin n) → OpDoubleMonoidTerm) | zeroOL : OpDoubleMonoidTerm | plusOL : (OpDoubleMonoidTerm → (OpDoubleMonoidTerm → OpDoubleMonoidTerm)) | oneOL : OpDoubleMonoidTerm | timesOL : (OpDoubleMonoidTerm → (OpDoubleMonoidTerm → OpDoubleMonoidTerm)) open OpDoubleMonoidTerm inductive OpDoubleMonoidTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpDoubleMonoidTerm2) | sing2 : (A → OpDoubleMonoidTerm2) | zeroOL2 : OpDoubleMonoidTerm2 | plusOL2 : (OpDoubleMonoidTerm2 → (OpDoubleMonoidTerm2 → OpDoubleMonoidTerm2)) | oneOL2 : OpDoubleMonoidTerm2 | timesOL2 : (OpDoubleMonoidTerm2 → (OpDoubleMonoidTerm2 → OpDoubleMonoidTerm2)) open OpDoubleMonoidTerm2 def simplifyCl {A : Type} : ((ClDoubleMonoidTerm A) → (ClDoubleMonoidTerm A)) | (plusCl zeroCl x) := x | (plusCl x zeroCl) := x | (timesCl oneCl x) := x | (timesCl x oneCl) := x | zeroCl := zeroCl | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | oneCl := oneCl | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpDoubleMonoidTerm n) → (OpDoubleMonoidTerm n)) | (plusOL zeroOL x) := x | (plusOL x zeroOL) := x | (timesOL oneOL x) := x | (timesOL x oneOL) := x | zeroOL := zeroOL | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | oneOL := oneOL | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpDoubleMonoidTerm2 n A) → (OpDoubleMonoidTerm2 n A)) | (plusOL2 zeroOL2 x) := x | (plusOL2 x zeroOL2) := x | (timesOL2 oneOL2 x) := x | (timesOL2 x oneOL2) := x | zeroOL2 := zeroOL2 | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | oneOL2 := oneOL2 | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((DoubleMonoid A) → (DoubleMonoidTerm → A)) | Do zeroL := (zero Do) | Do (plusL x1 x2) := ((plus Do) (evalB Do x1) (evalB Do x2)) | Do oneL := (one Do) | Do (timesL x1 x2) := ((times Do) (evalB Do x1) (evalB Do x2)) def evalCl {A : Type} : ((DoubleMonoid A) → ((ClDoubleMonoidTerm A) → A)) | Do (sing x1) := x1 | Do zeroCl := (zero Do) | Do (plusCl x1 x2) := ((plus Do) (evalCl Do x1) (evalCl Do x2)) | Do oneCl := (one Do) | Do (timesCl x1 x2) := ((times Do) (evalCl Do x1) (evalCl Do x2)) def evalOpB {A : Type} {n : ℕ} : ((DoubleMonoid A) → ((vector A n) → ((OpDoubleMonoidTerm n) → A))) | Do vars (v x1) := (nth vars x1) | Do vars zeroOL := (zero Do) | Do vars (plusOL x1 x2) := ((plus Do) (evalOpB Do vars x1) (evalOpB Do vars x2)) | Do vars oneOL := (one Do) | Do vars (timesOL x1 x2) := ((times Do) (evalOpB Do vars x1) (evalOpB Do vars x2)) def evalOp {A : Type} {n : ℕ} : ((DoubleMonoid A) → ((vector A n) → ((OpDoubleMonoidTerm2 n A) → A))) | Do vars (v2 x1) := (nth vars x1) | Do vars (sing2 x1) := x1 | Do vars zeroOL2 := (zero Do) | Do vars (plusOL2 x1 x2) := ((plus Do) (evalOp Do vars x1) (evalOp Do vars x2)) | Do vars oneOL2 := (one Do) | Do vars (timesOL2 x1 x2) := ((times Do) (evalOp Do vars x1) (evalOp Do vars x2)) def inductionB {P : (DoubleMonoidTerm → Type)} : ((P zeroL) → ((∀ (x1 x2 : DoubleMonoidTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((P oneL) → ((∀ (x1 x2 : DoubleMonoidTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → (∀ (x : DoubleMonoidTerm) , (P x)))))) | p0l pplusl p1l ptimesl zeroL := p0l | p0l pplusl p1l ptimesl (plusL x1 x2) := (pplusl _ _ (inductionB p0l pplusl p1l ptimesl x1) (inductionB p0l pplusl p1l ptimesl x2)) | p0l pplusl p1l ptimesl oneL := p1l | p0l pplusl p1l ptimesl (timesL x1 x2) := (ptimesl _ _ (inductionB p0l pplusl p1l ptimesl x1) (inductionB p0l pplusl p1l ptimesl x2)) def inductionCl {A : Type} {P : ((ClDoubleMonoidTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P zeroCl) → ((∀ (x1 x2 : (ClDoubleMonoidTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((P oneCl) → ((∀ (x1 x2 : (ClDoubleMonoidTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → (∀ (x : (ClDoubleMonoidTerm A)) , (P x))))))) | psing p0cl ppluscl p1cl ptimescl (sing x1) := (psing x1) | psing p0cl ppluscl p1cl ptimescl zeroCl := p0cl | psing p0cl ppluscl p1cl ptimescl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing p0cl ppluscl p1cl ptimescl x1) (inductionCl psing p0cl ppluscl p1cl ptimescl x2)) | psing p0cl ppluscl p1cl ptimescl oneCl := p1cl | psing p0cl ppluscl p1cl ptimescl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing p0cl ppluscl p1cl ptimescl x1) (inductionCl psing p0cl ppluscl p1cl ptimescl x2)) def inductionOpB {n : ℕ} {P : ((OpDoubleMonoidTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P zeroOL) → ((∀ (x1 x2 : (OpDoubleMonoidTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((P oneOL) → ((∀ (x1 x2 : (OpDoubleMonoidTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → (∀ (x : (OpDoubleMonoidTerm n)) , (P x))))))) | pv p0ol pplusol p1ol ptimesol (v x1) := (pv x1) | pv p0ol pplusol p1ol ptimesol zeroOL := p0ol | pv p0ol pplusol p1ol ptimesol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv p0ol pplusol p1ol ptimesol x1) (inductionOpB pv p0ol pplusol p1ol ptimesol x2)) | pv p0ol pplusol p1ol ptimesol oneOL := p1ol | pv p0ol pplusol p1ol ptimesol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv p0ol pplusol p1ol ptimesol x1) (inductionOpB pv p0ol pplusol p1ol ptimesol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpDoubleMonoidTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P zeroOL2) → ((∀ (x1 x2 : (OpDoubleMonoidTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((P oneOL2) → ((∀ (x1 x2 : (OpDoubleMonoidTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → (∀ (x : (OpDoubleMonoidTerm2 n A)) , (P x)))))))) | pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 (v2 x1) := (pv2 x1) | pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 (sing2 x1) := (psing2 x1) | pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 zeroOL2 := p0ol2 | pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 x1) (inductionOp pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 x2)) | pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 oneOL2 := p1ol2 | pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 x1) (inductionOp pv2 psing2 p0ol2 pplusol2 p1ol2 ptimesol2 x2)) def stageB : (DoubleMonoidTerm → (Staged DoubleMonoidTerm)) | zeroL := (Now zeroL) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) | oneL := (Now oneL) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClDoubleMonoidTerm A) → (Staged (ClDoubleMonoidTerm A))) | (sing x1) := (Now (sing x1)) | zeroCl := (Now zeroCl) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) | oneCl := (Now oneCl) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpDoubleMonoidTerm n) → (Staged (OpDoubleMonoidTerm n))) | (v x1) := (const (code (v x1))) | zeroOL := (Now zeroOL) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) | oneOL := (Now oneOL) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpDoubleMonoidTerm2 n A) → (Staged (OpDoubleMonoidTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | zeroOL2 := (Now zeroOL2) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) | oneOL2 := (Now oneOL2) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (zeroT : (Repr A)) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) (oneT : (Repr A)) (timesT : ((Repr A) → ((Repr A) → (Repr A)))) end DoubleMonoid
9dc20994de045d62105c923d38aa68df42d1c0ff
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab/Tactic/Conv/Unfold.lean
fd2c60c8e4904878c23f255420aa2b4068c611f9
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
567
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.Unfold import Lean.Elab.Tactic.Conv.Simp namespace Lean.Elab.Tactic.Conv open Meta @[builtinTactic Lean.Parser.Tactic.Conv.unfold] def evalUnfold : Tactic := fun stx => withMainContext do for declNameId in stx[1].getArgs do let declName ← resolveGlobalConstNoOverloadWithInfo declNameId applySimpResult (← unfold (← getLhs) declName) end Lean.Elab.Tactic.Conv
57c05cae600be1f3bde7c7666ca3ca538267b029
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/measure_theory/bochner_integration.lean
ae6cd4cbe8ffaed5cec95fb810e230ab041d381d
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
64,861
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.simple_func_dense import analysis.normed_space.bounded_linear_maps import topology.sequences /-! # 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 α E` (notation : `α →ₛ E`) where `E` 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 `α →ₛ E` 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 `α →₁ₛ[μ] E`. 3. Show that the embedding of `α →₁ₛ[μ] E` into L1 is a dense and uniform one. 4. Show that the integral defined on `α →₁ₛ[μ] E` is a continuous linear map. 5. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ[μ] E` 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 `α → E`, where `α` is a measure space and `E` is a real normed space. * `integral_zero` : `∫ 0 ∂μ = 0` * `integral_add` : `∫ x, f x + g x ∂μ = ∫ x, f ∂μ + ∫ x, g x ∂μ` * `integral_neg` : `∫ x, - f x ∂μ = - ∫ x, f x ∂μ` * `integral_sub` : `∫ x, f x - g x ∂μ = ∫ x, f x ∂μ - ∫ x, g x ∂μ` * `integral_smul` : `∫ x, r • f x ∂μ = r • ∫ x, f x ∂μ` * `integral_congr_ae` : `f =ᵐ[μ] g → ∫ x, f x ∂μ = ∫ x, g x ∂μ` * `norm_integral_le_integral_norm` : `∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `0 ≤ᵐ[μ] f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos_of_ae` : `f ≤ᵐ[μ] 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono_ae` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` * `integral_nonneg` : `0 ≤ f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos` : `f ≤ 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` 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` : `∫ x, f x ∂μ = ∫⁻ x, f⁺ x ∂μ - ∫⁻ x, f⁻ x ∂μ`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `0 ≤ᵐ[μ] f → ∫ x, f x ∂μ = ∫⁻ x, f x ∂μ` 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. One method is to use the theorem `integrable.induction` in the file `set_integral`, which allows you to prove something for an arbitrary measurable + integrable function. Another method is using the following steps. 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 * `α →ₛ E` : simple functions (defined in `measure_theory/integration`) * `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/l1_space`) * `α →₁ₛ[μ] E` : 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 big_operators namespace measure_theory variables {α E : Type*} [measurable_space α] [linear_order E] [has_zero E] local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ E) : α →ₛ E := f.map (λb, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg E] (f : α →ₛ E) : α →ₛ E := 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 a, rw coe_sub, 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 variables {α E F : Type*} [measurable_space α] local infixr ` →ₛ `:25 := simple_func namespace simple_func section integral /-! ### 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 E] [measurable_space E] [normed_group F] variables {μ : measure α} /-- For simple functions with a `normed_group` as codomain, being integrable is the same as having finite volume support. -/ lemma integrable_iff_fin_meas_supp {f : α →ₛ E} {μ : measure α} : integrable f μ ↔ f.fin_meas_supp μ := calc integrable f μ ↔ ∫⁻ x, f.map (coe ∘ nnnorm : E → ennreal) x ∂μ < ⊤ : and_iff_right f.measurable ... ↔ (f.map (coe ∘ nnnorm : E → ennreal)).lintegral μ < ⊤ : by rw lintegral_eq_lintegral ... ↔ (f.map (coe ∘ nnnorm : E → ennreal)).fin_meas_supp μ : iff.symm $ fin_meas_supp.iff_lintegral_lt_top $ eventually_of_forall $ λ x, coe_lt_top ... ↔ _ : fin_meas_supp.map_iff $ λ b, coe_eq_zero.trans nnnorm_eq_zero lemma fin_meas_supp.integrable {f : α →ₛ E} (h : f.fin_meas_supp μ) : integrable f μ := integrable_iff_fin_meas_supp.2 h lemma integrable_pair [measurable_space F] {f : α →ₛ E} {g : α →ₛ F} : integrable f μ → integrable g μ → integrable (pair f g) μ := by simpa only [integrable_iff_fin_meas_supp] using fin_meas_supp.pair variables [normed_space ℝ F] /-- Bochner integral of simple functions whose codomain is a real `normed_space`. -/ def integral (μ : measure α) (f : α →ₛ F) : F := ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x lemma integral_eq_sum_filter (f : α →ₛ F) (μ) : f.integral μ = ∑ x in f.range.filter (λ x, x ≠ 0), (ennreal.to_real (μ (f ⁻¹' {x}))) • x := eq.symm $ sum_filter_of_ne $ λ x _, mt $ λ h0, h0.symm ▸ smul_zero _ /-- The Bochner integral is equal to a sum over any set that includes `f.range` (except `0`). -/ lemma integral_eq_sum_of_subset {f : α →ₛ F} {μ : measure α} {s : finset F} (hs : f.range.filter (λ x, x ≠ 0) ⊆ s) : f.integral μ = ∑ x in s, (μ (f ⁻¹' {x})).to_real • x := begin rw [simple_func.integral_eq_sum_filter, finset.sum_subset hs], rintro x - hx, rw [finset.mem_filter, not_and_distrib, ne.def, not_not] at hx, rcases hx with hx|rfl; [skip, simp], rw [simple_func.mem_range] at hx, rw [preimage_eq_empty]; simp [disjoint_singleton_left, hx] end /-- Calculate the integral of `g ∘ f : α →ₛ F`, where `f` is an integrable function from `α` to `E` and `g` is a function from `E` to `F`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_integral (f : α →ₛ E) (g : E → F) (hf : integrable f μ) (hg : g 0 = 0) : (f.map g).integral μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • (g x) := begin -- We start as in the proof of `map_lintegral` simp only [integral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_preimage _)], -- Now we use `hf : integrable f μ` to show that `ennreal.to_real` is additive. by_cases ha : g (f a) = 0, { simp only [ha, smul_zero], refine (sum_eq_zero $ λ x hx, _).symm, simp only [mem_filter] at hx, simp [hx.2] }, { rw [to_real_sum, sum_smul], { refine sum_congr rfl (λ x hx, _), simp only [mem_filter] at hx, rw [hx.2] }, { intros x hx, simp only [mem_filter] at hx, refine (integrable_iff_fin_meas_supp.1 hf).meas_preimage_singleton_ne_zero _, exact λ h0, ha (hx.2 ▸ h0.symm ▸ hg) } }, end /-- `simple_func.integral` and `simple_func.lintegral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `integral_eq_lintegral` for a simpler version. -/ lemma integral_eq_lintegral' {f : α →ₛ E} {g : E → ennreal} (hf : integrable f μ) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).integral μ = ennreal.to_real (∫⁻ a, g (f a) ∂μ) := begin have hf' : f.fin_meas_supp μ := integrable_iff_fin_meas_supp.1 hf, simp only [← map_apply g f, lintegral_eq_lintegral], rw [map_integral f _ hf, map_lintegral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul, to_real_mul, 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'.meas_preimage_singleton_ne_zero a0) } }, { simp [hg0] } end variables [normed_space ℝ E] lemma integral_congr {f g : α →ₛ E} (hf : integrable f μ) (h : f =ᵐ[μ] g): f.integral μ = g.integral μ := show ((pair f g).map prod.fst).integral μ = ((pair f g).map prod.snd).integral μ, from begin have inte := integrable_pair hf (hf.congr g.measurable h), rw [map_integral (pair f g) _ inte prod.fst_zero, map_integral (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 : μ ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine measure_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 integral_eq_lintegral {f : α →ₛ ℝ} (hf : integrable f μ) (h_pos : 0 ≤ᵐ[μ] f) : f.integral μ = ennreal.to_real (∫⁻ a, ennreal.of_real (f a) ∂μ) := begin have : f =ᵐ[μ] f.map (ennreal.to_real ∘ ennreal.of_real) := h_pos.mono (λ a h, (ennreal.to_real_of_real h).symm), rw [← integral_eq_lintegral' hf], { exact integral_congr hf this }, { exact ennreal.of_real_zero }, { assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top } end lemma integral_add {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f + g) = integral μ f + integral μ g := calc integral μ (f + g) = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • (x.fst + x.snd) : begin rw [add_eq_map₂, map_integral (pair f g)], { exact integrable_pair hf hg }, { simp only [add_zero, prod.fst_zero, prod.snd_zero] } end ... = ∑ x in (pair f g).range, (ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd) : finset.sum_congr rfl $ assume a ha, smul_add _ _ _ ... = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd : by rw finset.sum_add_distrib ... = ((pair f g).map prod.fst).integral μ + ((pair f g).map prod.snd).integral μ : begin rw [map_integral (pair f g), map_integral (pair f g)], { exact integrable_pair hf hg }, { refl }, { exact integrable_pair hf hg }, { refl } end ... = integral μ f + integral μ g : rfl lemma integral_neg {f : α →ₛ E} (hf : integrable f μ) : integral μ (-f) = - integral μ f := calc integral μ (-f) = integral μ (f.map (has_neg.neg)) : rfl ... = - integral μ f : begin rw [map_integral f _ hf neg_zero, integral, ← sum_neg_distrib], refine finset.sum_congr rfl (λx h, smul_neg _ _), end lemma integral_sub [borel_space E] {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f - g) = integral μ f - integral μ g := begin rw [sub_eq_add_neg, integral_add hf, integral_neg hg, sub_eq_add_neg], exact hg.neg end lemma integral_smul (r : ℝ) {f : α →ₛ E} (hf : integrable f μ) : integral μ (r • f) = r • integral μ f := calc integral μ (r • f) = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • r • x : by rw [smul_eq_map r f, map_integral f _ hf (smul_zero _)] ... = ∑ x in f.range, ((ennreal.to_real (μ (f ⁻¹' {x}))) * r) • x : finset.sum_congr rfl $ λb hb, by apply smul_smul ... = r • integral μ f : by simp only [integral, smul_sum, smul_smul, mul_comm] lemma norm_integral_le_integral_norm (f : α →ₛ E) (hf : integrable f μ) : ∥f.integral μ∥ ≤ (f.map norm).integral μ := begin rw [map_integral f norm hf norm_zero, integral], calc ∥∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • x∥ ≤ ∑ x in f.range, ∥ennreal.to_real (μ (f ⁻¹' {x})) • x∥ : norm_sum_le _ _ ... = ∑ x in f.range, ennreal.to_real (μ (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 lemma integral_add_measure {ν} (f : α →ₛ E) (hf : integrable f (μ + ν)) : f.integral (μ + ν) = f.integral μ + f.integral ν := begin simp only [integral_eq_sum_filter, ← sum_add_distrib, ← add_smul, measure.add_apply], refine sum_congr rfl (λ x hx, _), rw [to_real_add]; refine ne_of_lt ((integrable_iff_fin_meas_supp.1 _).meas_preimage_singleton_ne_zero (mem_filter.1 hx).2), exacts [hf.left_of_add_measure, hf.right_of_add_measure] end end integral end simple_func namespace l1 open ae_eq_fun variables [normed_group E] [second_countable_topology E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [measurable_space F] [borel_space F] {μ : measure α} variables (α E μ) -- We use `Type*` instead of `add_subgroup` because otherwise we loose dot notation. /-- `l1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple function. -/ def simple_func : Type* := ↥({ carrier := {f : α →₁[μ] E | ∃ (s : α →ₛ E), (ae_eq_fun.mk s s.measurable : α →ₘ[μ] E) = f}, zero_mem' := ⟨0, rfl⟩, add_mem' := λ f g ⟨s, hs⟩ ⟨t, ht⟩, ⟨s + t, by simp only [coe_add, ← hs, ← ht, mk_add_mk, ← simple_func.coe_add]⟩, neg_mem' := λ f ⟨s, hs⟩, ⟨-s, by simp only [coe_neg, ← hs, neg_mk, ← simple_func.coe_neg]⟩ } : add_subgroup (α →₁[μ] E)) variables {α E μ} notation α ` →₁ₛ[`:25 μ `] ` E := measure_theory.l1.simple_func α E μ namespace simple_func section instances /-! Simple functions in L1 space form a `normed_space`. -/ instance : has_coe (α →₁ₛ[μ] E) (α →₁[μ] E) := coe_subtype instance : has_coe_to_fun (α →₁ₛ[μ] E) := ⟨λ f, α → E, λ f, ⇑(f : α →₁[μ] E)⟩ @[simp, norm_cast] lemma coe_coe (f : α →₁ₛ[μ] E) : ⇑(f : α →₁[μ] E) = f := rfl protected lemma eq {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = (g : α →₁[μ] E) → f = g := subtype.eq protected lemma eq' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = (g : α →ₘ[μ] E) → f = g := subtype.eq ∘ subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = g ↔ f = g := subtype.ext_iff.symm @[norm_cast] protected lemma eq_iff' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = 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 (α →₁ₛ[μ] E) := 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 (α →₁ₛ[μ] E) := subtype.metric_space local attribute [instance] simple_func.metric_space simple_func.emetric_space /-- Functions `α →₁ₛ[μ] E` form an additive commutative group. -/ local attribute [instance, priority 10000] protected def add_comm_group : add_comm_group (α →₁ₛ[μ] E) := add_subgroup.to_add_comm_group _ instance : inhabited (α →₁ₛ[μ] E) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ₛ[μ] E) : α →₁[μ] E) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ₛ[μ] E) : ((f + g : α →₁ₛ[μ] E) : α →₁[μ] E) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ₛ[μ] E) : ((-f : α →₁ₛ[μ] E) : α →₁[μ] E) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ₛ[μ] E) : ((f - g : α →₁ₛ[μ] E) : α →₁[μ] E) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ₛ[μ] E) : edist f g = edist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl @[simp] lemma dist_eq (f g : α →₁ₛ[μ] E) : dist f g = dist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl /-- The norm on `α →₁ₛ[μ] E` is inherited from L1 space. That is, `∥f∥ = ∫⁻ a, edist (f a) 0`. Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def has_norm : has_norm (α →₁ₛ[μ] E) := ⟨λf, ∥(f : α →₁[μ] E)∥⟩ local attribute [instance] simple_func.has_norm lemma norm_eq (f : α →₁ₛ[μ] E) : ∥f∥ = ∥(f : α →₁[μ] E)∥ := rfl lemma norm_eq' (f : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ[μ] E) 0) := rfl /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def normed_group : normed_group (α →₁ₛ[μ] E) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add, l1.dist_eq, l1.coe_add], rw edist_add_right } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def has_scalar : has_scalar 𝕜 (α →₁ₛ[μ] E) := ⟨λk f, ⟨k • f, begin rcases f with ⟨f, ⟨s, hs⟩⟩, use k • s, 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 : α →₁ₛ[μ] E) : ((c • f : α →₁ₛ[μ] E) : α →₁[μ] E) = c • (f : α →₁[μ] E) := rfl /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def semimodule : semimodule 𝕜 (α →₁ₛ[μ] E) := { 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 _ _ }) } local attribute [instance] simple_func.normed_group simple_func.semimodule /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def normed_space : normed_space 𝕜 (α →₁ₛ[μ] E) := ⟨ λ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 : α →ₛ E) (hf : integrable f μ) : (α →₁ₛ[μ] E) := ⟨l1.of_fun f hf, ⟨f, rfl⟩⟩ lemma of_simple_func_eq_of_fun (f : α →ₛ E) (hf : integrable f μ) : (of_simple_func f hf : α →₁[μ] E) = l1.of_fun f hf := rfl lemma of_simple_func_eq_mk (f : α →ₛ E) (hf : integrable f μ) : (of_simple_func f hf : α →ₘ[μ] E) = ae_eq_fun.mk f f.measurable := rfl lemma of_simple_func_zero : of_simple_func (0 : α →ₛ E) (integrable_zero α E μ) = 0 := rfl lemma of_simple_func_add (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : of_simple_func (f + g) (hf.add hg) = of_simple_func f hf + of_simple_func g hg := rfl lemma of_simple_func_neg (f : α →ₛ E) (hf : integrable f μ) : of_simple_func (-f) hf.neg = -of_simple_func f hf := rfl lemma of_simple_func_sub (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : of_simple_func (f - g) (hf.sub hg) = of_simple_func f hf - of_simple_func g hg := by { simp only [sub_eq_add_neg, ← of_simple_func_neg, ← of_simple_func_add], refl } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma of_simple_func_smul (f : α →ₛ E) (hf : integrable f μ) (c : 𝕜) : of_simple_func (c • f) (hf.smul c) = c • of_simple_func f hf := rfl lemma norm_of_simple_func (f : α →ₛ E) (hf : integrable f μ) : ∥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 : α →₁ₛ[μ] E) : α →ₛ E := classical.some f.2 /-- `f.to_simple_func` is measurable. -/ protected lemma measurable (f : α →₁ₛ[μ] E) : measurable f.to_simple_func := f.to_simple_func.measurable /-- `f.to_simple_func` is integrable. -/ protected lemma integrable (f : α →₁ₛ[μ] E) : integrable f.to_simple_func μ := let h := classical.some_spec f.2 in (integrable_mk f.measurable).1 $ h.symm ▸ (f : α →₁[μ] E).2 lemma of_simple_func_to_simple_func (f : α →₁ₛ[μ] E) : of_simple_func (f.to_simple_func) f.integrable = f := by { rw ← simple_func.eq_iff', exact classical.some_spec f.2 } lemma to_simple_func_of_simple_func (f : α →ₛ E) (hfi : integrable f μ) : (of_simple_func f hfi).to_simple_func =ᵐ[μ] f := by { rw ← mk_eq_mk, exact classical.some_spec (of_simple_func f hfi).2 } lemma to_simple_func_eq_to_fun (f : α →₁ₛ[μ] E) : f.to_simple_func =ᵐ[μ] f := begin rw [← of_fun_eq_of_fun f.to_simple_func f f.integrable (f : α →₁[μ] E).integrable, ← l1.eq_iff], simp only [of_fun_eq_mk, ← coe_coe, mk_to_fun], exact classical.some_spec f.coe_prop end variables (α E) lemma zero_to_simple_func : (0 : α →₁ₛ[μ] E).to_simple_func =ᵐ[μ] 0 := begin filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ[μ] E), l1.zero_to_fun α E], assume a h₁ h₂, rwa h₁, end variables {α E} lemma add_to_simple_func (f g : α →₁ₛ[μ] E) : (f + g).to_simple_func =ᵐ[μ] f.to_simple_func + g.to_simple_func := 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 : α →₁[μ] E) g], assume a, simp only [← coe_coe, coe_add, pi.add_apply], iterate 4 { assume h, rw h } end lemma neg_to_simple_func (f : α →₁ₛ[μ] E) : (-f).to_simple_func =ᵐ[μ] - f.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, l1.neg_to_fun (f : α →₁[μ] E)], assume a, simp only [pi.neg_apply, coe_neg, ← coe_coe], repeat { assume h, rw h } end lemma sub_to_simple_func (f g : α →₁ₛ[μ] E) : (f - g).to_simple_func =ᵐ[μ] f.to_simple_func - g.to_simple_func := 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 : α →₁[μ] E) g], assume a, simp only [coe_sub, pi.sub_apply, ← coe_coe], repeat { assume h, rw h } end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ[μ] E) : (k • f).to_simple_func =ᵐ[μ] k • f.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f, l1.smul_to_fun k (f : α →₁[μ] E)], assume a, simp only [pi.smul_apply, coe_smul, ← coe_coe], repeat { assume h, rw h } end lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ[μ] E) : ∫⁻ (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 : α →₁ₛ[μ] E) : 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 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 : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a) ∂μ) := calc ∥f∥ = ennreal.to_real (∫⁻x, edist (f.to_simple_func x) ((0 : α →₁ₛ[μ] E).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 : α →₁ₛ[μ] E)) x) ∂μ = ∫⁻ x, edist ((to_simple_func f) x) 0 ∂μ, { refine lintegral_congr_ae ((zero_to_simple_func α E).mono (λ a h, _)), rw [h, pi.zero_apply] }, 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_integral (f : α →₁ₛ[μ] E) : ∥f∥ = (f.to_simple_func.map norm).integral μ := -- 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).integral μ : begin rw [norm_to_simple_func, simple_func.integral_eq_lintegral], { simp only [simple_func.map_apply, of_real_norm_eq_coe_nnnorm] }, { exact f.integrable.norm }, { exact eventually_of_forall (λ x, norm_nonneg _) } end end to_simple_func section coe_to_l1 protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_continuous_comap protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_embedding_comap subtype.val_injective protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.uniform_embedding.to_uniform_inducing protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := begin apply simple_func.uniform_embedding.dense_embedding, rintros ⟨⟨f, hfm⟩, hfi⟩, rw mem_closure_iff_seq_limit, have hfi' := (integrable_mk hfm).1 hfi, refine ⟨λ n, ↑(of_simple_func (simple_func.approx_on f hfm univ 0 trivial n) (simple_func.integrable_approx_on_univ hfi' n)), λ n, mem_range_self _, _⟩, rw tendsto_iff_edist_tendsto_0, simpa [edist_mk_mk] using simple_func.tendsto_approx_on_univ_l1_edist hfi' end protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_embedding.to_dense_inducing protected lemma dense_range : dense_range (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_inducing.dense variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 E] variables (α E) /-- The uniform and dense embedding of L1 simple functions into L1 functions. -/ def coe_to_l1 : (α →₁ₛ[μ] E) →L[𝕜] (α →₁[μ] E) := { to_fun := (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)), map_add' := λf g, rfl, map_smul' := λk f, rfl, cont := l1.simple_func.uniform_continuous.continuous, } variables {α E 𝕜} 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, hsf⟩, use s.pos_part, simp only [subtype.coe_mk, l1.coe_pos_part, ← hsf, ae_eq_fun.pos_part_mk, simple_func.pos_part, simple_func.coe_map] 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 `α →₁ₛ[μ] E` and prove basic properties of this integral. -/ variables [normed_space ℝ E] /-- The Bochner integral over simple functions in l1 space. -/ def integral (f : α →₁ₛ[μ] E) : E := (f.to_simple_func).integral μ lemma integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = (f.to_simple_func).integral μ := rfl lemma integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] f.to_simple_func) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real (f.to_simple_func a) ∂μ) := by rw [integral, simple_func.integral_eq_lintegral f.integrable h_pos] lemma integral_congr {f g : α →₁ₛ[μ] E} (h : f.to_simple_func =ᵐ[μ] g.to_simple_func) : integral f = integral g := simple_func.integral_congr f.integrable h lemma integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g := begin simp only [integral], rw ← simple_func.integral_add f.integrable g.integrable, apply measure_theory.simple_func.integral_congr (f + g).integrable, apply add_to_simple_func end lemma integral_smul (r : ℝ) (f : α →₁ₛ[μ] E) : integral (r • f) = r • integral f := begin simp only [integral], rw ← simple_func.integral_smul _ f.integrable, apply measure_theory.simple_func.integral_congr (r • f).integrable, apply smul_to_simple_func end lemma norm_integral_le_norm (f : α →₁ₛ[μ] E) : ∥ integral f ∥ ≤ ∥f∥ := begin rw [integral, norm_eq_integral], exact f.to_simple_func.norm_integral_le_integral_norm f.integrable end /-- The Bochner integral over simple functions in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ₛ[μ] E) →L[ℝ] E := 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 α E _ _ _ _ _ μ _ 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 : α →₁ₛ[μ] ℝ) : f.pos_part.to_simple_func =ᵐ[μ] f.to_simple_func.pos_part := 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], assume a h₁ h₂ h₃, rw [h₁, ← coe_coe, coe_pos_part, h₂, coe_coe, ← h₃] }, refine ae_eq.mono (assume a h, _), rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : f.neg_part.to_simple_func =ᵐ[μ] f.to_simple_func.neg_part := 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], 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₁ : f.to_simple_func.pos_part =ᵐ[μ] (f.pos_part).to_simple_func.map norm, { filter_upwards [pos_part_to_simple_func f], 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₂ : f.to_simple_func.neg_part =ᵐ[μ] (f.neg_part).to_simple_func.map norm, { filter_upwards [neg_part_to_simple_func f], 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₂], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_integral, norm_eq_integral, ← simple_func.integral_sub], { show f.to_simple_func.integral μ = ((f.pos_part.to_simple_func).map norm - f.neg_part.to_simple_func.map norm).integral μ, apply measure_theory.simple_func.integral_congr f.integrable, filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := f.to_simple_func.pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { exact f.integrable.max_zero.congr (measure_theory.simple_func.measurable _) ae_eq₁ }, { exact f.integrable.neg.max_zero.congr (measure_theory.simple_func.measurable _) ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func variables [normed_space ℝ E] [normed_space ℝ F] [complete_space E] section integration_in_l1 local notation `to_l1` := coe_to_l1 α E ℝ 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 : (α →₁[μ] E) →L[ℝ] E := integral_clm.extend to_l1 simple_func.dense_range simple_func.uniform_inducing /-- The Bochner integral in l1 space -/ def integral (f : α →₁[μ] E) : E := integral_clm f lemma integral_eq (f : α →₁[μ] E) : integral f = integral_clm f := rfl @[norm_cast] lemma simple_func.integral_l1_eq_integral (f : α →₁ₛ[μ] E) : integral (f : α →₁[μ] E) = f.integral := uniformly_extend_of_ind simple_func.uniform_inducing simple_func.dense_range simple_func.integral_clm.uniform_continuous _ variables (α E) @[simp] lemma integral_zero : integral (0 : α →₁[μ] E) = 0 := map_zero integral_clm variables {α E} lemma integral_add (f g : α →₁[μ] E) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁[μ] E) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁[μ] E) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (r : ℝ) (f : α →₁[μ] E) : integral (r • f) = r • integral f := map_smul r integral_clm f local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ _ local notation `sIntegral` := @simple_func.integral_clm α E _ _ _ _ _ μ _ 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 : α →₁[μ] E) : ∥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 _ @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), f.integral) := by simp [l1.integral, l1.integral_clm.continuous] 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 E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [normed_space ℝ F] [complete_space F] [measurable_space F] [borel_space F] /-- The Bochner integral -/ def integral (μ : measure α) (f : α → E) : E := if hf : integrable f μ then (l1.of_fun f hf).integral else 0 /-! 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 := integral μ r notation `∫` binders `, ` r:(scoped:60 f, integral volume f) := r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral (measure.restrict μ s) r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, integral (measure.restrict volume s) f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → E} {μ : measure α} lemma integral_eq (f : α → E) (hf : integrable f μ) : ∫ a, f a ∂μ = (l1.of_fun f hf).integral := dif_pos hf lemma l1.integral_eq_integral (f : α →₁[μ] E) : f.integral = ∫ a, f a ∂μ := by rw [integral_eq, l1.of_fun_to_fun] lemma integral_undef (h : ¬ integrable f μ) : ∫ a, f a ∂μ = 0 := dif_neg h lemma integral_non_measurable (h : ¬ measurable f) : ∫ a, f a ∂μ = 0 := integral_undef $ not_and_of_not_left _ h variables (α E) lemma integral_zero : ∫ a : α, (0:E) ∂μ = 0 := by rw [integral_eq, l1.of_fun_zero, l1.integral_zero] @[simp] lemma integral_zero' : integral μ (0 : α → E) = 0 := integral_zero α E variables {α E} lemma integral_add (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a + g a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := by { rw [integral_eq, integral_eq f hf, integral_eq g hg, ← l1.integral_add, ← l1.of_fun_add], refl } lemma integral_add' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f + g) a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := integral_add hf hg lemma integral_neg (f : α → E) : ∫ a, -f a ∂μ = - ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, - f a) hf.neg, ← l1.integral_neg, ← l1.of_fun_neg], refl }, { rw [integral_undef hf, integral_undef, neg_zero], rwa [← integrable_neg_iff] at hf } end lemma integral_neg' (f : α → E) : ∫ a, (-f) a ∂μ = - ∫ a, f a ∂μ := integral_neg f lemma integral_sub (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a - g a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := by { simp only [sub_eq_add_neg, ← integral_neg], exact integral_add hf hg.neg } lemma integral_sub' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f - g) a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := integral_sub hf hg lemma integral_smul (r : ℝ) (f : α → E) : ∫ a, r • (f a) ∂μ = r • ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, 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' : ¬ integrable (λ x, r • f x) μ, { change ¬ integrable (r • f) μ, rwa [integrable_smul_iff hr f] }, 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 : f =ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ := begin by_cases hfi : integrable f μ, { have hgi : integrable g μ := hfi.congr hgm h, rw [integral_eq f hfi, integral_eq g hgi, (l1.of_fun_eq_of_fun f g hfi hgi).2 h] }, { have hgi : ¬ integrable g μ, { rw integrable_congr hfm hgm h at hfi, exact hfi }, rw [integral_undef hfi, integral_undef hgi] }, end @[simp] lemma l1.integral_of_fun_eq_integral {f : α → E} (hf : integrable f μ) : ∫ a, (l1.of_fun f hf) a ∂μ = ∫ a, f a ∂μ := integral_congr_ae (l1.measurable _) hf.measurable (l1.to_fun_of_fun f hf) @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), ∫ a, f a ∂μ) := by { simp only [← l1.integral_eq_integral], exact l1.continuous_integral } lemma norm_integral_le_lintegral_norm (f : α → E) : ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, ← l1.norm_of_fun_eq_lintegral_norm f hf], exact l1.norm_integral_le _ }, { rw [integral_undef hf, norm_zero], exact to_real_nonneg } end lemma ennnorm_integral_le_lintegral_ennnorm (f : α → E) : (nnnorm (∫ a, f a ∂μ) : ennreal) ≤ ∫⁻ a, (nnnorm (f a)) ∂μ := by { simp_rw [← of_real_norm_eq_coe_nnnorm], apply ennreal.of_real_le_of_le_to_real, exact norm_integral_le_lintegral_norm f } lemma integral_eq_zero_of_ae {f : α → E} (hf : f =ᵐ[μ] 0) : ∫ a, f a ∂μ = 0 := if hfm : measurable f then by simp [integral_congr_ae hfm measurable_zero hf, integral_zero] else integral_non_measurable hfm /-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x∂μ`. -/ lemma tendsto_integral_of_l1 {ι} (f : α → E) (hfi : integrable f μ) {F : ι → α → E} {l : filter ι} (hFi : ∀ᶠ i in l, integrable (F i) μ) (hF : tendsto (λ i, ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0)) : tendsto (λ i, ∫ x, F i x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) := begin rw [tendsto_iff_norm_tendsto_zero], replace hF : tendsto (λ i, ennreal.to_real $ ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0) := (ennreal.tendsto_to_real zero_ne_top).comp hF, refine squeeze_zero_norm' (hFi.mp $ hFi.mono $ λ i hFi hFm, _) hF, simp only [norm_norm, ← integral_sub hFi hfi, edist_dist, dist_eq_norm], apply norm_integral_le_lintegral_norm 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 : ℕ → α → E} {f : α → E} (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.has_finite_integral 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) μ := bound_integrable.mono' (F_measurable n) (h_bound _), have h₂ : integrable f μ := ⟨f_measurable, has_finite_integral_of_dominated_convergence bound_integrable.has_finite_integral h_bound h_lim⟩, rw ← integral_sub h₁ 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 : ι → α → E} {f : α → E} (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], 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 : α → ℝ} (hf : 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 hf 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 hf], 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 hf], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], rw [neg_nonneg], exact min_le_right _ _ end, begin rw [eq₁, eq₂, integral, dif_pos], exact l1.integral_eq_norm_pos_part_sub _ end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (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 hfi, have h_min : ∫⁻ a, ennreal.of_real (-min (f a) 0) ∂μ = 0, { rw lintegral_eq_zero_iff, { refine hf.mono _, simp only [pi.zero_apply], assume a h, simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] }, { exact measurable_of_real.comp (measurable_id.neg.comp $ hfm.min measurable_const) } }, have h_max : ∫⁻ a, ennreal.of_real (max (f a) 0) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ, { refine lintegral_congr_ae (hf.mono (λ a h, _)), rw [pi.zero_apply] at h, rw max_eq_left h }, rw [h_min, h_max, zero_to_real, _root_.sub_zero] }, { rw integral_undef hfi, simp_rw [integrable, hfm, has_finite_integral_iff_norm, lt_top_iff_ne_top, ne.def, true_and, not_not] at hfi, have : ∫⁻ (a : α), ennreal.of_real (f a) ∂μ = ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ, { refine lintegral_congr_ae (hf.mono $ assume a h, _), rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) : 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 lintegral_coe_eq_integral (f : α → nnreal) (hfi : integrable (λ x, (f x : real)) μ) : ∫⁻ a, f a ∂μ = ennreal.of_real ∫ a, f a ∂μ := begin simp_rw [integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (λ x, (f x).coe_nonneg)) hfi.measurable, ← ennreal.coe_nnreal_eq], rw [ennreal.of_real_to_real], rw [← lt_top_iff_ne_top], convert hfi.has_finite_integral, ext1 x, rw [real.nnnorm_coe_eq_self] end lemma integral_to_real {f : α → ennreal} (hfm : measurable f) (hf : ∀ᵐ x ∂μ, f x < ⊤) : ∫ a, (f a).to_real ∂μ = (∫⁻ a, f a ∂μ).to_real := begin rw [integral_eq_lintegral_of_nonneg_ae _ hfm.to_real], { rw lintegral_congr_ae, refine hf.mp (eventually_of_forall _), intros x hx, rw [lt_top_iff_ne_top] at hx, simp [hx] }, { exact (eventually_of_forall $ λ x, ennreal.to_real_nonneg) } end lemma integral_nonneg {f : α → ℝ} (hf : 0 ≤ f) : 0 ≤ ∫ a, f a ∂μ := integral_nonneg_of_ae $ eventually_of_forall hf lemma integral_nonpos_of_ae {f : α → ℝ} (hf : f ≤ᵐ[μ] 0) : ∫ a, f a ∂μ ≤ 0 := begin have hf : 0 ≤ᵐ[μ] (-f) := hf.mono (assume a h, by rwa [pi.neg_apply, pi.zero_apply, neg_nonneg]), have : 0 ≤ ∫ a, -f a ∂μ := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_nonpos {f : α → ℝ} (hf : f ≤ 0) : ∫ a, f a ∂μ ≤ 0 := integral_nonpos_of_ae $ eventually_of_forall hf lemma integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := by simp_rw [integral_eq_lintegral_of_nonneg_ae hf hfi.1, ennreal.to_real_eq_zero_iff, lintegral_eq_zero_iff (ennreal.measurable_of_real.comp hfi.1), ← ennreal.not_lt_top, ← has_finite_integral_iff_of_real hf, hfi.2, not_true, or_false, ← hf.le_iff_eq, filter.eventually_eq, filter.eventually_le, (∘), pi.zero_apply, ennreal.of_real_eq_zero] lemma integral_eq_zero_iff_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := integral_eq_zero_iff_of_nonneg_ae (eventually_of_forall hf) hfi lemma integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := by simp_rw [(integral_nonneg_of_ae hf).lt_iff_ne, zero_lt_iff_ne_zero, ne.def, @eq_comm ℝ 0, integral_eq_zero_iff_of_nonneg_ae hf hfi, filter.eventually_eq, ae_iff, pi.zero_apply, function.support] lemma integral_pos_iff_support_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := integral_pos_iff_support_of_nonneg_ae (eventually_of_forall hf) hfi section normed_group variables {H : Type*} [normed_group H] [second_countable_topology H] [measurable_space H] [borel_space H] lemma l1.norm_eq_integral_norm (f : α →₁[μ] H) : ∥f∥ = ∫ a, ∥f a∥ ∂μ := by rw [l1.norm_eq_norm_to_fun, integral_eq_lintegral_of_nonneg_ae (eventually_of_forall $ by simp [norm_nonneg]) (continuous_norm.measurable.comp f.measurable)] lemma l1.norm_of_fun_eq_integral_norm {f : α → H} (hf : integrable f μ) : ∥ l1.of_fun f hf ∥ = ∫ a, ∥f a∥ ∂μ := begin rw l1.norm_eq_integral_norm, refine integral_congr_ae (l1.measurable_norm _) hf.measurable.norm _, apply (l1.to_fun_of_fun f hf).mono, intros a ha, simp [ha] end end normed_group lemma integral_mono_ae {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := le_of_sub_nonneg $ integral_sub hg hf ▸ integral_nonneg_of_ae $ h.mono (λ a, sub_nonneg_of_le) lemma integral_mono {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := integral_mono_ae hf hg $ eventually_of_forall h lemma integral_mono_of_nonneg {f g : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hgi : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := begin by_cases hfm : measurable f, { refine integral_mono_ae ⟨hfm, _⟩ hgi h, refine (hgi.has_finite_integral.mono $ h.mp $ hf.mono $ λ x hf hfg, _), simpa [real.norm_eq_abs, abs_of_nonneg hf, abs_of_nonneg (le_trans hf hfg)] }, { rw [integral_non_measurable hfm], exact integral_nonneg_of_ae (hf.trans h) } end lemma norm_integral_le_integral_norm (f : α → E) : ∥(∫ a, f a ∂μ)∥ ≤ ∫ a, ∥f a∥ ∂μ := have le_ae : ∀ᵐ a ∂μ, 0 ≤ ∥f a∥ := eventually_of_forall (λ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, norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma norm_integral_le_of_norm_le {f : α → E} {g : α → ℝ} (hg : integrable g μ) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ g x) : ∥∫ x, f x ∂μ∥ ≤ ∫ x, g x ∂μ := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ : norm_integral_le_integral_norm f ... ≤ ∫ x, g x ∂μ : integral_mono_of_nonneg (eventually_of_forall $ λ x, norm_nonneg _) hg h lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → E} (hf : ∀ i, integrable (f i) μ) : ∫ a, ∑ i in s, f i a ∂μ = ∑ i in s, ∫ 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 (hf _) (integrable_finset_sum s hf), ih] } end lemma simple_func.integral_eq_integral (f : α →ₛ E) (hfi : integrable f μ) : f.integral μ = ∫ x, f x ∂μ := begin rw [integral_eq f hfi, ← l1.simple_func.of_simple_func_eq_of_fun, l1.simple_func.integral_l1_eq_integral, l1.simple_func.integral_eq_integral], exact simple_func.integral_congr hfi (l1.simple_func.to_simple_func_of_simple_func _ _).symm end @[simp] lemma integral_const (c : E) : ∫ x : α, c ∂μ = (μ univ).to_real • c := begin by_cases hμ : μ univ < ⊤, { haveI : finite_measure μ := ⟨hμ⟩, calc ∫ x : α, c ∂μ = (simple_func.const α c).integral μ : ((simple_func.const α c).integral_eq_integral (integrable_const _)).symm ... = _ : _, rw [simple_func.integral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } }, { by_cases hc : c = 0, { simp [hc, integral_zero] }, { have : ¬integrable (λ x : α, c) μ, { simp only [integrable_const_iff, not_or_distrib], exact ⟨hc, hμ⟩ }, simp only [not_lt, top_le_iff] at hμ, simp [integral_undef, *] } } end lemma norm_integral_le_of_norm_le_const [finite_measure μ] {f : α → E} {C : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : ∥∫ x, f x ∂μ∥ ≤ C * (μ univ).to_real := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, C ∂μ : norm_integral_le_of_norm_le (integrable_const C) h ... = C * (μ univ).to_real : by rw [integral_const, smul_eq_mul, mul_comm] lemma tendsto_integral_approx_on_univ {f : α → E} (hf : integrable f μ) : tendsto (λ n, (simple_func.approx_on f hf.1 univ 0 trivial n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ) := begin have : tendsto (λ n, ∫ x, simple_func.approx_on f hf.1 univ 0 trivial n x ∂μ) at_top (𝓝 $ ∫ x, f x ∂μ) := tendsto_integral_of_l1 _ hf (eventually_of_forall $ simple_func.integrable_approx_on_univ hf) (simple_func.tendsto_approx_on_univ_l1_edist hf), simpa only [simple_func.integral_eq_integral, simple_func.integrable_approx_on_univ hf] end variable {ν : measure α} lemma integral_add_measure {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have hfi := hμ.add_measure hν, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ hfi) _, simpa only [simple_func.integral_add_measure _ (simple_func.integrable_approx_on_univ hfi _)] using (tendsto_integral_approx_on_univ hμ).add (tendsto_integral_approx_on_univ hν) end lemma integral_add_measure' {f : α → E} (hμ : has_finite_integral f μ) (hν : has_finite_integral f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin by_cases hfm : measurable f, { exact integral_add_measure ⟨hfm, hμ⟩ ⟨hfm, hν⟩ }, { simp only [integral_non_measurable hfm, zero_add] } end @[simp] lemma integral_zero_measure (f : α → E) : ∫ x, f x ∂0 = 0 := norm_le_zero_iff.1 $ le_trans (norm_integral_le_lintegral_norm f) $ by simp @[simp] lemma integral_smul_measure (f : α → E) (c : ennreal) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin -- First we consider “degenerate” cases: -- `f` is not measurable by_cases hfm : measurable f, swap, { simp [integral_non_measurable hfm] }, -- `c = 0` rcases (zero_le c).eq_or_lt with rfl|h0, { simp }, -- `c = ⊤` rcases (le_top : c ≤ ⊤).eq_or_lt with rfl|hc, { rw [ennreal.top_to_real, zero_smul], by_cases hf : f =ᵐ[μ] 0, { have : f =ᵐ[⊤ • μ] 0 := ae_smul_measure hf ⊤, exact integral_eq_zero_of_ae this }, { apply integral_undef, rw [integrable, has_finite_integral, iff_true_intro hfm, true_and, lintegral_smul_measure, top_mul, if_neg], { apply lt_irrefl }, { rw [lintegral_eq_zero_iff hfm.ennnorm], refine λ h, hf (h.mono $ λ x, _), simp } } }, -- `f` is not integrable and `0 < c < ⊤` by_cases hfi : integrable f μ, swap, { rw [integral_undef hfi, smul_zero], refine integral_undef (mt (λ h, _) hfi), convert h.smul_measure (ennreal.inv_lt_top.2 h0), rw [smul_smul, ennreal.inv_mul_cancel (ne_of_gt h0) (ne_of_lt hc), one_smul] }, -- Main case: `0 < c < ⊤`, `f` is measurable and integrable refine tendsto_nhds_unique _ (tendsto_const_nhds.smul (tendsto_integral_approx_on_univ hfi)), convert tendsto_integral_approx_on_univ (hfi.smul_measure hc), simp only [simple_func.integral, measure.smul_apply, finset.smul_sum, smul_smul, ennreal.to_real_mul] end lemma integral_map {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : measurable f) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := begin by_cases hfi : integrable f (measure.map φ μ), swap, { rw [integral_undef hfi, integral_undef], rwa [← integrable_map_measure hφ hfm] }, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ hfi) _, convert tendsto_integral_approx_on_univ ((integrable_map_measure hφ hfm).1 hfi), ext1 i, simp only [simple_func.approx_on_comp, simple_func.integral, measure.map_apply, hφ, simple_func.is_measurable_preimage, ← preimage_comp, simple_func.coe_comp], refine (finset.sum_subset (simple_func.range_comp_subset_range _ hφ) (λ y _ hy, _)).symm, rw [simple_func.mem_range, ← set.preimage_singleton_eq_empty, simple_func.coe_comp] at hy, simp [hy] end lemma integral_dirac (f : α → E) (a : α) (hfm : measurable f) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae hfm measurable_const $ eventually_eq_dirac hfm ... = f a : by simp [measure.dirac_apply_of_mem] 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
7ff96ff7d663d3af0de397d5c5eae9139852974b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/subobject/basic.lean
10c301af39121dcd92ed50a103274ba70d7e7c9c
[ "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
24,142
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.subobject.mono_over import category_theory.skeletal import tactic.elementwise import tactic.apply_fun /-! # Subobjects We define `subobject X` as the quotient (by isomorphisms) of `mono_over X := {f : over X // mono f.hom}`. Here `mono_over X` is a thin category (a pair of objects has at most one morphism between them), so we can think of it as a preorder. However as it is not skeletal, it is not a partial order. There is a coercion from `subobject X` back to the ambient category `C` (using choice to pick a representative), and for `P : subobject X`, `P.arrow : (P : C) ⟶ X` is the inclusion morphism. We provide * `def pullback [has_pullbacks C] (f : X ⟶ Y) : subobject Y ⥤ subobject X` * `def map (f : X ⟶ Y) [mono f] : subobject X ⥤ subobject Y` * `def «exists» [has_images C] (f : X ⟶ Y) : subobject X ⥤ subobject Y` and prove their basic properties and relationships. These are all easy consequences of the earlier development of the corresponding functors for `mono_over`. The subobjects of `X` form a preorder making them into a category. We have `X ≤ Y` if and only if `X.arrow` factors through `Y.arrow`: see `of_le`/`of_le_mk`/`of_mk_le`/`of_mk_le_mk` and `le_of_comm`. Similarly, to show that two subobjects are equal, we can supply an isomorphism between the underlying objects that commutes with the arrows (`eq_of_comm`). See also * `category_theory.subobject.factor_thru` : an API describing factorization of morphisms through subobjects. * `category_theory.subobject.lattice` : the lattice structures on subobjects. ## Notes This development originally appeared in Bhavik Mehta's "Topos theory for Lean" repository, and was ported to mathlib by Scott Morrison. ### Implementation note Currently we describe `pullback`, `map`, etc., as functors. It may be better to just say that they are monotone functions, and even avoid using categorical language entirely when describing `subobject X`. (It's worth keeping this in mind in future use; it should be a relatively easy change here if it looks preferable.) ### Relation to pseudoelements There is a separate development of pseudoelements in `category_theory.abelian.pseudoelements`, as a quotient (but not by isomorphism) of `over X`. When a morphism `f` has an image, the image represents the same pseudoelement. In a category with images `pseudoelements X` could be constructed as a quotient of `mono_over X`. In fact, in an abelian category (I'm not sure in what generality beyond that), `pseudoelements X` agrees with `subobject X`, but we haven't developed this in mathlib yet. -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open category_theory category_theory.category category_theory.limits variables {C : Type u₁} [category.{v₁} C] {X Y Z : C} variables {D : Type u₂} [category.{v₂} D] /-! We now construct the subobject lattice for `X : C`, as the quotient by isomorphisms of `mono_over X`. Since `mono_over X` is a thin category, we use `thin_skeleton` to take the quotient. Essentially all the structure defined above on `mono_over X` descends to `subobject X`, with morphisms becoming inequalities, and isomorphisms becoming equations. -/ /-- The category of subobjects of `X : C`, defined as isomorphism classes of monomorphisms into `X`. -/ @[derive [partial_order, category]] def subobject (X : C) := thin_skeleton (mono_over X) namespace subobject /-- Convenience constructor for a subobject. -/ abbreviation mk {X A : C} (f : A ⟶ X) [mono f] : subobject X := (to_thin_skeleton _).obj (mono_over.mk' f) section local attribute [ext] category_theory.comma protected lemma ind {X : C} (p : subobject X → Prop) (h : ∀ ⦃A : C⦄ (f : A ⟶ X) [mono f], by exactI p (subobject.mk f)) (P : subobject X) : p P := begin apply quotient.induction_on', intro a, convert h a.arrow, ext; refl end protected lemma ind₂ {X : C} (p : subobject X → subobject X → Prop) (h : ∀ ⦃A B : C⦄ (f : A ⟶ X) (g : B ⟶ X) [mono f] [mono g], by exactI p (subobject.mk f) (subobject.mk g)) (P Q : subobject X) : p P Q := begin apply quotient.induction_on₂', intros a b, convert h a.arrow b.arrow; ext; refl end end /-- Declare a function on subobjects of `X` by specifying a function on monomorphisms with codomain `X`. -/ protected def lift {α : Sort*} {X : C} (F : Π ⦃A : C⦄ (f : A ⟶ X) [mono f], α) (h : ∀ ⦃A B : C⦄ (f : A ⟶ X) (g : B ⟶ X) [mono f] [mono g] (i : A ≅ B), i.hom ≫ g = f → by exactI F f = F g) : subobject X → α := λ P, quotient.lift_on' P (λ m, by exactI F m.arrow) $ λ m n ⟨i⟩, h m.arrow n.arrow ((mono_over.forget X ⋙ over.forget X).map_iso i) (over.w i.hom) @[simp] protected lemma lift_mk {α : Sort*} {X : C} (F : Π ⦃A : C⦄ (f : A ⟶ X) [mono f], α) {h A} (f : A ⟶ X) [mono f] : subobject.lift F h (subobject.mk f) = F f := rfl /-- The category of subobjects is equivalent to the `mono_over` category. It is more convenient to use the former due to the partial order instance, but oftentimes it is easier to define structures on the latter. -/ noncomputable def equiv_mono_over (X : C) : subobject X ≌ mono_over X := thin_skeleton.equivalence _ /-- Use choice to pick a representative `mono_over X` for each `subobject X`. -/ noncomputable def representative {X : C} : subobject X ⥤ mono_over X := (equiv_mono_over X).functor /-- Starting with `A : mono_over X`, we can take its equivalence class in `subobject X` then pick an arbitrary representative using `representative.obj`. This is isomorphic (in `mono_over X`) to the original `A`. -/ noncomputable def representative_iso {X : C} (A : mono_over X) : representative.obj ((to_thin_skeleton _).obj A) ≅ A := (equiv_mono_over X).counit_iso.app A /-- Use choice to pick a representative underlying object in `C` for any `subobject X`. Prefer to use the coercion `P : C` rather than explicitly writing `underlying.obj P`. -/ noncomputable def underlying {X : C} : subobject X ⥤ C := representative ⋙ mono_over.forget _ ⋙ over.forget _ instance : has_coe (subobject X) C := { coe := λ Y, underlying.obj Y, } @[simp] lemma underlying_as_coe {X : C} (P : subobject X) : underlying.obj P = P := rfl /-- If we construct a `subobject Y` from an explicit `f : X ⟶ Y` with `[mono f]`, then pick an arbitrary choice of underlying object `(subobject.mk f : C)` back in `C`, it is isomorphic (in `C`) to the original `X`. -/ noncomputable def underlying_iso {X Y : C} (f : X ⟶ Y) [mono f] : (subobject.mk f : C) ≅ X := (mono_over.forget _ ⋙ over.forget _).map_iso (representative_iso (mono_over.mk' f)) /-- The morphism in `C` from the arbitrarily chosen underlying object to the ambient object. -/ noncomputable def arrow {X : C} (Y : subobject X) : (Y : C) ⟶ X := (representative.obj Y).obj.hom instance arrow_mono {X : C} (Y : subobject X) : mono (Y.arrow) := (representative.obj Y).property @[simp] lemma arrow_congr {A : C} (X Y : subobject A) (h : X = Y) : eq_to_hom (congr_arg (λ X : subobject A, (X : C)) h) ≫ Y.arrow = X.arrow := by { induction h, simp, } @[simp] lemma representative_coe (Y : subobject X) : (representative.obj Y : C) = (Y : C) := rfl @[simp] lemma representative_arrow (Y : subobject X) : (representative.obj Y).arrow = Y.arrow := rfl @[simp, reassoc] lemma underlying_arrow {X : C} {Y Z : subobject X} (f : Y ⟶ Z) : underlying.map f ≫ arrow Z = arrow Y := over.w (representative.map f) @[simp, reassoc, elementwise] lemma underlying_iso_arrow {X Y : C} (f : X ⟶ Y) [mono f] : (underlying_iso f).inv ≫ (subobject.mk f).arrow = f := over.w _ @[simp, reassoc] lemma underlying_iso_hom_comp_eq_mk {X Y : C} (f : X ⟶ Y) [mono f] : (underlying_iso f).hom ≫ f = (mk f).arrow := (iso.eq_inv_comp _).1 (underlying_iso_arrow f).symm /-- Two morphisms into a subobject are equal exactly if the morphisms into the ambient object are equal -/ @[ext] lemma eq_of_comp_arrow_eq {X Y : C} {P : subobject Y} {f g : X ⟶ P} (h : f ≫ P.arrow = g ≫ P.arrow) : f = g := (cancel_mono P.arrow).mp h lemma mk_le_mk_of_comm {B A₁ A₂ : C} {f₁ : A₁ ⟶ B} {f₂ : A₂ ⟶ B} [mono f₁] [mono f₂] (g : A₁ ⟶ A₂) (w : g ≫ f₂ = f₁) : mk f₁ ≤ mk f₂ := ⟨mono_over.hom_mk _ w⟩ @[simp] lemma mk_arrow (P : subobject X) : mk P.arrow = P := quotient.induction_on' P $ λ Q, begin obtain ⟨e⟩ := @quotient.mk_out' _ (is_isomorphic_setoid _) Q, refine quotient.sound' ⟨mono_over.iso_mk _ _ ≪≫ e⟩; tidy end lemma le_of_comm {B : C} {X Y : subobject B} (f : (X : C) ⟶ (Y : C)) (w : f ≫ Y.arrow = X.arrow) : X ≤ Y := by convert mk_le_mk_of_comm _ w; simp lemma le_mk_of_comm {B A : C} {X : subobject B} {f : A ⟶ B} [mono f] (g : (X : C) ⟶ A) (w : g ≫ f = X.arrow) : X ≤ mk f := le_of_comm (g ≫ (underlying_iso f).inv) $ by simp [w] lemma mk_le_of_comm {B A : C} {X : subobject B} {f : A ⟶ B} [mono f] (g : A ⟶ (X : C)) (w : g ≫ X.arrow = f) : mk f ≤ X := le_of_comm ((underlying_iso f).hom ≫ g) $ by simp [w] /-- To show that two subobjects are equal, it suffices to exhibit an isomorphism commuting with the arrows. -/ @[ext] lemma eq_of_comm {B : C} {X Y : subobject B} (f : (X : C) ≅ (Y : C)) (w : f.hom ≫ Y.arrow = X.arrow) : X = Y := le_antisymm (le_of_comm f.hom w) $ le_of_comm f.inv $ f.inv_comp_eq.2 w.symm /-- To show that two subobjects are equal, it suffices to exhibit an isomorphism commuting with the arrows. -/ @[ext] lemma eq_mk_of_comm {B A : C} {X : subobject B} (f : A ⟶ B) [mono f] (i : (X : C) ≅ A) (w : i.hom ≫ f = X.arrow) : X = mk f := eq_of_comm (i.trans (underlying_iso f).symm) $ by simp [w] /-- To show that two subobjects are equal, it suffices to exhibit an isomorphism commuting with the arrows. -/ @[ext] lemma mk_eq_of_comm {B A : C} {X : subobject B} (f : A ⟶ B) [mono f] (i : A ≅ (X : C)) (w : i.hom ≫ X.arrow = f) : mk f = X := eq.symm $ eq_mk_of_comm _ i.symm $ by rw [iso.symm_hom, iso.inv_comp_eq, w] /-- To show that two subobjects are equal, it suffices to exhibit an isomorphism commuting with the arrows. -/ @[ext] lemma mk_eq_mk_of_comm {B A₁ A₂ : C} (f : A₁ ⟶ B) (g : A₂ ⟶ B) [mono f] [mono g] (i : A₁ ≅ A₂) (w : i.hom ≫ g = f) : mk f = mk g := eq_mk_of_comm _ ((underlying_iso f).trans i) $ by simp [w] /-- An inequality of subobjects is witnessed by some morphism between the corresponding objects. -/ -- We make `X` and `Y` explicit arguments here so that when `of_le` appears in goal statements -- it is possible to see its source and target -- (`h` will just display as `_`, because it is in `Prop`). def of_le {B : C} (X Y : subobject B) (h : X ≤ Y) : (X : C) ⟶ (Y : C) := underlying.map $ h.hom @[simp, reassoc] lemma of_le_arrow {B : C} {X Y : subobject B} (h : X ≤ Y) : of_le X Y h ≫ Y.arrow = X.arrow := underlying_arrow _ instance {B : C} (X Y : subobject B) (h : X ≤ Y) : mono (of_le X Y h) := begin fsplit, intros Z f g w, replace w := w =≫ Y.arrow, ext, simpa using w, end lemma of_le_mk_le_mk_of_comm {B A₁ A₂ : C} {f₁ : A₁ ⟶ B} {f₂ : A₂ ⟶ B} [mono f₁] [mono f₂] (g : A₁ ⟶ A₂) (w : g ≫ f₂ = f₁) : of_le _ _ (mk_le_mk_of_comm g w) = (underlying_iso _).hom ≫ g ≫ (underlying_iso _).inv := by { ext, simp [w], } /-- An inequality of subobjects is witnessed by some morphism between the corresponding objects. -/ @[derive mono] def of_le_mk {B A : C} (X : subobject B) (f : A ⟶ B) [mono f] (h : X ≤ mk f) : (X : C) ⟶ A := of_le X (mk f) h ≫ (underlying_iso f).hom @[simp] lemma of_le_mk_comp {B A : C} {X : subobject B} {f : A ⟶ B} [mono f] (h : X ≤ mk f) : of_le_mk X f h ≫ f = X.arrow := by simp [of_le_mk] /-- An inequality of subobjects is witnessed by some morphism between the corresponding objects. -/ @[derive mono] def of_mk_le {B A : C} (f : A ⟶ B) [mono f] (X : subobject B) (h : mk f ≤ X) : A ⟶ (X : C) := (underlying_iso f).inv ≫ of_le (mk f) X h @[simp] lemma of_mk_le_arrow {B A : C} {f : A ⟶ B} [mono f] {X : subobject B} (h : mk f ≤ X) : of_mk_le f X h ≫ X.arrow = f := by simp [of_mk_le] /-- An inequality of subobjects is witnessed by some morphism between the corresponding objects. -/ @[derive mono] def of_mk_le_mk {B A₁ A₂ : C} (f : A₁ ⟶ B) (g : A₂ ⟶ B) [mono f] [mono g] (h : mk f ≤ mk g) : A₁ ⟶ A₂ := (underlying_iso f).inv ≫ of_le (mk f) (mk g) h ≫ (underlying_iso g).hom @[simp] lemma of_mk_le_mk_comp {B A₁ A₂ : C} {f : A₁ ⟶ B} {g : A₂ ⟶ B} [mono f] [mono g] (h : mk f ≤ mk g) : of_mk_le_mk f g h ≫ g = f := by simp [of_mk_le_mk] @[simp, reassoc] lemma of_le_comp_of_le {B : C} (X Y Z : subobject B) (h₁ : X ≤ Y) (h₂ : Y ≤ Z) : of_le X Y h₁ ≫ of_le Y Z h₂ = of_le X Z (h₁.trans h₂) := by simp [of_le, ←functor.map_comp underlying] @[simp, reassoc] lemma of_le_comp_of_le_mk {B A : C} (X Y : subobject B) (f : A ⟶ B) [mono f] (h₁ : X ≤ Y) (h₂ : Y ≤ mk f) : of_le X Y h₁ ≫ of_le_mk Y f h₂ = of_le_mk X f (h₁.trans h₂) := by simp [of_mk_le, of_le_mk, of_le, ←functor.map_comp_assoc underlying] @[simp, reassoc] lemma of_le_mk_comp_of_mk_le {B A : C} (X : subobject B) (f : A ⟶ B) [mono f] (Y : subobject B) (h₁ : X ≤ mk f) (h₂ : mk f ≤ Y) : of_le_mk X f h₁ ≫ of_mk_le f Y h₂ = of_le X Y (h₁.trans h₂) := by simp [of_mk_le, of_le_mk, of_le, ←functor.map_comp underlying] @[simp, reassoc] lemma of_le_mk_comp_of_mk_le_mk {B A₁ A₂ : C} (X : subobject B) (f : A₁ ⟶ B) [mono f] (g : A₂ ⟶ B) [mono g] (h₁ : X ≤ mk f) (h₂ : mk f ≤ mk g) : of_le_mk X f h₁ ≫ of_mk_le_mk f g h₂ = of_le_mk X g (h₁.trans h₂) := by simp [of_mk_le, of_le_mk, of_le, of_mk_le_mk, ←functor.map_comp_assoc underlying] @[simp, reassoc] lemma of_mk_le_comp_of_le {B A₁ : C} (f : A₁ ⟶ B) [mono f] (X Y : subobject B) (h₁ : mk f ≤ X) (h₂ : X ≤ Y) : of_mk_le f X h₁ ≫ of_le X Y h₂ = of_mk_le f Y (h₁.trans h₂) := by simp [of_mk_le, of_le_mk, of_le, of_mk_le_mk, ←functor.map_comp underlying] @[simp, reassoc] lemma of_mk_le_comp_of_le_mk {B A₁ A₂ : C} (f : A₁ ⟶ B) [mono f] (X : subobject B) (g : A₂ ⟶ B) [mono g] (h₁ : mk f ≤ X) (h₂ : X ≤ mk g) : of_mk_le f X h₁ ≫ of_le_mk X g h₂ = of_mk_le_mk f g (h₁.trans h₂) := by simp [of_mk_le, of_le_mk, of_le, of_mk_le_mk, ←functor.map_comp_assoc underlying] @[simp, reassoc] lemma of_mk_le_mk_comp_of_mk_le {B A₁ A₂ : C} (f : A₁ ⟶ B) [mono f] (g : A₂ ⟶ B) [mono g] (X : subobject B) (h₁ : mk f ≤ mk g) (h₂ : mk g ≤ X) : of_mk_le_mk f g h₁ ≫ of_mk_le g X h₂ = of_mk_le f X (h₁.trans h₂) := by simp [of_mk_le, of_le_mk, of_le, of_mk_le_mk, ←functor.map_comp underlying] @[simp, reassoc] lemma of_mk_le_mk_comp_of_mk_le_mk {B A₁ A₂ A₃ : C} (f : A₁ ⟶ B) [mono f] (g : A₂ ⟶ B) [mono g] (h : A₃ ⟶ B) [mono h] (h₁ : mk f ≤ mk g) (h₂ : mk g ≤ mk h) : of_mk_le_mk f g h₁ ≫ of_mk_le_mk g h h₂ = of_mk_le_mk f h (h₁.trans h₂) := by simp [of_mk_le, of_le_mk, of_le, of_mk_le_mk, ←functor.map_comp_assoc underlying] @[simp] lemma of_le_refl {B : C} (X : subobject B) : of_le X X le_rfl = 𝟙 _ := by { apply (cancel_mono X.arrow).mp, simp } @[simp] lemma of_mk_le_mk_refl {B A₁ : C} (f : A₁ ⟶ B) [mono f] : of_mk_le_mk f f le_rfl = 𝟙 _ := by { apply (cancel_mono f).mp, simp } /-- An equality of subobjects gives an isomorphism of the corresponding objects. (One could use `underlying.map_iso (eq_to_iso h))` here, but this is more readable.) -/ -- As with `of_le`, we have `X` and `Y` as explicit arguments for readability. @[simps] def iso_of_eq {B : C} (X Y : subobject B) (h : X = Y) : (X : C) ≅ (Y : C) := { hom := of_le _ _ h.le, inv := of_le _ _ h.ge, } /-- An equality of subobjects gives an isomorphism of the corresponding objects. -/ @[simps] def iso_of_eq_mk {B A : C} (X : subobject B) (f : A ⟶ B) [mono f] (h : X = mk f) : (X : C) ≅ A := { hom := of_le_mk X f h.le, inv := of_mk_le f X h.ge } /-- An equality of subobjects gives an isomorphism of the corresponding objects. -/ @[simps] def iso_of_mk_eq {B A : C} (f : A ⟶ B) [mono f] (X : subobject B) (h : mk f = X) : A ≅ (X : C) := { hom := of_mk_le f X h.le, inv := of_le_mk X f h.ge, } /-- An equality of subobjects gives an isomorphism of the corresponding objects. -/ @[simps] def iso_of_mk_eq_mk {B A₁ A₂ : C} (f : A₁ ⟶ B) (g : A₂ ⟶ B) [mono f] [mono g] (h : mk f = mk g) : A₁ ≅ A₂ := { hom := of_mk_le_mk f g h.le, inv := of_mk_le_mk g f h.ge, } end subobject open category_theory.limits namespace subobject /-- Any functor `mono_over X ⥤ mono_over Y` descends to a functor `subobject X ⥤ subobject Y`, because `mono_over Y` is thin. -/ def lower {Y : D} (F : mono_over X ⥤ mono_over Y) : subobject X ⥤ subobject Y := thin_skeleton.map F /-- Isomorphic functors become equal when lowered to `subobject`. (It's not as evil as usual to talk about equality between functors because the categories are thin and skeletal.) -/ lemma lower_iso (F₁ F₂ : mono_over X ⥤ mono_over Y) (h : F₁ ≅ F₂) : lower F₁ = lower F₂ := thin_skeleton.map_iso_eq h /-- A ternary version of `subobject.lower`. -/ def lower₂ (F : mono_over X ⥤ mono_over Y ⥤ mono_over Z) : subobject X ⥤ subobject Y ⥤ subobject Z := thin_skeleton.map₂ F @[simp] lemma lower_comm (F : mono_over Y ⥤ mono_over X) : to_thin_skeleton _ ⋙ lower F = F ⋙ to_thin_skeleton _ := rfl /-- An adjunction between `mono_over A` and `mono_over B` gives an adjunction between `subobject A` and `subobject B`. -/ def lower_adjunction {A : C} {B : D} {L : mono_over A ⥤ mono_over B} {R : mono_over B ⥤ mono_over A} (h : L ⊣ R) : lower L ⊣ lower R := thin_skeleton.lower_adjunction _ _ h /-- An equivalence between `mono_over A` and `mono_over B` gives an equivalence between `subobject A` and `subobject B`. -/ @[simps] def lower_equivalence {A : C} {B : D} (e : mono_over A ≌ mono_over B) : subobject A ≌ subobject B := { functor := lower e.functor, inverse := lower e.inverse, unit_iso := begin apply eq_to_iso, convert thin_skeleton.map_iso_eq e.unit_iso, { exact thin_skeleton.map_id_eq.symm }, { exact (thin_skeleton.map_comp_eq _ _).symm }, end, counit_iso := begin apply eq_to_iso, convert thin_skeleton.map_iso_eq e.counit_iso, { exact (thin_skeleton.map_comp_eq _ _).symm }, { exact thin_skeleton.map_id_eq.symm }, end } section pullback variables [has_pullbacks C] /-- When `C` has pullbacks, a morphism `f : X ⟶ Y` induces a functor `subobject Y ⥤ subobject X`, by pulling back a monomorphism along `f`. -/ def pullback (f : X ⟶ Y) : subobject Y ⥤ subobject X := lower (mono_over.pullback f) lemma pullback_id (x : subobject X) : (pullback (𝟙 X)).obj x = x := begin apply quotient.induction_on' x, intro f, apply quotient.sound, exact ⟨mono_over.pullback_id.app f⟩, end lemma pullback_comp (f : X ⟶ Y) (g : Y ⟶ Z) (x : subobject Z) : (pullback (f ≫ g)).obj x = (pullback f).obj ((pullback g).obj x) := begin apply quotient.induction_on' x, intro t, apply quotient.sound, refine ⟨(mono_over.pullback_comp _ _).app t⟩, end instance (f : X ⟶ Y) : faithful (pullback f) := {} end pullback section map /-- We can map subobjects of `X` to subobjects of `Y` by post-composition with a monomorphism `f : X ⟶ Y`. -/ def map (f : X ⟶ Y) [mono f] : subobject X ⥤ subobject Y := lower (mono_over.map f) lemma map_id (x : subobject X) : (map (𝟙 X)).obj x = x := begin apply quotient.induction_on' x, intro f, apply quotient.sound, exact ⟨mono_over.map_id.app f⟩, end lemma map_comp (f : X ⟶ Y) (g : Y ⟶ Z) [mono f] [mono g] (x : subobject X) : (map (f ≫ g)).obj x = (map g).obj ((map f).obj x) := begin apply quotient.induction_on' x, intro t, apply quotient.sound, refine ⟨(mono_over.map_comp _ _).app t⟩, end /-- Isomorphic objects have equivalent subobject lattices. -/ def map_iso {A B : C} (e : A ≅ B) : subobject A ≌ subobject B := lower_equivalence (mono_over.map_iso e) /-- In fact, there's a type level bijection between the subobjects of isomorphic objects, which preserves the order. -/ -- @[simps] here generates a lemma `map_iso_to_order_iso_to_equiv_symm_apply` -- whose left hand side is not in simp normal form. def map_iso_to_order_iso (e : X ≅ Y) : subobject X ≃o subobject Y := { to_fun := (map e.hom).obj, inv_fun := (map e.inv).obj, left_inv := λ g, by simp_rw [← map_comp, e.hom_inv_id, map_id], right_inv := λ g, by simp_rw [← map_comp, e.inv_hom_id, map_id], map_rel_iff' := λ A B, begin dsimp, fsplit, { intro h, apply_fun (map e.inv).obj at h, simp_rw [← map_comp, e.hom_inv_id, map_id] at h, exact h, }, { intro h, apply_fun (map e.hom).obj at h, exact h, }, end } @[simp] lemma map_iso_to_order_iso_apply (e : X ≅ Y) (P : subobject X) : map_iso_to_order_iso e P = (map e.hom).obj P := rfl @[simp] lemma map_iso_to_order_iso_symm_apply (e : X ≅ Y) (Q : subobject Y) : (map_iso_to_order_iso e).symm Q = (map e.inv).obj Q := rfl /-- `map f : subobject X ⥤ subobject Y` is the left adjoint of `pullback f : subobject Y ⥤ subobject X`. -/ def map_pullback_adj [has_pullbacks C] (f : X ⟶ Y) [mono f] : map f ⊣ pullback f := lower_adjunction (mono_over.map_pullback_adj f) @[simp] lemma pullback_map_self [has_pullbacks C] (f : X ⟶ Y) [mono f] (g : subobject X) : (pullback f).obj ((map f).obj g) = g := begin revert g, apply quotient.ind, intro g', apply quotient.sound, exact ⟨(mono_over.pullback_map_self f).app _⟩, end lemma map_pullback [has_pullbacks C] {X Y Z W : C} {f : X ⟶ Y} {g : X ⟶ Z} {h : Y ⟶ W} {k : Z ⟶ W} [mono h] [mono g] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk f g comm)) (p : subobject Y) : (map g).obj ((pullback f).obj p) = (pullback k).obj ((map h).obj p) := begin revert p, apply quotient.ind', intro a, apply quotient.sound, apply thin_skeleton.equiv_of_both_ways, { refine mono_over.hom_mk (pullback.lift pullback.fst _ _) (pullback.lift_snd _ _ _), change _ ≫ a.arrow ≫ h = (pullback.snd ≫ g) ≫ _, rw [assoc, ← comm, pullback.condition_assoc] }, { refine mono_over.hom_mk (pullback.lift pullback.fst (pullback_cone.is_limit.lift' t (pullback.fst ≫ a.arrow) pullback.snd _).1 (pullback_cone.is_limit.lift' _ _ _ _).2.1.symm) _, { rw [← pullback.condition, assoc], refl }, { dsimp, rw [pullback.lift_snd_assoc], apply (pullback_cone.is_limit.lift' _ _ _ _).2.2 } } end end map section «exists» variables [has_images C] /-- The functor from subobjects of `X` to subobjects of `Y` given by sending the subobject `S` to its "image" under `f`, usually denoted $\exists_f$. For instance, when `C` is the category of types, viewing `subobject X` as `set X` this is just `set.image f`. This functor is left adjoint to the `pullback f` functor (shown in `exists_pullback_adj`) provided both are defined, and generalises the `map f` functor, again provided it is defined. -/ def «exists» (f : X ⟶ Y) : subobject X ⥤ subobject Y := lower (mono_over.exists f) /-- When `f : X ⟶ Y` is a monomorphism, `exists f` agrees with `map f`. -/ lemma exists_iso_map (f : X ⟶ Y) [mono f] : «exists» f = map f := lower_iso _ _ (mono_over.exists_iso_map f) /-- `exists f : subobject X ⥤ subobject Y` is left adjoint to `pullback f : subobject Y ⥤ subobject X`. -/ def exists_pullback_adj (f : X ⟶ Y) [has_pullbacks C] : «exists» f ⊣ pullback f := lower_adjunction (mono_over.exists_pullback_adj f) end «exists» end subobject end category_theory
76d226b00a2d60ad3b887875b17f7fb4e6d9a040
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/finset/basic.lean
625cf405e624eb8ba7133c15473043aa33522c78
[ "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
28,642
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 Finite sets. -/ import data.fintype.basic data.nat data.list.perm algebra.binary open nat quot list subtype binary function eq.ops open [decl] perm definition nodup_list (A : Type) := {l : list A | nodup l} variable {A : Type} definition to_nodup_list_of_nodup {l : list A} (n : nodup l) : nodup_list A := tag l n definition to_nodup_list [decidable_eq A] (l : list A) : nodup_list A := @to_nodup_list_of_nodup A (erase_dup l) (nodup_erase_dup l) private definition eqv (l₁ l₂ : nodup_list A) := perm (elt_of l₁) (elt_of l₂) local infix ~ := eqv private definition eqv.refl (l : nodup_list A) : l ~ l := !perm.refl private definition eqv.symm {l₁ l₂ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₁ := perm.symm private definition eqv.trans {l₁ l₂ l₃ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := perm.trans attribute [instance] definition finset.nodup_list_setoid (A : Type) : setoid (nodup_list A) := setoid.mk (@eqv A) (mk_equivalence (@eqv A) (@eqv.refl A) (@eqv.symm A) (@eqv.trans A)) definition finset (A : Type) : Type := quot (finset.nodup_list_setoid A) namespace finset -- give finset notation higher priority than set notation, so that it is tried first protected definition prio : num := num.succ std.priority.default definition to_finset_of_nodup (l : list A) (n : nodup l) : finset A := ⟦to_nodup_list_of_nodup n⟧ definition to_finset [decidable_eq A] (l : list A) : finset A := ⟦to_nodup_list l⟧ lemma to_finset_eq_of_nodup [decidable_eq A] {l : list A} (n : nodup l) : to_finset_of_nodup l n = to_finset l := have P : to_nodup_list_of_nodup n = to_nodup_list l, from begin rewrite [↑to_nodup_list, ↑to_nodup_list_of_nodup], congruence, rewrite [erase_dup_eq_of_nodup n] end, quot.sound (eq.subst P !setoid.refl) attribute [instance] definition has_decidable_eq [decidable_eq A] : decidable_eq (finset A) := λ s₁ s₂, quot.rec_on_subsingleton₂ s₁ s₂ (λ l₁ l₂, match decidable_perm (elt_of l₁) (elt_of l₂) with | decidable.inl e := decidable.inl (quot.sound e) | decidable.inr n := decidable.inr (λ e : ⟦l₁⟧ = ⟦l₂⟧, absurd (quot.exact e) n) end) definition mem (a : A) (s : finset A) : Prop := quot.lift_on s (λ l, a ∈ elt_of l) (λ l₁ l₂ (e : l₁ ~ l₂), propext (iff.intro (λ ainl₁, mem_perm e ainl₁) (λ ainl₂, mem_perm (perm.symm e) ainl₂))) infix [priority finset.prio] ∈ := mem notation [priority finset.prio] a ∉ b := ¬ mem a b theorem mem_of_mem_list {a : A} {l : nodup_list A} : a ∈ elt_of l → a ∈ ⟦l⟧ := λ ainl, ainl theorem mem_list_of_mem {a : A} {l : nodup_list A} : a ∈ ⟦l⟧ → a ∈ elt_of l := λ ainl, ainl attribute [instance] definition decidable_mem [h : decidable_eq A] : ∀ (a : A) (s : finset A), decidable (a ∈ s) := λ a s, quot.rec_on_subsingleton s (λ l, match list.decidable_mem a (elt_of l) with | decidable.inl p := decidable.inl (mem_of_mem_list p) | decidable.inr n := decidable.inr (λ p, absurd (mem_list_of_mem p) n) end) theorem mem_to_finset [decidable_eq A] {a : A} {l : list A} : a ∈ l → a ∈ to_finset l := λ ainl, mem_erase_dup ainl theorem mem_to_finset_of_nodup {a : A} {l : list A} (n : nodup l) : a ∈ l → a ∈ to_finset_of_nodup l n := λ ainl, ainl /- extensionality -/ theorem ext {s₁ s₂ : finset A} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ e, quot.sound (perm_ext (has_property l₁) (has_property l₂) e)) /- empty -/ definition empty : finset A := to_finset_of_nodup [] nodup_nil notation [priority finset.prio] `∅` := !empty attribute [simp] theorem not_mem_empty (a : A) : a ∉ ∅ := λ aine : a ∈ ∅, aine attribute [simp] theorem mem_empty_iff (x : A) : x ∈ ∅ ↔ false := iff_false_intro !not_mem_empty theorem mem_empty_eq (x : A) : x ∈ ∅ = false := propext !mem_empty_iff theorem eq_empty_of_forall_not_mem {s : finset A} (H : ∀x, ¬ x ∈ s) : s = ∅ := ext (take x, iff_false_intro (H x)) /- universe -/ definition univ [h : fintype A] : finset A := to_finset_of_nodup (@fintype.elems A h) (@fintype.unique A h) theorem mem_univ [fintype A] (x : A) : x ∈ univ := fintype.complete x theorem mem_univ_eq [fintype A] (x : A) : x ∈ univ = true := propext (iff_true_intro !mem_univ) /- card -/ definition card (s : finset A) : nat := quot.lift_on s (λ l, length (elt_of l)) (λ l₁ l₂ p, length_eq_length_of_perm p) theorem card_empty : card (@empty A) = 0 := rfl lemma ne_empty_of_card_eq_succ {s : finset A} {n : nat} : card s = succ n → s ≠ ∅ := by intros; substvars; contradiction /- insert -/ section insert variable [h : decidable_eq A] include h definition insert (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (insert a (elt_of l)) (nodup_insert a (has_property l))) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (perm_insert a p)) -- set builder notation notation [priority finset.prio] `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem mem_insert (a : A) (s : finset A) : a ∈ insert a s := quot.induction_on s (λ l : nodup_list A, mem_to_finset_of_nodup _ !list.mem_insert) theorem mem_insert_of_mem {a : A} {s : finset A} (b : A) : a ∈ s → a ∈ insert b s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), mem_to_finset_of_nodup _ (list.mem_insert_of_mem _ ainl)) theorem eq_or_mem_of_mem_insert {x a : A} {s : finset A} : x ∈ insert a s → x = a ∨ x ∈ s := quot.induction_on s (λ l : nodup_list A, λ H, list.eq_or_mem_of_mem_insert H) theorem mem_of_mem_insert_of_ne {x a : A} {s : finset A} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_iff (x a : A) (s : finset A) : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem) theorem mem_insert_eq (x a : A) (s : finset A) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext !mem_insert_iff theorem mem_singleton_iff (x a : A) : x ∈ '{a} ↔ (x = a) := by rewrite [mem_insert_eq, mem_empty_eq, or_false] theorem mem_singleton (a : A) : a ∈ '{a} := mem_insert a ∅ theorem mem_singleton_of_eq {x a : A} (H : x = a) : x ∈ '{a} := by rewrite H; apply mem_insert theorem eq_of_mem_singleton {x a : A} (H : x ∈ '{a}) : x = a := iff.mp !mem_singleton_iff H theorem eq_of_singleton_eq {a b : A} (H : '{a} = '{b}) : a = b := have a ∈ '{b}, by rewrite -H; apply mem_singleton, eq_of_mem_singleton this theorem insert_eq_of_mem {a : A} {s : finset A} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) theorem singleton_ne_empty (a : A) : '{a} ≠ ∅ := begin intro H, apply not_mem_empty a, rewrite -H, apply mem_insert end theorem pair_eq_singleton (a : A) : '{a, a} = '{a} := by rewrite [insert_eq_of_mem !mem_singleton] -- useful in proofs by induction theorem forall_of_forall_insert {P : A → Prop} {a : A} {s : finset A} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x (!mem_insert_of_mem xs) theorem insert.comm (x y : A) (s : finset A) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) theorem card_insert_of_mem {a : A} {s : finset A} : a ∈ s → card (insert a s) = card s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), list.length_insert_of_mem ainl) theorem card_insert_of_not_mem {a : A} {s : finset A} : a ∉ s → card (insert a s) = card s + 1 := quot.induction_on s (λ (l : nodup_list A) (nainl : a ∉ ⟦l⟧), list.length_insert_of_not_mem nainl) theorem card_insert_le (a : A) (s : finset A) : card (insert a s) ≤ card s + 1 := if H : a ∈ s then by rewrite [card_insert_of_mem H]; apply le_succ else by rewrite [card_insert_of_not_mem H] attribute [recursor 6] protected theorem induction {P : finset A → Prop} (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀{s : finset A}, a ∉ s → P s → P (insert a s)) : ∀s, P s := take s, quot.induction_on s (take u, subtype.destruct u (take l, list.induction_on l (assume nodup_l, H1) (take a l', assume IH nodup_al', have aux₁: a ∉ l', from not_mem_of_nodup_cons nodup_al', have e : list.insert a l' = a :: l', from insert_eq_of_not_mem aux₁, have nodup l', from nodup_of_nodup_cons nodup_al', have P (quot.mk (subtype.tag l' this)), from IH this, have P (insert a (quot.mk (subtype.tag l' _))), from H2 aux₁ this, begin revert nodup_al', rewrite [-e], intros, apply this end))) protected theorem induction_on {P : finset A → Prop} (s : finset A) (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀ {s : finset A}, a ∉ s → P s → P (insert a s)) : P s := finset.induction H1 H2 s theorem exists_mem_of_ne_empty {s : finset A} : s ≠ ∅ → ∃ a : A, a ∈ s := begin induction s with a s nin ih, {intro h, exact absurd rfl h}, {intro h, existsi a, apply mem_insert} end theorem eq_empty_of_card_eq_zero {s : finset A} (H : card s = 0) : s = ∅ := begin induction s with a s' H1 IH, { reflexivity }, { rewrite (card_insert_of_not_mem H1) at H, apply nat.no_confusion H} end end insert /- erase -/ section erase variable [h : decidable_eq A] include h definition erase (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (erase a (elt_of l)) (nodup_erase_of_nodup a (has_property l))) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (erase_perm_erase_of_perm a p)) theorem not_mem_erase (a : A) (s : finset A) : a ∉ erase a s := quot.induction_on s (λ l, list.mem_erase_of_nodup _ (has_property l)) theorem card_erase_of_mem {a : A} {s : finset A} : a ∈ s → card (erase a s) = pred (card s) := quot.induction_on s (λ l ainl, list.length_erase_of_mem ainl) theorem card_erase_of_not_mem {a : A} {s : finset A} : a ∉ s → card (erase a s) = card s := quot.induction_on s (λ l nainl, list.length_erase_of_not_mem nainl) theorem erase_empty (a : A) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ≠ a := by intro h beqa; subst b; exact absurd h !not_mem_erase theorem mem_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ∈ s := quot.induction_on s (λ l bin, mem_of_mem_erase bin) theorem mem_erase_of_ne_of_mem {a b : A} {s : finset A} : a ≠ b → a ∈ s → a ∈ erase b s := quot.induction_on s (λ l n ain, list.mem_erase_of_ne_of_mem n ain) theorem mem_erase_iff (a b : A) (s : finset A) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : A) (s : finset A) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext !mem_erase_iff open decidable theorem erase_insert {a : A} {s : finset A} : a ∉ s → erase a (insert a s) = s := λ anins, finset.ext (λ b, by_cases (λ beqa : b = a, iff.intro (λ bin, by subst b; exact absurd bin !not_mem_erase) (λ bin, by subst b; contradiction)) (λ bnea : b ≠ a, iff.intro (λ bin, have b ∈ insert a s, from mem_of_mem_erase bin, mem_of_mem_insert_of_ne this bnea) (λ bin, have b ∈ insert a s, from mem_insert_of_mem _ bin, mem_erase_of_ne_of_mem bnea this))) theorem insert_erase {a : A} {s : finset A} : a ∈ s → insert a (erase a s) = s := λ ains, finset.ext (λ b, by_cases (suppose b = a, iff.intro (λ bin, by subst b; assumption) (λ bin, by subst b; apply mem_insert)) (suppose b ≠ a, iff.intro (λ bin, mem_of_mem_erase (mem_of_mem_insert_of_ne bin `b ≠ a`)) (λ bin, mem_insert_of_mem _ (mem_erase_of_ne_of_mem `b ≠ a` bin)))) end erase /- union -/ section union variable [h : decidable_eq A] include h definition union (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.union (elt_of l₁) (elt_of l₂)) (nodup_union_of_nodup_of_nodup (has_property l₁) (has_property l₂))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_union p₁ p₂)) infix [priority finset.prio] ∪ := union theorem mem_union_left {a : A} {s₁ : finset A} (s₂ : finset A) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁, list.mem_union_left _ ainl₁) theorem mem_union_l {a : A} {s₁ : finset A} {s₂ : finset A} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : A} {s₂ : finset A} (s₁ : finset A) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₂, list.mem_union_right _ ainl₂) theorem mem_union_r {a : A} {s₂ : finset A} {s₁ : finset A} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_or_mem_of_mem_union ainl₁l₂) theorem mem_union_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext !mem_union_iff theorem union_comm (s₁ s₂ : finset A) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext (λ a, by rewrite [*mem_union_eq]; exact or.comm) theorem union_assoc (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext (λ a, by rewrite [*mem_union_eq]; exact or.assoc) theorem union_left_comm (s₁ s₂ s₃ : finset A) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union_comm union_assoc s₁ s₂ s₃ theorem union_self (s : finset A) : s ∪ s = s := ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : finset A) : s ∪ ∅ = s := ext (λ a, iff.intro (suppose a ∈ s ∪ ∅, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i !not_mem_empty)) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : finset A) : ∅ ∪ s = s := calc ∅ ∪ s = s ∪ ∅ : union_comm ... = s : union_empty theorem insert_eq (a : A) (s : finset A) : insert a s = '{a} ∪ s := ext (take x, by rewrite [mem_insert_iff, mem_union_iff, mem_singleton_iff]) theorem insert_union (a : A) (s t : finset A) : insert a (s ∪ t) = insert a s ∪ t := by rewrite [insert_eq, insert_eq a s, union_assoc] end union /- inter -/ section inter variable [h : decidable_eq A] include h definition inter (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.inter (elt_of l₁) (elt_of l₂)) (nodup_inter_of_nodup _ (has_property l₁))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_inter p₁ p₂)) infix [priority finset.prio] ∩ := inter theorem mem_of_mem_inter_left {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_left ainl₁l₂) theorem mem_of_mem_inter_right {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_right ainl₁l₂) theorem mem_inter {a : A} {s₁ s₂ : finset A} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁ ainl₂, list.mem_inter_of_mem_of_mem ainl₁ ainl₂) theorem mem_inter_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext !mem_inter_iff theorem inter_comm (s₁ s₂ : finset A) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext (λ a, by rewrite [*mem_inter_eq]; exact and.comm) theorem inter_assoc (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext (λ a, by rewrite [*mem_inter_eq]; exact and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : finset A) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_self (s : finset A) : s ∩ s = s := ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : finset A) : s ∩ ∅ = ∅ := ext (λ a, iff.intro (suppose a ∈ s ∩ ∅, absurd (mem_of_mem_inter_right this) !not_mem_empty) (suppose a ∈ ∅, absurd this !not_mem_empty)) theorem empty_inter (s : finset A) : ∅ ∩ s = ∅ := calc ∅ ∩ s = s ∩ ∅ : inter_comm ... = ∅ : inter_empty theorem singleton_inter_of_mem {a : A} {s : finset A} (H : a ∈ s) : '{a} ∩ s = '{a} := ext (take x, begin rewrite [mem_inter_eq, !mem_singleton_iff], exact iff.intro (suppose x = a ∧ x ∈ s, and.left this) (suppose x = a, and.intro this (eq.subst (eq.symm this) H)) end) theorem singleton_inter_of_not_mem {a : A} {s : finset A} (H : a ∉ s) : '{a} ∩ s = ∅ := ext (take x, begin rewrite [mem_inter_eq, !mem_singleton_iff, mem_empty_eq], exact iff.intro (suppose x = a ∧ x ∈ s, H (eq.subst (and.left this) (and.right this))) (false.elim) end) end inter /- distributivity laws -/ section inter variable [h : decidable_eq A] include h theorem inter_distrib_left (s t u : finset A) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, by rewrite [mem_inter_eq, *mem_union_eq, *mem_inter_eq]; apply and.left_distrib) theorem inter_distrib_right (s t u : finset A) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, by rewrite [mem_inter_eq, *mem_union_eq, *mem_inter_eq]; apply and.right_distrib) theorem union_distrib_left (s t u : finset A) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, by rewrite [mem_union_eq, *mem_inter_eq, *mem_union_eq]; apply or.left_distrib) theorem union_distrib_right (s t u : finset A) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, by rewrite [mem_union_eq, *mem_inter_eq, *mem_union_eq]; apply or.right_distrib) end inter /- disjoint -/ -- Mainly for internal use; library will use s₁ ∩ s₂ = ∅. Note that it does not require decidable equality. definition disjoint (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, disjoint (elt_of l₁) (elt_of l₂)) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ d₁ a (ainw₁ : a ∈ elt_of w₁), have a ∈ elt_of v₁, from mem_perm (perm.symm p₁) ainw₁, have a ∉ elt_of v₂, from disjoint_left d₁ this, not_mem_perm p₂ this) (λ d₂ a (ainv₁ : a ∈ elt_of v₁), have a ∈ elt_of w₁, from mem_perm p₁ ainv₁, have a ∉ elt_of w₂, from disjoint_left d₂ this, not_mem_perm (perm.symm p₂) this))) theorem disjoint.elim {s₁ s₂ : finset A} {x : A} : disjoint s₁ s₂ → x ∈ s₁ → x ∈ s₂ → false := quot.induction_on₂ s₁ s₂ (take u₁ u₂, assume H H1 H2, H x H1 H2) theorem disjoint.intro {s₁ s₂ : finset A} : (∀{x : A}, x ∈ s₁ → x ∈ s₂ → false) → disjoint s₁ s₂ := quot.induction_on₂ s₁ s₂ (take u₁ u₂, assume H, H) theorem inter_eq_empty_of_disjoint [h : decidable_eq A] {s₁ s₂ : finset A} (H : disjoint s₁ s₂) : s₁ ∩ s₂ = ∅ := ext (take x, iff_false_intro (assume H1, disjoint.elim H (mem_of_mem_inter_left H1) (mem_of_mem_inter_right H1))) theorem disjoint_of_inter_eq_empty [h : decidable_eq A] {s₁ s₂ : finset A} (H : s₁ ∩ s₂ = ∅) : disjoint s₁ s₂ := disjoint.intro (take x H1 H2, have x ∈ s₁ ∩ s₂, from mem_inter H1 H2, !not_mem_empty (eq.subst H this)) theorem disjoint.comm {s₁ s₂ : finset A} : disjoint s₁ s₂ → disjoint s₂ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ d, list.disjoint.comm d) theorem inter_eq_empty [h : decidable_eq A] {s₁ s₂ : finset A} (H : ∀x : A, x ∈ s₁ → x ∈ s₂ → false) : s₁ ∩ s₂ = ∅ := inter_eq_empty_of_disjoint (disjoint.intro H) /- subset -/ definition subset (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, sublist (elt_of l₁) (elt_of l₂)) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ s₁ a i, mem_perm p₂ (s₁ a (mem_perm (perm.symm p₁) i))) (λ s₂ a i, mem_perm (perm.symm p₂) (s₂ a (mem_perm p₁ i))))) infix [priority finset.prio] ⊆ := subset theorem empty_subset (s : finset A) : ∅ ⊆ s := quot.induction_on s (λ l, list.nil_sub (elt_of l)) theorem subset_univ [h : fintype A] (s : finset A) : s ⊆ univ := quot.induction_on s (λ l a i, fintype.complete a) theorem subset.refl (s : finset A) : s ⊆ s := quot.induction_on s (λ l, list.sub.refl (elt_of l)) theorem subset.trans {s₁ s₂ s₃ : finset A} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := quot.induction_on₃ s₁ s₂ s₃ (λ l₁ l₂ l₃ h₁ h₂, list.sub.trans h₁ h₂) theorem mem_of_subset_of_mem {s₁ s₂ : finset A} {a : A} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h₁ h₂, h₁ a h₂) theorem subset.antisymm {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext (take x, iff.intro (assume H, mem_of_subset_of_mem H₁ H) (assume H, mem_of_subset_of_mem H₂ H)) -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : finset A} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ H, H) theorem subset_insert [h : decidable_eq A] (s : finset A) (a : A) : s ⊆ insert a s := subset_of_forall (take x, suppose x ∈ s, mem_insert_of_mem _ this) theorem eq_empty_of_subset_empty {x : finset A} (H : x ⊆ ∅) : x = ∅ := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : finset A) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) section variable [decA : decidable_eq A] include decA theorem erase_subset_erase (a : A) {s t : finset A} (H : s ⊆ t) : erase a s ⊆ erase a t := begin apply subset_of_forall, intro x, rewrite *mem_erase_eq, intro H', show x ∈ t ∧ x ≠ a, from and.intro (mem_of_subset_of_mem H (and.left H')) (and.right H') end theorem erase_subset (a : A) (s : finset A) : erase a s ⊆ s := begin apply subset_of_forall, intro x, rewrite mem_erase_eq, intro H, apply and.left H end theorem erase_eq_of_not_mem {a : A} {s : finset A} (anins : a ∉ s) : erase a s = s := eq_of_subset_of_subset !erase_subset (subset_of_forall (take x, assume xs : x ∈ s, have x ≠ a, from assume H', anins (eq.subst H' xs), mem_erase_of_ne_of_mem this xs)) theorem erase_insert_subset (a : A) (s : finset A) : erase a (insert a s) ⊆ s := decidable.by_cases (assume ains : a ∈ s, by rewrite [insert_eq_of_mem ains]; apply erase_subset) (assume nains : a ∉ s, by rewrite [!erase_insert nains]; apply subset.refl) theorem erase_subset_of_subset_insert {a : A} {s t : finset A} (H : s ⊆ insert a t) : erase a s ⊆ t := subset.trans (!erase_subset_erase H) !erase_insert_subset theorem insert_erase_subset (a : A) (s : finset A) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [!insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, by rewrite[erase_eq_of_not_mem nains]; apply subset_insert) theorem insert_subset_insert (a : A) {s t : finset A} (H : s ⊆ t) : insert a s ⊆ insert a t := begin apply subset_of_forall, intro x, rewrite *mem_insert_eq, intro H', cases H' with [xeqa, xins], exact (or.inl xeqa), exact (or.inr (mem_of_subset_of_mem H xins)) end theorem subset_insert_of_erase_subset {s t : finset A} {a : A} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (!insert_subset_insert H) theorem subset_insert_iff (s t : finset A) (a : A) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro !erase_subset_of_subset_insert !subset_insert_of_erase_subset end /- upto -/ section upto definition upto (n : nat) : finset nat := to_finset_of_nodup (list.upto n) (nodup_upto n) theorem card_upto : ∀ n, card (upto n) = n := list.length_upto theorem lt_of_mem_upto {n a : nat} : a ∈ upto n → a < n := list.lt_of_mem_upto theorem mem_upto_succ_of_mem_upto {n a : nat} : a ∈ upto n → a ∈ upto (succ n) := list.mem_upto_succ_of_mem_upto theorem mem_upto_of_lt {n a : nat} : a < n → a ∈ upto n := list.mem_upto_of_lt theorem mem_upto_iff (a n : nat) : a ∈ upto n ↔ a < n := iff.intro lt_of_mem_upto mem_upto_of_lt theorem mem_upto_eq (a n : nat) : a ∈ upto n = (a < n) := propext !mem_upto_iff end upto theorem upto_zero : upto 0 = ∅ := rfl theorem upto_succ (n : ℕ) : upto (succ n) = upto n ∪ '{n} := begin apply ext, intro x, rewrite [mem_union_iff, *mem_upto_iff, mem_singleton_iff, lt_succ_iff_le, nat.le_iff_lt_or_eq], end /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff {A : Type} (P : A → Prop) : (∃ x, x ∈ ∅ ∧ P x) ↔ false := iff.intro (assume H, obtain x (H1 : x ∈ ∅ ∧ P x), from H, !not_mem_empty (and.left H1)) (assume H, false.elim H) theorem exists_mem_empty_eq {A : Type} (P : A → Prop) : (∃ x, x ∈ ∅ ∧ P x) = false := propext !exists_mem_empty_iff theorem exists_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) ↔ P a ∨ (∃ x, x ∈ s ∧ P x) := iff.intro (assume H, obtain x [H1 H2], from H, or.elim (eq_or_mem_of_mem_insert H1) (suppose x = a, or.inl (eq.subst this H2)) (suppose x ∈ s, or.inr (exists.intro x (and.intro this H2)))) (assume H, or.elim H (suppose P a, exists.intro a (and.intro !mem_insert this)) (suppose ∃ x, x ∈ s ∧ P x, obtain x [H2 H3], from this, exists.intro x (and.intro (!mem_insert_of_mem H2) H3))) theorem exists_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) = (P a ∨ (∃ x, x ∈ s ∧ P x)) := propext !exists_mem_insert_iff theorem forall_mem_empty_iff {A : Type} (P : A → Prop) : (∀ x, x ∈ ∅ → P x) ↔ true := iff.intro (assume H, trivial) (assume H, take x, assume H', absurd H' !not_mem_empty) theorem forall_mem_empty_eq {A : Type} (P : A → Prop) : (∀ x, x ∈ ∅ → P x) = true := propext !forall_mem_empty_iff theorem forall_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) ↔ P a ∧ (∀ x, x ∈ s → P x) := iff.intro (assume H, and.intro (H _ !mem_insert) (take x, assume H', H _ (!mem_insert_of_mem H'))) (assume H, take x, assume H' : x ∈ insert a s, or.elim (eq_or_mem_of_mem_insert H') (suppose x = a, eq.subst (eq.symm this) (and.left H)) (suppose x ∈ s, and.right H _ this)) theorem forall_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) = (P a ∧ (∀ x, x ∈ s → P x)) := propext !forall_mem_insert_iff end finset
9a14e6f87c187cb7394bb305283ab6e2e0d44209
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/init/wf.lean
c6abc70dac1687476c846c4868c53e068b4f901b
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,934
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.wf Author: Leonardo de Moura -/ prelude import init.relation inductive acc {A : Type} (R : A → A → Prop) : A → Prop := intro : ∀x, (∀ y, R y x → acc R y) → acc R x namespace acc variables {A : Type} {R : A → A → Prop} definition inv {x y : A} (H₁ : acc R x) (H₂ : R y x) : acc R y := acc.rec_on H₁ (λ x₁ ac₁ iH H₂, ac₁ y H₂) H₂ end acc inductive well_founded [class] {A : Type} (R : A → A → Prop) : Prop := intro : (∀ a, acc R a) → well_founded R namespace well_founded definition apply [coercion] {A : Type} {R : A → A → Prop} (wf : well_founded R) : ∀a, acc R a := take a, well_founded.rec_on wf (λp, p) a section parameters {A : Type} {R : A → A → Prop} local infix `≺`:50 := R hypothesis [Hwf : well_founded R] theorem recursion {C : A → Type} (a : A) (H : Πx, (Πy, y ≺ x → C y) → C x) : C a := acc.rec_on (Hwf a) (λ x₁ ac₁ iH, H x₁ iH) theorem induction {C : A → Prop} (a : A) (H : ∀x, (∀y, y ≺ x → C y) → C x) : C a := recursion a H variable {C : A → Type} variable F : Πx, (Πy, y ≺ x → C y) → C x definition fix_F (x : A) (a : acc R x) : C x := acc.rec_on a (λ x₁ ac₁ iH, F x₁ iH) theorem fix_F_eq (x : A) (r : acc R x) : fix_F F x r = F x (λ (y : A) (p : y ≺ x), fix_F F y (acc.inv r p)) := have gen : Π r : acc R x, fix_F F x r = F x (λ (y : A) (p : y ≺ x), fix_F F y (acc.inv r p)), from acc.rec_on r (λ x₁ ac iH (r₁ : acc R x₁), -- The proof is straightforward after we replace r₁ with acc.intro (to "unblock" evaluation). calc fix_F F x₁ r₁ = fix_F F x₁ (acc.intro x₁ ac) : proof_irrel r₁ ... = F x₁ (λ y ay, fix_F F y (acc.inv r₁ ay)) : rfl), gen r end variables {A : Type} {C : A → Type} {R : A → A → Prop} -- Well-founded fixpoint definition fix [Hwf : well_founded R] (F : Πx, (Πy, R y x → C y) → C x) (x : A) : C x := fix_F F x (Hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fix_eq [Hwf : well_founded R] (F : Πx, (Πy, R y x → C y) → C x) (x : A) : fix F x = F x (λy h, fix F y) := calc -- The proof is straightforward, it just uses fix_F_eq and proof irrelevance fix F x = F x (λy h, fix_F F y (acc.inv (Hwf x) h)) : fix_F_eq F x (Hwf x) ... = F x (λy h, fix F y) : rfl -- proof irrelevance is used here end well_founded open well_founded -- Empty relation is well-founded definition empty.wf {A : Type} : well_founded empty_relation := well_founded.intro (λ (a : A), acc.intro a (λ (b : A) (lt : false), false.rec _ lt)) -- Subrelation of a well-founded relation is well-founded namespace subrelation section parameters {A : Type} {R Q : A → A → Prop} parameters (H₁ : subrelation Q R) parameters (H₂ : well_founded R) definition accessible {a : A} (ac : acc R a) : acc Q a := acc.rec_on ac (λ (x : A) (ax : _) (iH : ∀ (y : A), R y x → acc Q y), acc.intro x (λ (y : A) (lt : Q y x), iH y (H₁ lt))) definition wf : well_founded Q := well_founded.intro (λ a, accessible (H₂ a)) end end subrelation -- The inverse image of a well-founded relation is well-founded namespace inv_image section parameters {A B : Type} {R : B → B → Prop} parameters (f : A → B) parameters (H : well_founded R) definition accessible {a : A} (ac : acc R (f a)) : acc (inv_image R f) a := have gen : ∀x, f x = f a → acc (inv_image R f) x, from acc.rec_on ac (λx acx (iH : ∀y, R y x → (∀z, f z = y → acc (inv_image R f) z)) (z : A) (eq₁ : f z = x), acc.intro z (λ (y : A) (lt : R (f y) (f z)), iH (f y) (eq.rec_on eq₁ lt) y rfl)), gen a rfl definition wf : well_founded (inv_image R f) := well_founded.intro (λ a, accessible (H (f a))) end end inv_image -- The transitive closure of a well-founded relation is well-founded namespace tc section parameters {A : Type} {R : A → A → Prop} local notation `R⁺` := tc R definition accessible {z} (ac: acc R z) : acc R⁺ z := acc.rec_on ac (λ x acx (iH : ∀y, R y x → acc R⁺ y), acc.intro x (λ (y : A) (lt : R⁺ y x), have gen : x = x → acc R⁺ y, from tc.rec_on lt (λa b (H : R a b) (Heq : b = x), iH a (eq.rec_on Heq H)) (λa b c (H₁ : R⁺ a b) (H₂ : R⁺ b c) (iH₁ : b = x → acc R⁺ a) (iH₂ : c = x → acc R⁺ b) (Heq : c = x), acc.inv (iH₂ Heq) H₁), gen rfl)) definition wf (H : well_founded R) : well_founded R⁺ := well_founded.intro (λ a, accessible (H a)) end end tc
7a73f5bfe2c78672e046ab412d95725e4946b9d9
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/filter/extr.lean
6ca0a533ada0731959a82b86f9ddfcc460c6a5a1
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
20,886
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import order.filter.basic /-! # Minimum and maximum w.r.t. a filter and on a aet ## Main Definitions This file defines six predicates of the form `is_A_B`, where `A` is `min`, `max`, or `extr`, and `B` is `filter` or `on`. * `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a`; * `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a`; * `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a`. Similar predicates with `_on` suffix are particular cases for `l = 𝓟 s`. ## Main statements ### Change of the filter (set) argument * `is_*_filter.filter_mono` : replace the filter with a smaller one; * `is_*_filter.filter_inf` : replace a filter `l` with `l ⊓ l'`; * `is_*_on.on_subset` : restrict to a smaller set; * `is_*_on.inter` : replace a set `s` wtih `s ∩ t`. ### Composition * `is_*_*.comp_mono` : if `x` is an extremum for `f` and `g` is a monotone function, then `x` is an extremum for `g ∘ f`; * `is_*_*.comp_antimono` : similarly for the case of monotonically decreasing `g`; * `is_*_*.bicomp_mono` : if `x` is an extremum of the same type for `f` and `g` and a binary operation `op` is monotone in both arguments, then `x` is an extremum of the same type for `λ x, op (f x) (g x)`. * `is_*_filter.comp_tendsto` : if `g x` is an extremum for `f` w.r.t. `l'` and `tendsto g l l'`, then `x` is an extremum for `f ∘ g` w.r.t. `l`. * `is_*_on.on_preimage` : if `g x` is an extremum for `f` on `s`, then `x` is an extremum for `f ∘ g` on `g ⁻¹' s`. ### Algebraic operations * `is_*_*.add` : if `x` is an extremum of the same type for two functions, then it is an extremum of the same type for their sum; * `is_*_*.neg` : if `x` is an extremum for `f`, then it is an extremum of the opposite type for `-f`; * `is_*_*.sub` : if `x` is an a minimum for `f` and a maximum for `g`, then it is a minimum for `f - g` and a maximum for `g - f`; * `is_*_*.max`, `is_*_*.min`, `is_*_*.sup`, `is_*_*.inf` : similarly for `is_*_*.add` for pointwise `max`, `min`, `sup`, `inf`, respectively. ### Miscellaneous definitions * `is_*_*_const` : any point is both a minimum and maximum for a constant function; * `is_min/max_*.is_ext` : any minimum/maximum point is an extremum; * `is_*_*.dual`, `is_*_*.undual`: conversion between codomains `α` and `dual α`; ## Missing features (TODO) * Multiplication and division; * `is_*_*.bicompl` : if `x` is a minimum for `f`, `y` is a minimum for `g`, and `op` is a monotone binary operation, then `(x, y)` is a minimum for `uncurry (bicompl op f g)`. From this point of view, `is_*_*.bicomp` is a composition * It would be nice to have a tactic that specializes `comp_(anti)mono` or `bicomp_mono` based on a proof of monotonicity of a given (binary) function. The tactic should maintain a `meta` list of known (anti)monotone (binary) functions with their names, as well as a list of special types of filters, and define the missing lemmas once one of these two lists grows. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} open set filter open_locale filter section preorder variables [preorder β] [preorder γ] variables (f : α → β) (s : set α) (l : filter α) (a : α) /-! ### Definitions -/ /-- `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a` -/ def is_min_filter : Prop := ∀ᶠ x in l, f a ≤ f x /-- `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a` -/ def is_max_filter : Prop := ∀ᶠ x in l, f x ≤ f a /-- `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a` -/ def is_extr_filter : Prop := is_min_filter f l a ∨ is_max_filter f l a /-- `is_min_on f s a` means that `f a ≤ f x` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/ def is_min_on := is_min_filter f (𝓟 s) a /-- `is_max_on f s a` means that `f x ≤ f a` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/ def is_max_on := is_max_filter f (𝓟 s) a /-- `is_extr_on f s a` means `is_min_on f s a` or `is_max_on f s a` -/ def is_extr_on : Prop := is_extr_filter f (𝓟 s) a variables {f s a l} {t : set α} {l' : filter α} lemma is_extr_on.elim {p : Prop} : is_extr_on f s a → (is_min_on f s a → p) → (is_max_on f s a → p) → p := or.elim lemma is_min_on_iff : is_min_on f s a ↔ ∀ x ∈ s, f a ≤ f x := iff.rfl lemma is_max_on_iff : is_max_on f s a ↔ ∀ x ∈ s, f x ≤ f a := iff.rfl lemma is_min_on_univ_iff : is_min_on f univ a ↔ ∀ x, f a ≤ f x := univ_subset_iff.trans eq_univ_iff_forall lemma is_max_on_univ_iff : is_max_on f univ a ↔ ∀ x, f x ≤ f a := univ_subset_iff.trans eq_univ_iff_forall /-! ### Conversion to `is_extr_*` -/ lemma is_min_filter.is_extr : is_min_filter f l a → is_extr_filter f l a := or.inl lemma is_max_filter.is_extr : is_max_filter f l a → is_extr_filter f l a := or.inr lemma is_min_on.is_extr (h : is_min_on f s a) : is_extr_on f s a := h.is_extr lemma is_max_on.is_extr (h : is_max_on f s a) : is_extr_on f s a := h.is_extr /-! ### Constant function -/ lemma is_min_filter_const {b : β} : is_min_filter (λ _, b) l a := univ_mem_sets' $ λ _, le_refl _ lemma is_max_filter_const {b : β} : is_max_filter (λ _, b) l a := univ_mem_sets' $ λ _, le_refl _ lemma is_extr_filter_const {b : β} : is_extr_filter (λ _, b) l a := is_min_filter_const.is_extr lemma is_min_on_const {b : β} : is_min_on (λ _, b) s a := is_min_filter_const lemma is_max_on_const {b : β} : is_max_on (λ _, b) s a := is_max_filter_const lemma is_extr_on_const {b : β} : is_extr_on (λ _, b) s a := is_extr_filter_const /-! ### Order dual -/ lemma is_min_filter_dual_iff : @is_min_filter α (order_dual β) _ f l a ↔ is_max_filter f l a := iff.rfl lemma is_max_filter_dual_iff : @is_max_filter α (order_dual β) _ f l a ↔ is_min_filter f l a := iff.rfl lemma is_extr_filter_dual_iff : @is_extr_filter α (order_dual β) _ f l a ↔ is_extr_filter f l a := or_comm _ _ alias is_min_filter_dual_iff ↔ is_min_filter.undual is_max_filter.dual alias is_max_filter_dual_iff ↔ is_max_filter.undual is_min_filter.dual alias is_extr_filter_dual_iff ↔ is_extr_filter.undual is_extr_filter.dual lemma is_min_on_dual_iff : @is_min_on α (order_dual β) _ f s a ↔ is_max_on f s a := iff.rfl lemma is_max_on_dual_iff : @is_max_on α (order_dual β) _ f s a ↔ is_min_on f s a := iff.rfl lemma is_extr_on_dual_iff : @is_extr_on α (order_dual β) _ f s a ↔ is_extr_on f s a := or_comm _ _ alias is_min_on_dual_iff ↔ is_min_on.undual is_max_on.dual alias is_max_on_dual_iff ↔ is_max_on.undual is_min_on.dual alias is_extr_on_dual_iff ↔ is_extr_on.undual is_extr_on.dual /-! ### Operations on the filter/set -/ lemma is_min_filter.filter_mono (h : is_min_filter f l a) (hl : l' ≤ l) : is_min_filter f l' a := hl h lemma is_max_filter.filter_mono (h : is_max_filter f l a) (hl : l' ≤ l) : is_max_filter f l' a := hl h lemma is_extr_filter.filter_mono (h : is_extr_filter f l a) (hl : l' ≤ l) : is_extr_filter f l' a := h.elim (λ h, (h.filter_mono hl).is_extr) (λ h, (h.filter_mono hl).is_extr) lemma is_min_filter.filter_inf (h : is_min_filter f l a) (l') : is_min_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_max_filter.filter_inf (h : is_max_filter f l a) (l') : is_max_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_extr_filter.filter_inf (h : is_extr_filter f l a) (l') : is_extr_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_min_on.on_subset (hf : is_min_on f t a) (h : s ⊆ t) : is_min_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_max_on.on_subset (hf : is_max_on f t a) (h : s ⊆ t) : is_max_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_extr_on.on_subset (hf : is_extr_on f t a) (h : s ⊆ t) : is_extr_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_min_on.inter (hf : is_min_on f s a) (t) : is_min_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_max_on.inter (hf : is_max_on f s a) (t) : is_max_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_extr_on.inter (hf : is_extr_on f s a) (t) : is_extr_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) /-! ### Composition with (anti)monotone functions -/ lemma is_min_filter.comp_mono (hf : is_min_filter f l a) {g : β → γ} (hg : monotone g) : is_min_filter (g ∘ f) l a := mem_sets_of_superset hf $ λ x hx, hg hx lemma is_max_filter.comp_mono (hf : is_max_filter f l a) {g : β → γ} (hg : monotone g) : is_max_filter (g ∘ f) l a := mem_sets_of_superset hf $ λ x hx, hg hx lemma is_extr_filter.comp_mono (hf : is_extr_filter f l a) {g : β → γ} (hg : monotone g) : is_extr_filter (g ∘ f) l a := hf.elim (λ hf, (hf.comp_mono hg).is_extr) (λ hf, (hf.comp_mono hg).is_extr) lemma is_min_filter.comp_antimono (hf : is_min_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_max_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_max_filter.comp_antimono (hf : is_max_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_min_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_extr_filter.comp_antimono (hf : is_extr_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_extr_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_min_on.comp_mono (hf : is_min_on f s a) {g : β → γ} (hg : monotone g) : is_min_on (g ∘ f) s a := hf.comp_mono hg lemma is_max_on.comp_mono (hf : is_max_on f s a) {g : β → γ} (hg : monotone g) : is_max_on (g ∘ f) s a := hf.comp_mono hg lemma is_extr_on.comp_mono (hf : is_extr_on f s a) {g : β → γ} (hg : monotone g) : is_extr_on (g ∘ f) s a := hf.comp_mono hg lemma is_min_on.comp_antimono (hf : is_min_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_max_on (g ∘ f) s a := hf.comp_antimono hg lemma is_max_on.comp_antimono (hf : is_max_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_min_on (g ∘ f) s a := hf.comp_antimono hg lemma is_extr_on.comp_antimono (hf : is_extr_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_extr_on (g ∘ f) s a := hf.comp_antimono hg lemma is_min_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_min_filter f l a) {g : α → γ} (hg : is_min_filter g l a) : is_min_filter (λ x, op (f x) (g x)) l a := mem_sets_of_superset (inter_mem_sets hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx lemma is_max_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_max_filter f l a) {g : α → γ} (hg : is_max_filter g l a) : is_max_filter (λ x, op (f x) (g x)) l a := mem_sets_of_superset (inter_mem_sets hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx -- No `extr` version because we need `hf` and `hg` to be of the same kind lemma is_min_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_min_on f s a) {g : α → γ} (hg : is_min_on g s a) : is_min_on (λ x, op (f x) (g x)) s a := hf.bicomp_mono hop hg lemma is_max_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_max_on f s a) {g : α → γ} (hg : is_max_on g s a) : is_max_on (λ x, op (f x) (g x)) s a := hf.bicomp_mono hop hg /-! ### Composition with `tendsto` -/ lemma is_min_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_min_filter f l (g b)) (hg : tendsto g l' l) : is_min_filter (f ∘ g) l' b := hg hf lemma is_max_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_max_filter f l (g b)) (hg : tendsto g l' l) : is_max_filter (f ∘ g) l' b := hg hf lemma is_extr_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_extr_filter f l (g b)) (hg : tendsto g l' l) : is_extr_filter (f ∘ g) l' b := hf.elim (λ hf, (hf.comp_tendsto hg).is_extr) (λ hf, (hf.comp_tendsto hg).is_extr) lemma is_min_on.on_preimage (g : δ → α) {b : δ} (hf : is_min_on f s (g b)) : is_min_on (f ∘ g) (g ⁻¹' s) b := hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _) lemma is_max_on.on_preimage (g : δ → α) {b : δ} (hf : is_max_on f s (g b)) : is_max_on (f ∘ g) (g ⁻¹' s) b := hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _) lemma is_extr_on.on_preimage (g : δ → α) {b : δ} (hf : is_extr_on f s (g b)) : is_extr_on (f ∘ g) (g ⁻¹' s) b := hf.elim (λ hf, (hf.on_preimage g).is_extr) (λ hf, (hf.on_preimage g).is_extr) end preorder /-! ### Pointwise addition -/ section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.add (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x + g x) l a := show is_min_filter (λ x, f x + g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg lemma is_max_filter.add (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x + g x) l a := show is_max_filter (λ x, f x + g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg lemma is_min_on.add (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x + g x) s a := hf.add hg lemma is_max_on.add (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x + g x) s a := hf.add hg end ordered_add_comm_monoid /-! ### Pointwise negation and subtraction -/ section ordered_add_comm_group variables [ordered_add_comm_group β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.neg (hf : is_min_filter f l a) : is_max_filter (λ x, -f x) l a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_max_filter.neg (hf : is_max_filter f l a) : is_min_filter (λ x, -f x) l a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_extr_filter.neg (hf : is_extr_filter f l a) : is_extr_filter (λ x, -f x) l a := hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr) lemma is_min_on.neg (hf : is_min_on f s a) : is_max_on (λ x, -f x) s a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_max_on.neg (hf : is_max_on f s a) : is_min_on (λ x, -f x) s a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_extr_on.neg (hf : is_extr_on f s a) : is_extr_on (λ x, -f x) s a := hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr) lemma is_min_filter.sub (hf : is_min_filter f l a) (hg : is_max_filter g l a) : is_min_filter (λ x, f x - g x) l a := hf.add hg.neg lemma is_max_filter.sub (hf : is_max_filter f l a) (hg : is_min_filter g l a) : is_max_filter (λ x, f x - g x) l a := hf.add hg.neg lemma is_min_on.sub (hf : is_min_on f s a) (hg : is_max_on g s a) : is_min_on (λ x, f x - g x) s a := hf.add hg.neg lemma is_max_on.sub (hf : is_max_on f s a) (hg : is_min_on g s a) : is_max_on (λ x, f x - g x) s a := hf.add hg.neg end ordered_add_comm_group /-! ### Pointwise `sup`/`inf` -/ section semilattice_sup variables [semilattice_sup β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.sup (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x ⊔ g x) l a := show is_min_filter (λ x, f x ⊔ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg lemma is_max_filter.sup (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x ⊔ g x) l a := show is_max_filter (λ x, f x ⊔ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg lemma is_min_on.sup (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x ⊔ g x) s a := hf.sup hg lemma is_max_on.sup (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x ⊔ g x) s a := hf.sup hg end semilattice_sup section semilattice_inf variables [semilattice_inf β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.inf (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x ⊓ g x) l a := show is_min_filter (λ x, f x ⊓ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg lemma is_max_filter.inf (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x ⊓ g x) l a := show is_max_filter (λ x, f x ⊓ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg lemma is_min_on.inf (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x ⊓ g x) s a := hf.inf hg lemma is_max_on.inf (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x ⊓ g x) s a := hf.inf hg end semilattice_inf /-! ### Pointwise `min`/`max` -/ section linear_order variables [linear_order β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.min (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, min (f x) (g x)) l a := show is_min_filter (λ x, min (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg lemma is_max_filter.min (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, min (f x) (g x)) l a := show is_max_filter (λ x, min (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg lemma is_min_on.min (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, min (f x) (g x)) s a := hf.min hg lemma is_max_on.min (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, min (f x) (g x)) s a := hf.min hg lemma is_min_filter.max (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, max (f x) (g x)) l a := show is_min_filter (λ x, max (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg lemma is_max_filter.max (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, max (f x) (g x)) l a := show is_max_filter (λ x, max (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg lemma is_min_on.max (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, max (f x) (g x)) s a := hf.max hg lemma is_max_on.max (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, max (f x) (g x)) s a := hf.max hg end linear_order section eventually /-! ### Relation with `eventually` comparisons of two functions -/ lemma filter.eventually_le.is_max_filter {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (hle : g ≤ᶠ[l] f) (hfga : f a = g a) (h : is_max_filter f l a) : is_max_filter g l a := begin refine hle.mp (h.mono $ λ x hf hgf, _), rw ← hfga, exact le_trans hgf hf end lemma is_max_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_max_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_max_filter g l a := heq.symm.le.is_max_filter hfga h lemma filter.eventually_eq.is_max_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_max_filter f l a ↔ is_max_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ lemma filter.eventually_le.is_min_filter {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (hle : f ≤ᶠ[l] g) (hfga : f a = g a) (h : is_min_filter f l a) : is_min_filter g l a := @filter.eventually_le.is_max_filter _ (order_dual β) _ _ _ _ _ hle hfga h lemma is_min_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_min_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_min_filter g l a := heq.le.is_min_filter hfga h lemma filter.eventually_eq.is_min_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_min_filter f l a ↔ is_min_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ lemma is_extr_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_extr_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_extr_filter g l a := begin rw is_extr_filter at *, rwa [← heq.is_max_filter_iff hfga, ← heq.is_min_filter_iff hfga], end lemma filter.eventually_eq.is_extr_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_extr_filter f l a ↔ is_extr_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ end eventually
960fa9aee7373030c0a8e71fbff9bed44ae39d24
5ee26964f602030578ef0159d46145dd2e357ba5
/src/Huber_ring/localization.lean
ba50d637d6505fb2610885fe831f0305d0f7d9a9
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
15,606
lean
import ring_theory.localization import tactic.tidy import tactic.ring import Huber_ring.basic import for_mathlib.topological_rings import for_mathlib.algebra import for_mathlib.submodule import for_mathlib.subgroup import for_mathlib.nonarchimedean.basic import for_mathlib.group universes u v local attribute [instance, priority 0] classical.prop_decidable local attribute [instance] set.pointwise_mul_comm_semiring namespace Huber_ring open localization algebra topological_ring submodule set topological_add_group variables {A : Type u} [comm_ring A] [topological_space A ] [topological_ring A] variables (T : set A) (s : A) /- Our goal is to define a topology on (away s), which is the localization of A at s. This topology will depend on T, and should not depend on the ring of definition. In the literature, this ring is commonly denoted with A(T/s) to indicate the dependence on T. For the same reason, we start by defining a wrapper type that includes T in its assumptions. -/ /--The localization at `s`, endowed with a topology that depends on `T`-/ def away (T : set A) (s : A) := away s local notation `ATs` := away T s namespace away instance : comm_ring ATs := by delta away; apply_instance instance : module A ATs := by delta away; apply_instance instance : algebra A ATs := by delta away; apply_instance instance : has_coe A ATs := ⟨λ a, (of_id A ATs : A → ATs) a⟩ /--An auxiliary subring, used to define the topology on `away T s`-/ def D.aux : set ATs := let s_inv : ATs := ((to_units ⟨s, ⟨1, by simp⟩⟩)⁻¹ : units ATs) in ring.closure (s_inv • of_id A ATs '' T) local notation `D` := D.aux T s instance : is_subring D := by delta D.aux; apply_instance local notation `Dspan` U := span D (of_id A ATs '' (U : set A)) /- To put a topology on `away T s` we want to use the construction `topology_of_submodules_comm` which needs a directed family of submodules of `ATs = away T s` viewed as `D`-algebra. This directed family has two satisfy two extra conditions. Proving these two conditions takes up the beef of this file. Initially we only assume that `A` is a nonarchimedean ring, but towards the end we need to strengthen this assumption to Huber ring. -/ set_option class.instance_max_depth 50 /-The submodules spanned by the open subgroups of `A` form a directed family-/ lemma directed (U₁ U₂ : open_add_subgroup A) : ∃ (U : open_add_subgroup A), (Dspan U) ≤ (Dspan U₁) ⊓ (Dspan U₂) := begin use U₁ ⊓ U₂, apply lattice.le_inf _ _; rw span_le; refine subset.trans (image_subset _ _) subset_span, { apply inter_subset_left }, { apply inter_subset_right }, end /-For every open subgroup `U` of `A` and every `a : A`, there exists an open subgroup `V` of `A`, such that `a • (span D V)` is contained in the `D`-span of `U`.-/ lemma exists_mul_left_subset (h : nonarchimedean A) (U : open_add_subgroup A) (a : A) : ∃ V : open_add_subgroup A, (a : ATs) • (Dspan V) ≤ (Dspan U) := begin cases h _ _ with V hV, use V, work_on_goal 0 { erw [smul_singleton, ← span_image, span_le, ← image_comp, ← algebra.map_lmul_left, image_comp], refine subset.trans (image_subset (of_id A ATs : A → ATs) _) subset_span, rw image_subset_iff, exact hV }, apply mem_nhds_sets (continuous_mul_left _ _ U.is_open), { rw [mem_preimage_eq, mul_zero], apply is_add_submonoid.zero_mem } end /-For every open subgroup `U` of `A`, there exists an open subgroup `V` of `A`, such that the multiplication map sends the `D`-span of `V` into the `D`-span of `U`.-/ lemma mul_le (h : nonarchimedean A) (U : open_add_subgroup A) : ∃ (V : open_add_subgroup A), (Dspan V) * (Dspan V) ≤ (Dspan U) := begin rcases nonarchimedean.mul_subset h U with ⟨V, hV⟩, use V, rw span_mul_span, apply span_mono, rw ← is_semiring_hom.map_mul (image (of_id A ATs : A → ATs)), exact image_subset _ hV, end lemma K.aux (L : finset A) (h : (↑L : set A) ⊆ ideal.span T) : ∃ (K : finset A), (↑L : set A) ⊆ (↑(span ℤ (T * ↑K)) : set A) := begin delta ideal.span at h, erw span_eq_map_lc at h, choose s hs using finset.subset_image_iff.mp h, use s.bind (λ f, f.frange), rcases hs with ⟨hs, rfl⟩, intros l hl, rcases finset.mem_image.mp hl with ⟨f, hf, rfl⟩, apply submodule.sum_mem_span, intros t ht, refine ⟨t, _, _, _, mul_comm _ _⟩, { replace hf := hs hf, erw lc.mem_supported at hf, exact hf ht }, { erw [linear_map.id_apply, finset.mem_bind], use [f, hf], erw finsupp.mem_support_iff at ht, erw finsupp.mem_frange, exact ⟨ht, ⟨t, rfl⟩⟩ } end end away end Huber_ring namespace Huber_ring open localization algebra topological_ring submodule set topological_add_group variables {A : Type u} [Huber_ring A] variables (T : set A) (s : A) namespace away local notation `ATs` := away T s local notation `D` := D.aux T s local notation `Dspan` U := span D (of_id A ATs '' (U : set A)) set_option class.instance_max_depth 80 /- Wedhorn 6.20 for n = 1-/ lemma mul_T_open (hT : is_open (↑(ideal.span T) : set A)) (U : open_add_subgroup A) : is_open (↑(T • span ℤ (U : set A)) : set A) := begin -- Choose an ideal I ⊆ span T rcases exists_pod_subset _ (mem_nhds_sets hT $ ideal.zero_mem $ ideal.span T) with ⟨A₀, _, _, _, ⟨_, emb, hf, I, fg, top⟩, hI⟩, resetI, dsimp only at hI, -- Choose a generating set L ⊆ I cases fg with L hL, rw ← hL at hI, -- Observe L ⊆ span T have Lsub : (↑(L.image (to_fun A)) : set A) ⊆ ↑(ideal.span T) := by { rw finset.coe_image, exact set.subset.trans (image_subset _ subset_span) hI }, -- Choose a finite set K such that L ⊆ span (T * K) cases K.aux _ _ Lsub with K hK, -- Choose V such that K * V ⊆ U let nonarch := Huber_ring.nonarchimedean, let V := K.inf (λ k : A, classical.some (nonarch.left_mul_subset U k)), cases (is_ideal_adic_iff I).mp top with H₁ H₂, have hV : ↑K * (V : set A) ⊆ U, { rintros _ ⟨k, hk, v, hv, rfl⟩, apply classical.some_spec (nonarch.left_mul_subset U k), refine ⟨k, set.mem_singleton _, v, _, rfl⟩, apply (finset.inf_le hk : V ≤ _), exact hv }, replace hV : span ℤ _ ≤ span ℤ _ := span_mono hV, erw [← span_mul_span, ← submodule.smul_def] at hV, -- Choose m such that I^m ⊆ V cases H₂ _ (mem_nhds_sets (emb.continuous _ V.is_open) _) with m hm, work_on_goal 1 { erw [mem_preimage_eq, is_ring_hom.map_zero (to_fun A)], { exact V.zero_mem }, apply_instance }, rw ← image_subset_iff at hm, erw [← add_subgroup_eq_spanℤ (V : set A), ← add_subgroup_eq_spanℤ (↑(I^m) : set A₀)] at hm, change (submodule.map (alg_hom_int $ to_fun A).to_linear_map _) ≤ _ at hm, work_on_goal 1 {apply_instance}, -- It suffices to provide an open subgroup apply @open_add_subgroup.is_open_of_open_add_subgroup A _ _ _ _ (submodule.submodule_is_add_subgroup _), refine ⟨⟨to_fun A '' ↑(I^(m+1)), _, _⟩, _⟩, work_on_goal 2 {assumption}, all_goals { try {apply_instance} }, { exact embedding_open emb hf (H₁ _) }, -- And now we start a long calculation -- Unfortunately it seems to be hard to express in calc mode -- First observe: I^(m+1) = L • I^m as A₀-ideal, but also as ℤ-submodule erw [subtype.coe_mk, pow_succ, ← hL, ← submodule.smul_def, hL, smul_eq_smul_spanℤ], change (submodule.map (alg_hom_int $ to_fun A).to_linear_map _) ≤ _, work_on_goal 1 {apply_instance}, -- Now we map the above equality through the canonical map A₀ → A erw [submodule.map_mul, ← span_image, ← submodule.smul_def], erw [finset.coe_image] at hK, -- Next observe: L • I^m ≤ (T * K) • V refine le_trans (smul_le_smul hK hm) _, -- Also observe: T • (K • V) ≤ T • U refine (le_trans (le_of_eq _) (smul_le_smul (le_refl T) hV)), change span _ _ * _ = _, erw [span_span, ← mul_smul], refl end set_option class.instance_max_depth 80 lemma mul_left.aux₁ (hT : is_open (↑(ideal.span T) : set A)) (U : open_add_subgroup A) : ∃ (V : open_add_subgroup A), (↑((to_units ⟨s, ⟨1, pow_one s⟩⟩)⁻¹ : units ATs) : ATs) • (Dspan ↑V) ≤ Dspan ↑U := begin refine ⟨⟨_, mul_T_open _ hT U, by apply_instance⟩, _⟩, erw [subtype.coe_mk (↑(T • span ℤ ↑U) : set A), @submodule.smul_def ℤ, span_mul_span], change _ • span _ ↑(submodule.map (alg_hom_int $ (of_id A ATs : A → ATs)).to_linear_map _) ≤ _, erw [← span_image, span_spanℤ, submodule.smul_def, span_mul_span, span_le], rintros _ ⟨s_inv, hs_inv, tu, htu, rfl⟩, erw mem_image at htu, rcases htu with ⟨_, ⟨t, ht, u, hu, rfl⟩, rfl⟩, rw submodule.mem_coe, convert (span _ _).smul_mem _ _ using 1, work_on_goal 3 { exact subset_span ⟨u, hu, rfl⟩ }, work_on_goal 1 { constructor }, work_on_goal 0 { change s_inv * (algebra_map _ _) = _ • (algebra_map _ _), rw [algebra.map_mul, ← mul_assoc], congr }, { apply ring.mem_closure, exact ⟨s_inv, hs_inv, _, ⟨t, ht, rfl⟩, rfl⟩ } end lemma mul_left.aux₂ (hT : is_open (↑(ideal.span T) : set A)) (s' : powers s) (U : open_add_subgroup A) : ∃ (V : open_add_subgroup A), (↑((to_units s')⁻¹ : units ATs) : ATs) • (Dspan (V : set A)) ≤ Dspan (U : set A) := begin rcases s' with ⟨_, ⟨n, rfl⟩⟩, induction n with k hk, { use U, simp only [pow_zero], change (1 : ATs) • _ ≤ _, rw one_smul, exact le_refl _ }, cases hk with W hW, cases mul_left.aux₁ T s hT W with V hV, use V, refine le_trans _ hW, refine le_trans (le_of_eq _) (smul_le_smul (le_refl _) hV), change _ = (_ : ATs) • _, rw ← mul_smul, congr' 1, change ⟦((1 : A), _)⟧ = ⟦(1 * 1, _)⟧, simpa [pow_succ'], end lemma mul_left (hT : is_open (↑(ideal.span T) : set A)) (a : ATs) (U : open_add_subgroup A) : ∃ (V : open_add_subgroup A), a • (Dspan (V : set A)) ≤ Dspan (U : set A) := begin apply localization.induction_on a, intros a' s', clear a, cases mul_left.aux₂ _ _ hT s' U with W hW, cases exists_mul_left_subset T s Huber_ring.nonarchimedean W a' with V hV, use V, erw [localization.mk_eq, mul_comm, mul_smul], exact le_trans (smul_le_smul (le_refl _) hV) hW end lemma is_basis (hT : is_open (↑(ideal.span T) : set A)) : is_subgroups_basis (λ U : open_add_subgroup A, (span D (of_id A ATs '' U.1) : set ATs)) := is_subgroups_basis.of_submodules_comm _ (directed T s) (mul_left T s hT) (mul_le T s Huber_ring.nonarchimedean) def ring_with_nhds (hT : is_open (↑(ideal.span T) : set A)) : ring_with_zero_nhd ATs := @is_subgroups_basis.to_ring_with_zero_nhd ATs _ _ _ (λ U : open_add_subgroup A, (span D (of_id A ATs '' U.1) : set ATs)) (away.is_basis T s hT) def top_space (hT : is_open (↑(ideal.span T) : set A)) : topological_space ATs := @ring_with_zero_nhd.topological_space ATs (ring_with_nhds T s hT) section variables {B : Type*} [comm_ring B] [topological_space B] [topological_ring B] variables (hB : nonarchimedean B) {f : A → B} [is_ring_hom f] (hf : continuous f) variables {fs_inv : units B} (hs : fs_inv.inv = f s) variables (hT : is_open (↑(ideal.span T) : set A)) variables (hTB : is_power_bounded_subset ((↑fs_inv : B) • f '' T)) include hs lemma is_unit : is_unit (f s) := by rw [← hs, ← units.coe_inv]; exact is_unit_unit _ noncomputable def lift : ATs → B := localization.away.lift f (is_unit s hs) instance : is_ring_hom (lift T s hs : ATs → B) := localization.away.lift.is_ring_hom f _ @[simp] lemma lift_of (a : A) : lift T s hs (of a) = f a := localization.away.lift_of _ _ _ @[simp] lemma lift_coe (a : A) : lift T s hs a = f a := localization.away.lift_of _ _ _ @[simp] lemma lift_comp_of : lift T s hs ∘ of = f := localization.lift'_comp_of _ _ _ -- TODO: this has nothing to do with lift so should perhaps be elsewhere -- (because KMB keeps confusing it with the next lemma ;-)) lemma of_continuous (hT : is_open (↑(ideal.span T) : set A)) : @continuous _ _ _ (away.top_space T s hT) (of : A → ATs) := begin apply is_subgroups_basis.continuous_into _, all_goals {try {apply_instance}}, intro U, apply open_add_subgroup.is_open_of_open_add_subgroup _, all_goals {try {apply_instance}}, { use U, rw ← image_subset_iff, exact subset_span }, { apply is_add_group_hom.preimage _ _, all_goals {apply_instance} } end include hB hf hT hTB lemma lift_continuous : @continuous _ _ (away.top_space T s hT) _ (lift T s hs) := begin apply continuous_of_continuous_at_zero _ _, all_goals {try {apply_instance}}, apply is_subgroups_basis.is_topological_add_group, intros U hU, rw is_ring_hom.map_zero (lift T s hs) at hU, rw filter.mem_map_sets_iff, let hF := power_bounded.ring.closure' hB _ hTB, erw is_bounded_add_subgroup_iff hB at hF, rcases hF U hU with ⟨V, hVF⟩, let hV := V.mem_nhds_zero, rw ← is_ring_hom.map_zero f at hV, replace hV := hf.tendsto 0 hV, rw filter.mem_map_sets_iff at hV, rcases hV with ⟨W, hW, hWV⟩, cases Huber_ring.nonarchimedean W hW with Y hY, refine ⟨↑(Dspan Y), _, _⟩, { apply mem_nhds_sets, { convert is_subgroups_basis.is_op _ Y }, { exact (Dspan ↑Y).zero_mem } }, { refine set.subset.trans _ hVF, rintros _ ⟨x, hx, rfl⟩, apply span_induction hx, { rintros _ ⟨a, ha, rfl⟩, erw [lift_of, ← mul_one (f a)], refine mul_mem_mul (subset_span $ hWV $ ⟨a, hY ha, rfl⟩) (subset_span $ is_submonoid.one_mem _) }, { rw is_ring_hom.map_zero (lift T s hs), exact is_add_submonoid.zero_mem _ }, { intros a b ha hb, rw is_ring_hom.map_add (lift T s hs), exact is_add_submonoid.add_mem ha hb }, { rw [submodule.smul_def, span_mul_span], intros d a ha, rw [(show d • a = ↑d * a, from rfl), is_ring_hom.map_mul (lift T s hs), mul_comm], rcases mem_span_iff_lc.mp ha with ⟨l, hl₁, hl₂⟩, rw lc.mem_supported at hl₁, rw [← hl₂, lc.total_apply] at ha ⊢, rw finsupp.sum_mul, apply sum_mem_span, intros b hb', show (↑(_ : ℤ) * _) * _ ∈ _, rcases hl₁ hb' with ⟨v, hv, b, hb, rfl⟩, refine ⟨↑(l (v * b)) * v, _, b * lift T s hs ↑d, _, _⟩, { rw ← gsmul_eq_mul, exact is_add_subgroup.gsmul_mem hv }, { refine is_submonoid.mul_mem hb _, cases d with d hd, rw subtype.coe_mk, apply ring.in_closure.rec_on hd, { rw is_ring_hom.map_one (lift T s hs), exact is_submonoid.one_mem _ }, { rw [is_ring_hom.map_neg (lift T s hs), is_ring_hom.map_one (lift T s hs)], exact is_add_subgroup.neg_mem (is_submonoid.one_mem _) }, { rintros _ ⟨sinv, hsinv, _, ⟨t, ht, rfl⟩, rfl⟩ b hb, rw is_ring_hom.map_mul (lift T s hs), refine is_submonoid.mul_mem _ hb, apply ring.mem_closure, erw [is_ring_hom.map_mul (lift T s hs), lift_of], refine ⟨_, _, _, ⟨t, ht, rfl⟩, rfl⟩, rw mem_singleton_iff at hsinv ⊢, subst hsinv, erw [← units.coe_map (lift T s hs), ← units.ext_iff, is_group_hom.map_inv (units.map _), inv_eq_iff_inv_eq, units.ext_iff, units.coe_inv, hs], { symmetry, exact lift_of T s hs s }, { apply_instance } }, { intros a b ha hb, rw is_ring_hom.map_add (lift T s hs), exact is_add_submonoid.add_mem ha hb } }, { repeat {rw mul_assoc} } } } end end end away end Huber_ring
9617a86bd542846422a8936d72178f03b4b2570b
88892181780ff536a81e794003fe058062f06758
/src/logic_and_proof/exercises.lean
82fd417090f7a4f782c3f9f7e7156af1a6a6bda3
[]
no_license
AtnNn/lean-sandbox
fe2c44280444e8bb8146ab8ac391c82b480c0a2e
8c68afbdc09213173aef1be195da7a9a86060a97
refs/heads/master
1,623,004,395,876
1,579,969,507,000
1,579,969,507,000
146,666,368
0
0
null
null
null
null
UTF-8
Lean
false
false
8,200
lean
-- § 4.7 section variables A B C D : Prop example : A ∧ (A → B) → B := λ ⟨a, f⟩, f a example : A → ¬(¬A ∧ B) := λ a ⟨f, b⟩, f a example : ¬ (A ∧ B) → (A → ¬B) := λ f a b, f ⟨a, b⟩ example (h₁ : A ∨ B) (h₂ : A → C) (h₃ : B → D) : C ∨ D := h₁.cases_on (or.inl ∘ h₂) (or.inr ∘ h₃) example (h : ¬A ∧ ¬B) : ¬(A ∨ B) := let ⟨f, g⟩ := h in λ ab, ab.cases_on f g lemma t : ¬ (A ↔ ¬A) := λ ⟨f, g⟩, let a := g (λ a, f a a) in f a a end -- § 5.3 section variables {A B C D : Prop} example : (A ∨ ¬A) → (¬¬A → A) := λ d f, d.cases_on id (false.rec _ ∘ f) variable em : ∀ {p : Prop}, p ∨ ¬p variable by_contradiction : ∀ {p : Prop}, ¬¬p → p example : ¬A ∨ ¬B → ¬(A ∧ B) := λ d ⟨a, b⟩, d.cases_on (λ f, f a) (λ f, f b) example : ¬(A ∧ B) → ¬A ∨ ¬B := λ f, em.cases_on (λ a, or.inr (λ b, f ⟨a, b⟩)) (λ f, or.inl (λ a, f a)) example : (A → B) → ¬A ∨ B := λ f, em.cases_on (or.inr ∘ f) or.inl lemma step1 (h₁ : ¬(A ∧ B)) (h₂ : A) : ¬A ∨ ¬B := have ¬B, from λ b, h₁ ⟨h₂, b⟩, show ¬A ∨ ¬B, from or.inr this lemma step2 (h₁ : ¬(A ∧ B)) (h₂ : ¬(¬A ∨ ¬B)) : false := have ¬A, from assume : A, have ¬A ∨ ¬B, from (step1 h₁ ‹A›), show false, from h₂ this, show false, from h₂ (or.inl ‹¬A›) theorem step3 (h : ¬(A ∧ B)) : ¬A ∨ ¬B := by_contradiction (assume h' : ¬(¬A ∨ ¬B), show false, from step2 h h') example (h : ¬B → ¬A) : A → B := λ a, by_contradiction (λ f, h f a) example (h : A → B) : ¬A ∨ B := em.cases_on (or.inr ∘ h) or.inl end -- § 8.6 section variables {T : Type} {A B C : T → Prop} {even odd : T → Prop} {s : T → T} example : (∀ x, A x → B x) → ((∀ x, A x) → (∀ x, B x)) := λ f g x, f x (g x) example : (∀ x, A x ∨ B x) → (∀ y, ¬(A y)) → (∀ x, B x) := λ f g x, (f x).cases_on (false.rec _ ∘ g x) id example (h₁ : ∀ x, even x ∨ odd x) (h₂ : ∀ x, odd x → even (s x)) : ∀ x, even x ∨ even (s x) := λ x, (h₁ x).cases_on or.inl (or.inr ∘ h₂ x) example : (∃ x, A x) ∨ (∃ x, B x) → ∃ x, (A x ∨ B x) := λ d, d.cases_on (λ ⟨x, p⟩, (⟨x, or.inl p⟩ : ∃ x, (A x ∨ B x))) (λ ⟨x, p⟩, ⟨x, or.inr p⟩) example (h₁ : ∃ x, A x ∧ B x) (h₂ : ∀ x, A x ∧ B x → C x) : (∃ x, A x ∧ C x) := let ⟨x, ⟨a, b⟩⟩ := h₁ in ⟨x, ⟨a, h₂ x ⟨a, b⟩⟩⟩ variables {politician : T → Prop} {trusts : T → T → Prop} example : (∀ x y, politician x → ¬(trusts y x)) ↔ (∀ x y, trusts y x → ¬(politician x)) := ⟨λ f x y t p, f x y p t, λ f x y p t, f x y t p⟩ variables {person : Type} {young healthy likes_baseball active : person → Prop} example (h₁ : ∀ p, young p ∧ healthy p → likes_baseball p) (h₂ : ∀ p, active p → healthy p) (h₃ : ∃ p, young p ∧ active p) : ∃ p, likes_baseball p := let ⟨p, ⟨y, a⟩⟩ := h₃ in ⟨p, h₁ p ⟨y, h₂ p a⟩⟩ end section variables {T : Type} {f : T → T} {P : T → Prop} variable {refl : ∀ {t : T}, t = t} variable {symm : ∀ {s t : T}, s = t → t = s} variable {trans : ∀ {r s t : T}, r = s → s = t → r = t} variable {congr : ∀ {s t : T}, s = t → f s = f t} variable {subst : ∀ {s t : T}, s = t → P s → P t} example : ∀ {x y z : T}, x = z → y = z → x = y := λ x y z xz yz, trans xz (symm yz) end section variables {T : Type} example (h₁ : ∀ (x : T), x = x) (h₂ : ∀ (u v w : T), u = w → v = w → u = v) : ∀ x y, (x = y → y = x) := λ x y xy, h₂ _ _ _ (h₁ y) xy end section variables {T: Type} {x : T} {A B : T → Prop} example : ¬(∃x, A x ∧ B x) ↔ (∀x, A x → ¬(B x)) := ⟨λ f x a b, (f ⟨x, ⟨a, b⟩⟩).elim, λ f ⟨x, ⟨a, b⟩⟩, f x a b⟩ open classical example : ¬(∀x, A x) → ∃x, ¬(A x) := λ f, by_contradiction (λ g, f (λ x, by_contradiction (λ h, g ⟨x, h⟩))) example : ¬(∀x, A x → B x) ↔ (∃x, A x ∧ ¬(B x)) := ⟨λ f, by_contradiction (λ g, f (λ x a, (by_contradiction (λ h, g ⟨x, ⟨a, h⟩⟩) : B x))), λ ⟨x, ⟨a, f⟩⟩ g, (f (g x a)).elim⟩ variables {f : T → T} {P : T → Prop} variable {refl : ∀ {t : T}, t = t} variable {symm : ∀ {s t : T}, s = t → t = s} variable {trans : ∀ {r s t : T}, r = s → s = t → r = t} variable {congr : ∀ {s t : T}, s = t → f s = f t} variable {subst : ∀ {s t : T}, s = t → P s → P t} def L (P : T → Prop) := ∃ (x : T), P x ∧ ∀ y, P y → y = x def R (P : T → Prop) := ∃ (x : T), P x ∧ ∀ y y', P y ∧ P y' → y = y' example : L A → R A := λ ⟨x, ax, f⟩, ⟨x, ax, (λ y y' ⟨ay, ay'⟩, trans (f y ay) (symm (f y' ay')))⟩ example : R A → L A := λ ⟨x, ax, f⟩, ⟨x, ax, λ y ay, f y x ⟨ay, ax⟩⟩ end -- § 9.5 section variable A : Type variable f : A → A variable P : A → Prop variable h : ∀ x, P x → P (f x) example : ∀ y, P y → P (f (f y)) := λ _ py, h _ (h _ py). end section variable U : Type variables A B : U → Prop example : (∀ x, A x ∧ B x) → ∀ x, A x := λ f x, (f x).elim_left end section variable U : Type variables A B C : U → Prop variable h1 : ∀ x, A x ∨ B x variable h2 : ∀ x, A x → C x variable h3 : ∀ x, B x → C x example : ∀ x, C x := λ x, (h1 x).elim (h2 x) (h3 x) end section variable not_iff_not_self (P : Prop) : ¬ (P ↔ ¬ P) variable Person : Type variable shaves : Person → Person → Prop variable barber : Person variable h : ∀ x, shaves barber x ↔ ¬ shaves x x example : false := not_iff_not_self _ (h barber) end section variable U : Type variables A B : U → Prop example : (∃ x, A x) → ∃ x, A x ∨ B x := λ ⟨x, a⟩, ⟨x, or.inl a⟩ end section variable U : Type variables A B : U → Prop variable h1 : ∀ x, A x → B x variable h2 : ∃ x, A x example : ∃ x, B x := let ⟨x, a⟩ := h2 in ⟨x, h1 x a⟩ end section variable U : Type variables A B C : U → Prop example (h1 : ∃ x, A x ∧ B x) (h2 : ∀ x, B x → C x) : ∃ x, A x ∧ C x := let ⟨x, a, b⟩ := h1 in ⟨x, a, h2 x b⟩ end section variable U : Type variables A B C : U → Prop example : (¬ ∃ x, A x) → ∀ x, ¬ A x := λ f x a, f ⟨x, a⟩ example : (∀ x, ¬ A x) → ¬ ∃ x, A x := λ f ⟨x, a⟩, f x a end section variable U : Type variables R : U → U → Prop example : (∃ x, ∀ y, R x y) → ∀ y, ∃ x, R x y := λ ⟨x, f⟩ y, ⟨x, f y⟩ end section theorem foo {A : Type} {a b c : A} : a = b → c = b → a = c := λ h₁ h₂, eq.symm h₂ ▸ h₁ section variable {A : Type} variables {a b c : A} -- replace the sorry with a proof, using foo and rfl, without using eq.symm. theorem my_symm (h : b = a) : a = b := foo rfl h -- now use foo, rfl, and my_symm to prove transitivity theorem my_trans (h1 : a = b) (h2 : b = c) : a = c := foo h1 (my_symm h2) end end -- § 10.6 section variables {T : Type} (R : T → T → Prop) def has_min := ∃x, ∀y, R x y def has_max := ∃y, ∀x, R x y def has_between := ∀ x y, R x y ∧ x ≠ y → ∃ z, R x z ∧ R z y ∧ x ≠ z ∧ y ≠ z #print nat.less_than_or_equal lemma not_succ_le {x : ℕ} : ¬(nat.succ x ≤ x) := λ le, begin induction x, { cases le }, { exact x_ih (nat.pred_le_pred le) } end #check nat.less_than_or_equal.rec_on universe u def double : ℕ → ℕ := nat.rec 0 (λ (n m : ℕ), nat.succ (nat.succ m)) #reduce double 7 lemma nat_le_rec_on {a b : ℕ} {T : Type} {P : ℕ → Prop} (le : a ≤ b) (x : T) : (T → P a) → (T → ∀ ⦃b : ℕ⦄, nat.less_than_or_equal a b → P b → P (nat.succ b)) → P b := λ h₁ h₂, nat.less_than_or_equal.rec_on le (h₁ x) (h₂ x) lemma not_succ_le' {x : ℕ} : ¬(nat.succ x ≤ x) := λ le, nat_le_rec_on le x (λ x, _) (λ b le' x, _) example : has_min nat.le := ⟨0, λ x, x.rec_on (nat.less_than_or_equal.refl _) (λ n h, nat.less_than_or_equal.step h)⟩ example : ¬has_max nat.le := λ ⟨y, f⟩, not_succ_le (f (nat.succ y)) end
9beec09ea939dea6fbdf9b74e5b03b0343d4d276
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/logic/embedding.lean
8553ca4321720986883de75981ea6f65a2c766c7
[ "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
15,337
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.equiv.basic import data.sigma.basic /-! # Injective functions -/ universes u v w x namespace function /-- `α ↪ β` is a bundled injective function. -/ @[nolint has_inhabited_instance] -- depending on cardinalities, an injective function may not exist structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj' : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := ⟨_, embedding.to_fun⟩ initialize_simps_projections embedding (to_fun → apply) end function section equiv variables {α : Sort u} {β : Sort v} (f : α ≃ β) /-- Convert an `α ≃ β` to `α ↪ β`. This is also available as a coercion `equiv.coe_embedding`. The explicit `equiv.to_embedding` version is preferred though, since the coercion can have issues inferring the type of the resulting embedding. For example: ```lean -- Works: example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f.to_embedding = s.map f := by simp -- Error, `f` has type `fin 3 ≃ fin 3` but is expected to have type `fin 3 ↪ ?m_1 : Type ?` example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f = s.map f.to_embedding := by simp ``` -/ @[simps] protected def equiv.to_embedding : α ↪ β := ⟨f, f.injective⟩ instance equiv.coe_embedding : has_coe (α ≃ β) (α ↪ β) := ⟨equiv.to_embedding⟩ @[reducible] instance equiv.perm.coe_embedding : has_coe (equiv.perm α) (α ↪ α) := equiv.coe_embedding @[simp] lemma equiv.coe_eq_to_embedding : ↑f = f.to_embedding := rfl /-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding set. -/ @[simps] def equiv.as_embedding {p : β → Prop} (e : α ≃ subtype p) : α ↪ β := ⟨coe ∘ e, subtype.coe_injective.comp e.injective⟩ @[simp] lemma equiv.as_embedding_range {α β : Sort*} {p : β → Prop} (e : α ≃ subtype p) : set.range e.as_embedding = set_of p := set.ext $ λ x, ⟨λ ⟨y, h⟩, h ▸ subtype.coe_prop (e y), λ hs, ⟨e.symm ⟨x, hs⟩, by simp⟩⟩ end equiv namespace function namespace embedding lemma coe_injective {α β} : @function.injective (α ↪ β) (α → β) coe_fn | ⟨x, _⟩ ⟨y, _⟩ rfl := rfl @[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := coe_injective (funext h) lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := ⟨ext, λ h _, by rw h⟩ @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl @[simp] lemma mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f := by { ext, simp } theorem injective {α β} (f : α ↪ β) : injective f := f.inj' @[simp] lemma apply_eq_iff_eq {α β : Type*} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y := f.injective.eq_iff @[refl, simps {simp_rhs := tt}] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ @[trans, simps {simp_rhs := tt}] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.injective.comp f.injective⟩ @[simp] lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) : e.to_embedding.trans e.symm.to_embedding = embedding.refl _ := by { ext, simp, } @[simp] lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) : e.symm.to_embedding.trans e.to_embedding = embedding.refl _ := by { ext, simp, } protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ /-- Convert a surjective `embedding` to an `equiv` -/ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective f ⟨f.injective, hf⟩ /-- There is always an embedding from an empty type. --/ protected def of_is_empty {α β} [is_empty α] : α ↪ β := ⟨is_empty_elim, is_empty_elim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : α ↪ β := ⟨λ a', if a' = a then b else if f a' = b then f a else f a', begin intros x y h, dsimp at h, split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : set_value f a b a = b := by simp [set_value] /-- Embedding into `option` -/ protected def some {α} : α ↪ option α := ⟨some, option.some_injective α⟩ /-- Embedding of a `subtype`. -/ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨coe, λ _ _, subtype.ext_val⟩ @[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort*} (b : β) : punit ↪ β := ⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β := ⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β := ⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩ /-- Restrict the codomain of an embedding. -/ def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩ @[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩ @[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(e₁.prod_map e₂) = prod.map e₁ e₂ := rfl section sum open sum /-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/ def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨sum.map e₁ e₂, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h end⟩ @[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map e₁ e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ @[simps] def inl {α β : Type*} : α ↪ α ⊕ β := ⟨sum.inl, λ a b, sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ @[simps] def inr {α β : Type*} : β ↪ α ⊕ β := ⟨sum.inr, λ a b, sum.inr.inj⟩ end sum section sigma variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*} /-- `sigma.mk` as an `function.embedding`. -/ @[simps apply] def sigma_mk (a : α) : β a ↪ Σ x, β x := ⟨sigma.mk a, sigma_mk_injective⟩ /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `sigma.map f g` is an embedding. -/ @[simps apply] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) : (Σ a, β a) ↪ Σ a', β' a' := ⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩ end sigma def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩ def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := by haveI := classical.prop_decidable; exact let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in ⟨f', assume f₁ f₂ h, funext $ assume c, have ∃c', e c' = e c, from ⟨c, rfl⟩, have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _, have eq_b : classical.some this = c, from e.injective $ classical.some_spec this, by simp [f', this, if_pos, eq_b] at eq'; assumption⟩ protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} := ⟨subtype.map f h, subtype.map_injective h f.2⟩ open set /-- `set.image` as an embedding `set α ↪ set β`. -/ @[simps apply] protected def image {α β} (f : α ↪ β) : set α ↪ set β := ⟨image f, f.2.image_injective⟩ lemma swap_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := f.injective.swap_apply x y z lemma swap_comp {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := f.injective.swap_comp x y end embedding end function namespace equiv open function.embedding /-- The type of embeddings `α ↪ β` is equivalent to the subtype of all injective functions `α → β`. -/ def subtype_injective_equiv_embedding (α β : Sort*) : {f : α → β // function.injective f} ≃ (α ↪ β) := { to_fun := λ f, ⟨f.val, f.property⟩, inv_fun := λ f, ⟨f, f.injective⟩, left_inv := λ f, by simp, right_inv := λ f, by {ext, refl} } /-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁` is equivalent to the type of embeddings `α₂ ↪ β₂`. -/ @[congr, simps apply] def embedding_congr {α β γ δ : Sort*} (h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) := { to_fun := λ f, h.symm.to_embedding.trans $ f.trans $ h'.to_embedding, inv_fun := λ f, h.to_embedding.trans $ f.trans $ h'.symm.to_embedding, left_inv := λ x, by {ext, simp}, right_inv := λ x, by {ext, simp} } @[simp] lemma embedding_congr_refl {α β : Sort*} : embedding_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ↪ β) := by {ext, refl} @[simp] lemma embedding_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : embedding_congr (e₁.trans e₂) (e₁'.trans e₂') = (embedding_congr e₁ e₁').trans (embedding_congr e₂ e₂') := rfl @[simp] lemma embedding_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (embedding_congr e₁ e₂).symm = embedding_congr e₁.symm e₂.symm := rfl lemma embedding_congr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) : equiv.embedding_congr ea ec (f.trans g) = (equiv.embedding_congr ea eb f).trans (equiv.embedding_congr eb ec g) := by {ext, simp} @[simp] lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl @[simp] lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl end equiv namespace set /-- The injection map is an embedding between subsets. -/ @[simps apply] def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t := ⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by { congr, injection h }⟩ end set section subtype variable {α : Type*} /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/ def subtype_or_left_embedding (p q : α → Prop) [decidable_pred p] : {x // p x ∨ q x} ↪ {x // p x} ⊕ {x // q x} := ⟨λ x, if h : p x then sum.inl ⟨x, h⟩ else sum.inr ⟨x, x.prop.resolve_left h⟩, begin intros x y, dsimp only, split_ifs; simp [subtype.ext_iff] end⟩ lemma subtype_or_left_embedding_apply_left {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : p x) : subtype_or_left_embedding p q x = sum.inl ⟨x, hx⟩ := dif_pos hx lemma subtype_or_left_embedding_apply_right {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : ¬ p x) : subtype_or_left_embedding p q x = sum.inr ⟨x, x.prop.resolve_left hx⟩ := dif_neg hx /-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`, if `p x → q x` for all `x : α`. -/ @[simps] def subtype.imp_embedding (p q : α → Prop) (h : p ≤ q) : {x // p x} ↪ {x // q x} := ⟨λ x, ⟨x, h x x.prop⟩, λ x y, by simp [subtype.ext_iff]⟩ /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` is equivalent to a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right, when `disjoint p q`. See also `equiv.sum_compl`, for when `is_compl p q`. -/ @[simps apply] def subtype_or_equiv (p q : α → Prop) [decidable_pred p] (h : disjoint p q) : {x // p x ∨ q x} ≃ {x // p x} ⊕ {x // q x} := { to_fun := subtype_or_left_embedding p q, inv_fun := sum.elim (subtype.imp_embedding _ _ (λ x hx, (or.inl hx : p x ∨ q x))) (subtype.imp_embedding _ _ (λ x hx, (or.inr hx : p x ∨ q x))), left_inv := λ x, begin by_cases hx : p x, { rw subtype_or_left_embedding_apply_left _ hx, simp [subtype.ext_iff] }, { rw subtype_or_left_embedding_apply_right _ hx, simp [subtype.ext_iff] }, end, right_inv := λ x, begin cases x, { simp only [sum.elim_inl], rw subtype_or_left_embedding_apply_left, { simp }, { simpa using x.prop } }, { simp only [sum.elim_inr], rw subtype_or_left_embedding_apply_right, { simp }, { suffices : ¬ p x, { simpa }, intro hp, simpa using h x ⟨hp, x.prop⟩ } } end } @[simp] lemma subtype_or_equiv_symm_inl (p q : α → Prop) [decidable_pred p] (h : disjoint p q) (x : {x // p x}) : (subtype_or_equiv p q h).symm (sum.inl x) = ⟨x, or.inl x.prop⟩ := rfl @[simp] lemma subtype_or_equiv_symm_inr (p q : α → Prop) [decidable_pred p] (h : disjoint p q) (x : {x // q x}) : (subtype_or_equiv p q h).symm (sum.inr x) = ⟨x, or.inr x.prop⟩ := rfl end subtype
d32ebe29aaa3fdb3d125baee0f4b3848b9fa1005
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/library/init/data/list/basic.lean
ec9763bbbdc7b653498176b0dd361d2bac76ccae
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,839
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic init.data.nat.basic open decidable list universes u v w instance (α : Type u) : inhabited (list α) := ⟨list.nil⟩ variables {α : Type u} {β : Type v} {γ : Type w} namespace list protected def append : list α → list α → list α | [] l := l | (h :: s) t := h :: (append s t) instance : has_append (list α) := ⟨list.append⟩ protected def mem : α → list α → Prop | a [] := false | a (b :: l) := a = b ∨ mem a l instance : has_mem α (list α) := ⟨list.mem⟩ instance decidable_mem [decidable_eq α] (a : α) : ∀ (l : list α), decidable (a ∈ l) | [] := is_false not_false | (b::l) := if h₁ : a = b then is_true (or.inl h₁) else match decidable_mem l with | is_true h₂ := is_true (or.inr h₂) | is_false h₂ := is_false (not_or h₁ h₂) end def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a instance : has_emptyc (list α) := ⟨list.nil⟩ protected def insert [decidable_eq α] (a : α) (l : list α) : list α := if a ∈ l then l else concat l a instance [decidable_eq α] : has_insert α (list α) := ⟨list.insert⟩ protected def union [decidable_eq α] : list α → list α → list α | l₁ [] := l₁ | l₁ (a::l₂) := union (insert a l₁) l₂ instance [decidable_eq α] : has_union (list α) := ⟨list.union⟩ protected def inter [decidable_eq α] : list α → list α → list α | [] l₂ := [] | (a::l₁) l₂ := if a ∈ l₂ then a :: inter l₁ l₂ else inter l₁ l₂ instance [decidable_eq α] : has_inter (list α) := ⟨list.inter⟩ def length : list α → nat | [] := 0 | (a :: l) := length l + 1 def empty : list α → bool | [] := tt | (_ :: _) := ff open option nat def nth : list α → nat → option α | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n def update_nth : list α → ℕ → α → list α | (x::xs) 0 a := a :: xs | (x::xs) (i+1) a := x :: update_nth xs i a | [] _ _ := [] def remove_nth : list α → ℕ → list α | [] _ := [] | (x::xs) 0 := xs | (x::xs) (i+1) := x :: remove_nth xs i def remove_all [decidable_eq α] : list α → list α → list α | (x :: xs) ys := (if x ∈ ys then remove_all xs ys else x :: remove_all xs ys) | [] ys := [] def head [inhabited α] : list α → α | [] := default α | (a :: l) := a def tail : list α → list α | [] := [] | (a :: l) := l def reverse_core : list α → list α → list α | [] r := r | (a::l) r := reverse_core l (a::r) def reverse : list α → list α := λ l, reverse_core l [] def map (f : α → β) : list α → list β | [] := [] | (a :: l) := f a :: map l def for : list α → (α → β) → list β := flip map def map₂ (f : α → β → γ) : list α → list β → list γ | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys def join : list (list α) → list α | [] := [] | (l :: ls) := append l (join ls) def filter (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: filter l else filter l def find [decidable_eq α] : α → list α → nat | a [] := 0 | a (b :: l) := if a = b then 0 else succ (find a l) def dropn : ℕ → list α → list α | 0 a := a | (succ n) [] := [] | (succ n) (x::r) := dropn n r def taken : ℕ → list α → list α | 0 a := [] | (succ n) [] := [] | (succ n) (x :: r) := x :: taken n r def foldl (f : α → β → α) : α → list β → α | a [] := a | a (b :: l) := foldl (f a b) l def foldr (f : α → β → β) : β → list α → β | b [] := b | b (a :: l) := f a (foldr b l) def any (l : list α) (p : α → bool) : bool := foldr (λ a r, p a || r) ff l def all (l : list α) (p : α → bool) : bool := foldr (λ a r, p a && r) tt l def bor (l : list bool) : bool := any l id def band (l : list bool) : bool := all l id def zip_with (f : α → β → γ) : list α → list β → list γ | (x::xs) (y::ys) := f x y :: zip_with xs ys | _ _ := [] def zip : list α → list β → list (prod α β) := zip_with prod.mk def unzip : list (α × β) → list α × list β | [] := ([], []) | ((a, b) :: t) := match unzip t with (al, bl) := (a::al, b::bl) end def repeat (a : α) : ℕ → list α | 0 := [] | (succ n) := a :: repeat n def range_core : ℕ → list ℕ → list ℕ | 0 l := l | (succ n) l := range_core n (n :: l) def range (n : ℕ) : list ℕ := range_core n [] def iota_core : ℕ → list ℕ → list ℕ | 0 l := reverse l | (succ n) l := iota_core n (succ n :: l) def iota : ℕ → list ℕ := λ n, iota_core n [] def enum_from : ℕ → list α → list (ℕ × α) | n [] := nil | n (x :: xs) := (n, x) :: enum_from (n + 1) xs def enum : list α → list (ℕ × α) := enum_from 0 def sum [has_add α] [has_zero α] : list α → α := foldl add zero def last : Π l : list α, l ≠ [] → α | [] h := absurd rfl h | [a] h := a | (a::b::l) h := last (b::l) (λ h, list.no_confusion h) def ilast [inhabited α] : list α → α | [] := arbitrary α | [a] := a | [a, b] := b | (a::b::l) := ilast l def intersperse (sep : α) : list α → list α | [] := [] | [x] := [x] | (x::xs) := x::sep::intersperse xs def intercalate (sep : list α) (xs : list (list α)) : list α := join (intersperse sep xs) @[inline] def bind {α : Type u} {β : Type v} (a : list α) (b : α → list β) : list β := join (map b a) @[inline] def ret {α : Type u} (a : α) : list α := [a] end list
c4e50d352c30fbf325fc3748b0d4a60f99c75665
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/to_additive.lean
36036fda647c26a11db452c477dd14af2d37a1bf
[]
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
2,847
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.transform_decl import Mathlib.tactic.algebra import Mathlib.PostPort universes l namespace Mathlib /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. Usage information is contained in the doc string of `to_additive.attr`. ### Missing features * Automatically transport structures and other inductive types. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. * Rewrite rules for the last part of the name that work in more cases. E.g., we can replace `monoid` with `add_monoid` etc. -/ namespace to_additive /-- An auxiliary attribute used to store the names of the additive versions of declarations that have been processed by `to_additive`. -/ /-- A command that can be used to have future uses of `to_additive` change the `src` namespace to the `tgt` namespace. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. -/ /-- `value_type` is the type of the arguments that can be provided to `to_additive`. `to_additive.parser` parses the provided arguments into `name` for the target and an optional doc string. -/ structure value_type where tgt : name doc : Option string /-- `add_comm_prefix x s` returns `"comm_" ++ s` if `x = tt` and `s` otherwise. -/ /-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/ /-- Autogenerate target name for `to_additive`. -/ /-- Return the provided target name or autogenerate one if one was not provided. -/ /-- the parser for the arguments to `to_additive` -/ /-- Add the `aux_attr` attribute to the structure fields of `src` so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/ /-- The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration, and provide a documentation string: ``` @[to_additive add_foo "add_foo doc string"] /-- foo doc string -/
d77eb45762c8554018c1c7303fc37616a4e351cc
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/quadratic_form/complex.lean
63190d440fec23bc8d3676379807138e816bc6e6
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,157
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Kexing Ying, Eric Wieser -/ import linear_algebra.quadratic_form.basic import analysis.special_functions.pow /-! # Quadratic forms over the complex numbers `equivalent_sum_squares`: A nondegenerate quadratic form over the complex numbers is equivalent to a sum of squares. -/ namespace quadratic_form open_locale big_operators open finset variables {ι : Type*} [fintype ι] /-- The isometry between a weighted sum of squares on the complex numbers and the sum of squares, i.e. `weighted_sum_squares` with weights 1 or 0. -/ noncomputable def isometry_sum_squares [decidable_eq ι] (w' : ι → ℂ) : isometry (weighted_sum_squares ℂ w') (weighted_sum_squares ℂ (λ i, if w' i = 0 then 0 else 1 : ι → ℂ)) := begin let w := λ i, if h : w' i = 0 then (1 : units ℂ) else units.mk0 (w' i) h, have hw' : ∀ i : ι, (w i : ℂ) ^ - (1 / 2 : ℂ) ≠ 0, { intros i hi, exact (w i).ne_zero ((complex.cpow_eq_zero_iff _ _).1 hi).1 }, convert (weighted_sum_squares ℂ w').isometry_basis_repr ((pi.basis_fun ℂ ι).units_smul (λ i, (is_unit_iff_ne_zero.2 $ hw' i).unit)), ext1 v, erw [basis_repr_apply, weighted_sum_squares_apply, weighted_sum_squares_apply], refine sum_congr rfl (λ j hj, _), have hsum : (∑ (i : ι), v i • ((is_unit_iff_ne_zero.2 $ hw' i).unit : ℂ) • (pi.basis_fun ℂ ι) i) j = v j • w j ^ - (1 / 2 : ℂ), { rw [finset.sum_apply, sum_eq_single j, pi.basis_fun_apply, is_unit.unit_spec, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_same, smul_eq_mul, smul_eq_mul, smul_eq_mul, mul_one], intros i _ hij, rw [pi.basis_fun_apply, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_noteq hij.symm, pi.zero_apply, smul_eq_mul, smul_eq_mul, mul_zero, mul_zero], intro hj', exact false.elim (hj' hj) }, simp_rw basis.units_smul_apply, erw [hsum, smul_eq_mul], split_ifs, { simp only [h, zero_smul, zero_mul]}, have hww' : w' j = w j, { simp only [w, dif_neg h, units.coe_mk0] }, simp only [hww', one_mul], change v j * v j = ↑(w j) * ((v j * ↑(w j) ^ -(1 / 2 : ℂ)) * (v j * ↑(w j) ^ -(1 / 2 : ℂ))), suffices : v j * v j = w j ^ - (1 / 2 : ℂ) * w j ^ - (1 / 2 : ℂ) * w j * v j * v j, { rw [this], ring }, rw [← complex.cpow_add _ _ (w j).ne_zero, show - (1 / 2 : ℂ) + - (1 / 2) = -1, by ring, complex.cpow_neg_one, inv_mul_cancel (w j).ne_zero, one_mul], end /-- The isometry between a weighted sum of squares on the complex numbers and the sum of squares, i.e. `weighted_sum_squares` with weight `λ i : ι, 1`. -/ noncomputable def isometry_sum_squares_units [decidable_eq ι] (w : ι → units ℂ) : isometry (weighted_sum_squares ℂ w) (weighted_sum_squares ℂ (1 : ι → ℂ)) := begin have hw1 : (λ i, if (w i : ℂ) = 0 then 0 else 1 : ι → ℂ) = 1, { ext i : 1, exact dif_neg (w i).ne_zero }, have := isometry_sum_squares (coe ∘ w), rw hw1 at this, exact this, end /-- A nondegenerate quadratic form on the complex numbers is equivalent to the sum of squares, i.e. `weighted_sum_squares` with weight `λ i : ι, 1`. -/ theorem equivalent_sum_squares {M : Type*} [add_comm_group M] [module ℂ M] [finite_dimensional ℂ M] (Q : quadratic_form ℂ M) (hQ : (associated Q).nondegenerate) : equivalent Q (weighted_sum_squares ℂ (1 : fin (finite_dimensional.finrank ℂ M) → ℂ)) := let ⟨w, ⟨hw₁⟩⟩ := Q.equivalent_weighted_sum_squares_units_of_nondegenerate' hQ in ⟨hw₁.trans (isometry_sum_squares_units w)⟩ /-- All nondegenerate quadratic forms on the complex numbers are equivalent. -/ theorem complex_equivalent {M : Type*} [add_comm_group M] [module ℂ M] [finite_dimensional ℂ M] (Q₁ Q₂ : quadratic_form ℂ M) (hQ₁ : (associated Q₁).nondegenerate) (hQ₂ : (associated Q₂).nondegenerate) : equivalent Q₁ Q₂ := (Q₁.equivalent_sum_squares hQ₁).trans (Q₂.equivalent_sum_squares hQ₂).symm end quadratic_form
d5a23c9720d1be95d2df8858f9f79d9d73643616
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Parser/Basic.lean
24fd380ecd11e236c7fa3ebda68146b738efeaf9
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
75,202
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.Trie import Lean.Syntax import Lean.Message /-! # Basic Lean parser infrastructure The Lean parser was developed with the following primary goals in mind: * flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach. * extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens. * losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token" information for the use in tooling. * performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be necessary for this. Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we usually use the macro `leading_parser p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the declaration being defined. The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser` for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace. The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information: `collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST" token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel. If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator. This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these parallel parsers apart from the first token, though we might change this in the future if the need arises. Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly. Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips tokens until the next command keyword on error. -/ namespace Lean namespace Parser abbrev mkAtom (info : SourceInfo) (val : String) : Syntax := Syntax.atom info val abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax := Syntax.ident info rawVal val [] /-- Return character after position `pos` -/ def getNext (input : String) (pos : String.Pos) : Char := input.get (input.next pos) /-- Maximal (and function application) precedence. In the standard lean language, no parser has precedence higher than `maxPrec`. Note that nothing prevents users from using a higher precedence, but we strongly discourage them from doing it. -/ def maxPrec : Nat := eval_prec max def argPrec : Nat := eval_prec arg def leadPrec : Nat := eval_prec lead def minPrec : Nat := eval_prec min abbrev Token := String structure TokenCacheEntry where startPos : String.Pos := 0 stopPos : String.Pos := 0 token : Syntax := Syntax.missing structure ParserCache where tokenCache : TokenCacheEntry def initCacheForInput (input : String) : ParserCache := { tokenCache := { startPos := input.endPos + ' ' /- make sure it is not a valid position -/} } abbrev TokenTable := Trie Token abbrev SyntaxNodeKindSet := PersistentHashMap SyntaxNodeKind Unit def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet := PersistentHashMap.insert s k () /-- Input string and related data. Recall that the `FileMap` is a helper structure for mapping `String.Pos` in the input string to line/column information. -/ structure InputContext where input : String fileName : String fileMap : FileMap deriving Inhabited /-- Input context derived from elaboration of previous commands. -/ structure ParserModuleContext where env : Environment options : Options -- for name lookup currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] structure ParserContext extends InputContext, ParserModuleContext where prec : Nat tokens : TokenTable -- used for bootstrapping only quotDepth : Nat := 0 suppressInsideQuot : Bool := false savedPos? : Option String.Pos := none forbiddenTk? : Option Token := none structure Error where unexpected : String := "" expected : List String := [] deriving Inhabited, BEq namespace Error private def expectedToString : List String → String | [] => "" | [e] => e | [e1, e2] => e1 ++ " or " ++ e2 | e::es => e ++ ", " ++ expectedToString es protected def toString (e : Error) : String := let unexpected := if e.unexpected == "" then [] else [e.unexpected] let expected := if e.expected == [] then [] else let expected := e.expected.toArray.qsort (fun e e' => e < e') let expected := expected.toList.eraseReps ["expected " ++ expectedToString expected] "; ".intercalate $ unexpected ++ expected instance : ToString Error := ⟨Error.toString⟩ def merge (e₁ e₂ : Error) : Error := match e₂ with | { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected } end Error structure ParserState where stxStack : Array Syntax := #[] /-- Set to the precedence of the preceding (not surrounding) parser by `runLongestMatchParser` for the use of `checkLhsPrec` in trailing parsers. Note that with chaining, the preceding parser can be another trailing parser: in `1 * 2 + 3`, the preceding parser is '*' when '+' is executed. -/ lhsPrec : Nat := 0 pos : String.Pos := 0 cache : ParserCache errorMsg : Option Error := none namespace ParserState def hasError (s : ParserState) : Bool := s.errorMsg != none def stackSize (s : ParserState) : Nat := s.stxStack.size def restore (s : ParserState) (iniStackSz : Nat) (iniPos : String.Pos) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos } def setPos (s : ParserState) (pos : String.Pos) : ParserState := { s with pos := pos } def setCache (s : ParserState) (cache : ParserCache) : ParserState := { s with cache := cache } def pushSyntax (s : ParserState) (n : Syntax) : ParserState := { s with stxStack := s.stxStack.push n } def popSyntax (s : ParserState) : ParserState := { s with stxStack := s.stxStack.pop } def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz } def next (s : ParserState) (input : String) (pos : String.Pos) : ParserState := { s with pos := input.next pos } def toErrorMsg (ctx : ParserContext) (s : ParserState) : String := match s.errorMsg with | none => "" | some msg => let pos := ctx.fileMap.toPosition s.pos mkErrorStringWithPos ctx.fileName pos (toString msg) def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => if err != none && stack.size == iniStackSz then -- If there is an error but there are no new nodes on the stack, use `missing` instead. -- Thus we ensure the property that an syntax tree contains (at least) one `missing` node -- if (and only if) there was a parse error. -- We should not create an actual node of kind `k` in this case because it would mean we -- choose an "arbitrary" node (in practice the last one) in an alternative of the form -- `node k1 p1 <|> ... <|> node kn pn` when all parsers fail. With the code below we -- instead return a less misleading single `missing` node without randomly selecting any `ki`. let stack := stack.push Syntax.missing ⟨stack, lhsPrec, pos, cache, err⟩ else let newNode := Syntax.node SourceInfo.none k (stack.extract iniStackSz stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => let newNode := Syntax.node SourceInfo.none k (stack.extract (iniStackSz - 1) stack.size) let stack := stack.shrink (iniStackSz - 1) let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def setError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkUnexpectedError (s : ParserState) (msg : String) (expected : List String := []) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg, expected := expected }⟩ def mkEOIError (s : ParserState) (expected : List String := []) : ParserState := s.mkUnexpectedError "unexpected end of input" expected def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩ def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ end ParserState def ParserFn := ParserContext → ParserState → ParserState instance : Inhabited ParserFn where default := fun _ s => s inductive FirstTokens where | epsilon : FirstTokens | unknown : FirstTokens | tokens : List Token → FirstTokens | optTokens : List Token → FirstTokens deriving Inhabited namespace FirstTokens def seq : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => tks | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | tks, _ => tks def toOptional : FirstTokens → FirstTokens | tokens tks => optTokens tks | tks => tks def merge : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => toOptional tks | tks, epsilon => toOptional tks | tokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂) | _, _ => unknown def toStr : FirstTokens → String | epsilon => "epsilon" | unknown => "unknown" | tokens tks => toString tks | optTokens tks => "?" ++ toString tks instance : ToString FirstTokens := ⟨toStr⟩ end FirstTokens structure ParserInfo where collectTokens : List Token → List Token := id collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id firstTokens : FirstTokens := FirstTokens.unknown deriving Inhabited structure Parser where info : ParserInfo := {} fn : ParserFn deriving Inhabited abbrev TrailingParser := Parser def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn := fun c s => let sz := s.stxStack.size let s' := p c s dbg_trace "{label} pos: {s'.pos} err: {s'.errorMsg} out: {s'.stxStack.extract sz s'.stxStack.size}" s' def dbgTraceState (label : String) (p : Parser) : Parser where fn := dbgTraceStateFn label p.fn info := p.info @[noinline]def epsilonInfo : ParserInfo := { firstTokens := FirstTokens.epsilon } def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun _ s => if p s.stxStack.back then s else s.mkUnexpectedError msg def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := { info := epsilonInfo, fn := checkStackTopFn p msg } def andthenFn (p q : ParserFn) : ParserFn := fun c s => let s := p c s if s.hasError then s else q c s @[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.seq q.firstTokens } def andthen (p q : Parser) : Parser := { info := andthenInfo p.info q.info, fn := andthenFn p.fn q.fn } instance : AndThen Parser where andThen a b := andthen a (b ()) def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkNode n iniSz def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkTrailingNode n iniSz @[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := fun s => (p.collectKinds s).insert n, firstTokens := p.firstTokens } def node (n : SyntaxNodeKind) (p : Parser) : Parser := { info := nodeInfo n p.info, fn := nodeFn n p.fn } def errorFn (msg : String) : ParserFn := fun _ s => s.mkUnexpectedError msg def error (msg : String) : Parser := { info := epsilonInfo, fn := errorFn msg } def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s => match c.savedPos? with | none => s | some pos => let pos := if delta then c.input.next pos else pos match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ /-- Generate an error at the position saved with the `withPosition` combinator. If `delta == true`, then it reports at saved position+1. This useful to make sure a parser consumed at least one character. -/ def errorAtSavedPos (msg : String) (delta : Bool) : Parser := { fn := errorAtSavedPosFn msg delta } /-- Succeeds if `c.prec <= prec` -/ def checkPrecFn (prec : Nat) : ParserFn := fun c s => if c.prec <= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" def checkPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkPrecFn prec } /-- Succeeds if `c.lhsPrec >= prec` -/ def checkLhsPrecFn (prec : Nat) : ParserFn := fun _ s => if s.lhsPrec >= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" def checkLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkLhsPrecFn prec } def setLhsPrecFn (prec : Nat) : ParserFn := fun _ s => if s.hasError then s else { s with lhsPrec := prec } def setLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := setLhsPrecFn prec } private def addQuotDepthFn (i : Int) (p : ParserFn) : ParserFn := fun c s => p { c with quotDepth := c.quotDepth + i |>.toNat } s def incQuotDepth (p : Parser) : Parser := { info := p.info, fn := addQuotDepthFn 1 p.fn } def decQuotDepth (p : Parser) : Parser := { info := p.info, fn := addQuotDepthFn (-1) p.fn } def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s => p { c with suppressInsideQuot := true } s def suppressInsideQuot (p : Parser) : Parser := { info := p.info, fn := suppressInsideQuotFn p.fn } def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser := checkPrec prec >> node n p >> setLhsPrec prec def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := { info := nodeInfo n p.info, fn := trailingNodeFn n p.fn } def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser := checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : String.Pos) (mergeErrors : Bool) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some error2⟩ => if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩ else s | other => other -- When `p` in `p <|> q` parses exactly one antiquotation, ... inductive OrElseOnAntiquotBehavior where | acceptLhs -- return it | takeLongest -- return result of `q` instead if it made more progress | merge -- ... and create choice node if both made the same progress deriving BEq def orelseFnCore (p q : ParserFn) (antiquotBehavior := OrElseOnAntiquotBehavior.merge) : ParserFn := fun c s => Id.run do let s0 := s let iniSz := s.stackSize let iniPos := s.pos let mut s := p c s match s.errorMsg with | some errorMsg => if s.pos == iniPos then mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos true else s | none => let back := s.stxStack.back if antiquotBehavior != .acceptLhs && s.stackSize == iniSz + 1 && back.isAntiquots then let s' := q c s0 if !s'.hasError then -- If `q` made more progress than `p`, we prefer its result. -- Thus `(structInstField| $id := $val) is interpreted as -- `(structInstField| $id:ident := $val:term), not -- `(structInstField| $id:structInstField <ERROR: expected ')'>. if s'.pos > s.pos then return s' else if antiquotBehavior == .merge && s'.stackSize == iniSz + 1 && s'.stxStack.back.isAntiquot then if back.isOfKind choiceKind then s := { s with stxStack := s.stxStack.pop ++ back.getArgs } s := s.pushSyntax s'.stxStack.back s := s.mkNode choiceKind iniSz s def orelseFn (p q : ParserFn) : ParserFn := orelseFnCore p q @[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.merge q.firstTokens } /-- Run `p`, falling back to `q` if `p` failed without consuming any input. NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...` is fine as well. -/ def orelse (p q : Parser) : Parser := { info := orelseInfo p.info q.info, fn := orelseFn p.fn q.fn } instance : OrElse Parser where orElse a b := orelse a (b ()) @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { collectTokens := info.collectTokens, collectKinds := info.collectKinds } def atomicFn (p : ParserFn) : ParserFn := fun c s => let iniPos := s.pos match p c s with | ⟨stack, lhsPrec, _, cache, some msg⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg⟩ | other => other def atomic (p : Parser) : Parser := { info := p.info, fn := atomicFn p.fn } def optionalFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s s.mkNode nullKind iniSz @[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds, firstTokens := p.firstTokens.toOptional } def optionalNoAntiquot (p : Parser) : Parser := { info := optionaInfo p.info, fn := optionalFn p.fn } def lookaheadFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s else s.restore iniSz iniPos def lookahead (p : Parser) : Parser := { info := p.info, fn := lookaheadFn p.fn } def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s.restore iniSz iniPos else let s := s.restore iniSz iniPos s.mkUnexpectedError s!"unexpected {msg}" def notFollowedBy (p : Parser) (msg : String) : Parser := { fn := notFollowedByFn p.fn msg } partial def manyAux (p : ParserFn) : ParserFn := fun c s => Id.run do let iniSz := s.stackSize let iniPos := s.pos let mut s := p c s if s.hasError then return if iniPos == s.pos then s.restore iniSz iniPos else s if iniPos == s.pos then return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything" if s.stackSize > iniSz + 1 then s := s.mkNode nullKind iniSz manyAux p c s def manyFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := manyAux p c s s.mkNode nullKind iniSz def manyNoAntiquot (p : Parser) : Parser := { info := noFirstTokenInfo p.info, fn := manyFn p.fn } def many1Fn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := andthenFn p (manyAux p) c s s.mkNode nullKind iniSz def many1NoAntiquot (p : Parser) : Parser := { info := p.info, fn := many1Fn p.fn } private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn := let rec parse (pOpt : Bool) (c s) := Id.run do let sz := s.stackSize let pos := s.pos let mut s := p c s if s.hasError then if s.pos > pos then return s.mkNode nullKind iniSz else if pOpt then s := s.restore sz pos return s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete s := s.pushSyntax Syntax.missing return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz let sz := s.stackSize let pos := s.pos s := sep c s if s.hasError then s := s.restore sz pos return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz parse allowTrailingSep c s parse pOpt def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz true c s def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz false c s @[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds } @[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds, firstTokens := p.firstTokens } def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepByInfo p.info sep.info, fn := sepByFn allowTrailingSep p.fn sep.fn } def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepBy1Info p.info sep.info, fn := sepBy1Fn allowTrailingSep p.fn sep.fn } /-- Apply `f` to the syntax object produced by `p` -/ def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s => let s := p c s if s.hasError then s else let stx := s.stxStack.back s.popSyntax.pushSyntax (f stx) @[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds } def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := { info := withResultOfInfo p.info, fn := withResultOfFn p.fn f } def many1Unbox (p : Parser) : Parser := withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s.mkEOIError else if p (c.input.get i) then s.next c.input i else s.mkUnexpectedError errorMsg partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else if p (c.input.get i) then s else takeUntilFn p c (s.next c.input i) def takeWhileFn (p : Char → Bool) : ParserFn := takeUntilFn (fun c => !p c) def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn := andthenFn (satisfyFn p errorMsg) (takeWhileFn p) partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then eoi s else let curr := input.get i let i := input.next i if curr == '-' then if input.atEnd i then eoi s else let curr := input.get i if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next input i else finishCommentBlock (nesting-1) c (s.next input i) else finishCommentBlock nesting c (s.next input i) else if curr == '/' then if input.atEnd i then eoi s else let curr := input.get i if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i) else finishCommentBlock nesting c (s.setPos i) else finishCommentBlock nesting c (s.setPos i) where eoi s := s.mkUnexpectedError "unterminated comment" /-- Consume whitespace and comments -/ partial def whitespace : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == '\t' then s.mkUnexpectedError "tabs are not allowed; please configure your editor to expand them" else if curr.isWhitespace then whitespace c (s.next input i) else if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i) else s else if curr == '/' then let i := input.next i let curr := input.get i if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' || curr == '!' then s -- "/--" and "/-!" doc comment are actual tokens else andthenFn (finishCommentBlock 1) whitespace c (s.next input i) else s else s def mkEmptySubstringAt (s : String) (p : String.Pos) : Substring := { str := s, startPos := p, stopPos := p } private def rawAux (startPos : String.Pos) (trailingWs : Bool) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos if trailingWs then let s := whitespace c s let stopPos' := s.pos let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val)) val s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val)) val s.pushSyntax atom /-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/ def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s => let startPos := s.pos let s := p c s if s.hasError then s else rawAux startPos trailingWs c s def chFn (c : Char) (trailingWs := false) : ParserFn := rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs def rawCh (c : Char) (trailingWs := false) : Parser := { fn := chFn c trailingWs } def hexDigitFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let i := input.next i if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i else s.mkUnexpectedError "invalid hexadecimal numeral" def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i if isQuotable curr then s.next input i else if curr == 'x' then andthenFn hexDigitFn hexDigitFn c (s.next input i) else if curr == 'u' then andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i) else s.mkUnexpectedError "invalid escape sequence" def isQuotableCharDefault (c : Char) : Bool := c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't' def quotedCharFn : ParserFn := quotedCharCoreFn isQuotableCharDefault /-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/ def mkNodeToken (n : SyntaxNodeKind) (startPos : String.Pos) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let info := SourceInfo.original leading startPos trailing stopPos s.pushSyntax (Syntax.mkLit n val info) def charLitFnAux (startPos : String.Pos) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let s := s.setPos (input.next i) let s := if curr == '\\' then quotedCharFn c s else s if s.hasError then s else let i := s.pos let curr := input.get i let s := s.setPos (input.next i) if curr == '\'' then mkNodeToken charLitKind startPos c s else s.mkUnexpectedError "missing end of character literal" partial def strLitFnAux (startPos : String.Pos) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos else let curr := input.get i let s := s.setPos (input.next i) if curr == '\"' then mkNodeToken strLitKind startPos c s else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s else strLitFnAux startPos c s def decimalNumberFn (startPos : String.Pos) (c : ParserContext) : ParserState → ParserState := fun s => let s := takeWhileFn (fun c => c.isDigit) c s let input := c.input let i := s.pos let curr := input.get i if curr == '.' || curr == 'e' || curr == 'E' then let s := parseOptDot s let s := parseOptExp s mkNodeToken scientificLitKind startPos c s else mkNodeToken numLitKind startPos c s where parseOptDot s := let input := c.input let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s parseOptExp s := let input := c.input let i := s.pos let curr := input.get i if curr == 'e' || curr == 'E' then let i := input.next i let i := if input.get i == '-' || input.get i == '+' then input.next i else i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.mkUnexpectedError "missing exponent digits in scientific literal" else s def binNumberFn (startPos : String.Pos) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s mkNodeToken numLitKind startPos c s def octalNumberFn (startPos : String.Pos) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s mkNodeToken numLitKind startPos c s def hexNumberFn (startPos : String.Pos) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s mkNodeToken numLitKind startPos c s def numberFnAux : ParserFn := fun c s => let input := c.input let startPos := s.pos if input.atEnd startPos then s.mkEOIError else let curr := input.get startPos if curr == '0' then let i := input.next startPos let curr := input.get i if curr == 'b' || curr == 'B' then binNumberFn startPos c (s.next input i) else if curr == 'o' || curr == 'O' then octalNumberFn startPos c (s.next input i) else if curr == 'x' || curr == 'X' then hexNumberFn startPos c (s.next input i) else decimalNumberFn startPos c (s.setPos i) else if curr.isDigit then decimalNumberFn startPos c (s.next input startPos) else s.mkError "numeral" def isIdCont : String → ParserState → Bool := fun input s => let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i if input.atEnd i then false else let curr := input.get i isIdFirst curr || isIdBeginEscape curr else false private def isToken (idStartPos idStopPos : String.Pos) (tk : Option Token) : Bool := match tk with | none => false | some tk => -- if a token is both a symbol and a valid identifier (i.e. a keyword), -- we want it to be recognized as a symbol tk.endPos ≥ idStopPos - idStartPos def mkTokenAndFixPos (startPos : String.Pos) (tk : Option Token) : ParserFn := fun c s => match tk with | none => s.mkErrorAt "token" startPos | some tk => if c.forbiddenTk? == some tk then s.mkErrorAt "forbidden token" startPos else let input := c.input let leading := mkEmptySubstringAt input startPos let stopPos := startPos + tk let s := s.setPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing stopPos) tk s.pushSyntax atom def mkIdResult (startPos : String.Pos) (tk : Option Token) (val : Name) : ParserFn := fun c s => let stopPos := s.pos if isToken startPos stopPos tk then mkTokenAndFixPos startPos tk c s else let input := c.input let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring } let s := whitespace c s let trailingStopPos := s.pos let leading := mkEmptySubstringAt input startPos let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring } let info := SourceInfo.original leading startPos trailing stopPos let atom := mkIdent info rawVal val s.pushSyntax atom partial def identFnAux (startPos : String.Pos) (tk : Option Token) (r : Name) : ParserFn := let rec parse (r : Name) (c s) := Id.run do let input := c.input let i := s.pos if input.atEnd i then return s.mkEOIError let curr := input.get i if isIdBeginEscape curr then let startPart := input.next i let s := takeUntilFn isIdEndEscape c (s.setPos startPart) if input.atEnd s.pos then return s.mkUnexpectedErrorAt "unterminated identifier escape" startPart let stopPart := s.pos let s := s.next c.input s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else if isIdFirst curr then let startPart := i let s := takeWhileFn isIdRest c (s.next input i) let stopPart := s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else mkTokenAndFixPos startPos tk c s parse r private def isIdFirstOrBeginEscape (c : Char) : Bool := isIdFirst c || isIdBeginEscape c private def nameLitAux (startPos : String.Pos) : ParserFn := fun c s => let input := c.input let s := identFnAux startPos none Name.anonymous c (s.next input startPos) if s.hasError then s else let stx := s.stxStack.back match stx with | Syntax.ident info rawStr _ _ => let s := s.popSyntax s.pushSyntax (Syntax.mkNameLit rawStr.toString info) | _ => s.mkError "invalid Name literal" private def tokenFnAux : ParserFn := fun c s => let input := c.input let i := s.pos let curr := input.get i if curr == '\"' then strLitFnAux i c (s.next input i) else if curr == '\'' then charLitFnAux i c (s.next input i) else if curr.isDigit then numberFnAux c s else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then nameLitAux i c s else let (_, tk) := c.tokens.matchPrefix input i identFnAux i tk Name.anonymous c s private def updateCache (startPos : String.Pos) (s : ParserState) : ParserState := -- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache` match s with | ⟨stack, lhsPrec, pos, _, none⟩ => if stack.size == 0 then s else let tk := stack.back ⟨stack, lhsPrec, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩ | other => other def tokenFn (expected : List String := []) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError expected else let tkc := s.cache.tokenCache if tkc.startPos == i then let s := s.pushSyntax tkc.token s.setPos tkc.stopPos else let s := tokenFnAux c s updateCache i s def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let iniSz := s.stackSize let iniPos := s.pos let s := tokenFn [] c s if let some _ := s.errorMsg then (s.restore iniSz iniPos, Except.error s) else let stx := s.stxStack.back (s.restore iniSz iniPos, Except.ok stx) def peekToken (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let tkc := s.cache.tokenCache if tkc.startPos == s.pos then (s, Except.ok tkc.token) else peekTokenAux c s /-- Treat keywords as identifiers. -/ def rawIdentFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else identFnAux i none Name.anonymous c s def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn expected c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz | _ => s.mkErrorsAt expected startPos initStackSz def symbolFnAux (sym : String) (errorMsg : String) : ParserFn := satisfySymbolFn (fun s => s == sym) [errorMsg] def symbolInfo (sym : String) : ParserInfo := { collectTokens := fun tks => sym :: tks, firstTokens := FirstTokens.tokens [ sym ] } def symbolFn (sym : String) : ParserFn := symbolFnAux sym ("'" ++ sym ++ "'") def symbolNoAntiquot (sym : String) : Parser := let sym := sym.trim { info := symbolInfo sym, fn := symbolFn sym } def checkTailNoWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.stopPos == trailing.startPos | _ => false /-- Check if the following token is the symbol _or_ identifier `sym`. Useful for parsing local tokens that have not been added to the token table (but may have been so by some unrelated code). For example, the universe `max` Function is parsed using this combinator so that it can still be used as an identifier outside of universe (but registering it as a token in a Term Syntax would not break the universe Parser). -/ def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn [errorMsg] c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym' => if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz | Syntax.ident info rawVal _ _ => if sym == rawVal.toString then let s := s.popSyntax s.pushSyntax (Syntax.atom info sym) else s.mkErrorAt errorMsg startPos initStackSz | _ => s.mkErrorAt errorMsg startPos initStackSz def nonReservedSymbolFn (sym : String) : ParserFn := nonReservedSymbolFnAux sym ("'" ++ sym ++ "'") def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := { firstTokens := if includeIdent then FirstTokens.tokens [ sym, "ident" ] else FirstTokens.tokens [ sym ] } def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser := let sym := sym.trim { info := nonReservedSymbolInfo sym includeIdent, fn := nonReservedSymbolFn sym } partial def strAux (sym : String) (errorMsg : String) (j : String.Pos) :ParserFn := let rec parse (j c s) := if sym.atEnd j then s else let i := s.pos let input := c.input if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg else parse (sym.next j) c (s.next input i) parse j def checkTailWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.stopPos > trailing.startPos | _ => false def checkWsBeforeFn (errorMsg : String) : ParserFn := fun _ s => let prev := s.stxStack.back if checkTailWs prev then s else s.mkError errorMsg def checkWsBefore (errorMsg : String := "space before") : Parser := { info := epsilonInfo, fn := checkWsBeforeFn errorMsg } def checkTailLinebreak (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.contains '\n' | _ => false def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun _ s => let prev := s.stxStack.back if checkTailLinebreak prev then s else s.mkError errorMsg def checkLinebreakBefore (errorMsg : String := "line break") : Parser := { info := epsilonInfo fn := checkLinebreakBeforeFn errorMsg } private def pickNonNone (stack : Array Syntax) : Syntax := match stack.findRev? fun stx => !stx.isNone with | none => Syntax.missing | some stx => stx def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun _ s => let prev := pickNonNone s.stxStack if checkTailNoWs prev then s else s.mkError errorMsg def checkNoWsBefore (errorMsg : String := "no space before") : Parser := { info := epsilonInfo, fn := checkNoWsBeforeFn errorMsg } def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn := satisfySymbolFn (fun s => s == sym || s == asciiSym) expected def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := { collectTokens := fun tks => sym :: asciiSym :: tks, firstTokens := FirstTokens.tokens [ sym, asciiSym ] } def unicodeSymbolFn (sym asciiSym : String) : ParserFn := unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser := let sym := sym.trim let asciiSym := asciiSym.trim { info := unicodeSymbolInfo sym asciiSym, fn := unicodeSymbolFn sym asciiSym } def mkAtomicInfo (k : String) : ParserInfo := { firstTokens := FirstTokens.tokens [ k ] } def numLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["numeral"] c s if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s def numLitNoAntiquot : Parser := { fn := numLitFn, info := mkAtomicInfo "num" } def scientificLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["scientific number"] c s if !s.hasError && !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos initStackSz else s def scientificLitNoAntiquot : Parser := { fn := scientificLitFn, info := mkAtomicInfo "scientific" } def strLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["string literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos initStackSz else s def strLitNoAntiquot : Parser := { fn := strLitFn, info := mkAtomicInfo "str" } def charLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["char literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos initStackSz else s def charLitNoAntiquot : Parser := { fn := charLitFn, info := mkAtomicInfo "char" } def nameLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["Name literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos initStackSz else s def nameLitNoAntiquot : Parser := { fn := nameLitFn, info := mkAtomicInfo "name" } def identFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if !s.hasError && !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos initStackSz else s def identNoAntiquot : Parser := { fn := identFn, info := mkAtomicInfo "ident" } def rawIdentNoAntiquot : Parser := { fn := rawIdentFn } def identEqFn (id : Name) : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if s.hasError then s else match s.stxStack.back with | Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos initStackSz else s | _ => s.mkErrorAt "identifier" iniPos initStackSz def identEq (id : Name) : Parser := { fn := identEqFn id, info := mkAtomicInfo "ident" } namespace ParserState def keepTop (s : Array Syntax) (startStackSize : Nat) : Array Syntax := let node := s.back s.shrink startStackSize |>.push node def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => ⟨keepTop stack oldStackSize, lhsPrec, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) (oldLhsPrec : Nat) : ParserState := match s with | ⟨stack, _, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldLhsPrec, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some err⟩ => if oldError == err then s else ⟨stack.shrink oldStackSize, lhsPrec, pos, cache, some (oldError.merge err)⟩ | other => other def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨keepTop stack startStackSize, lhsPrec, pos, cache, none⟩ def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState := s.keepLatest startStackSize end ParserState def invalidLongestMatchParser (s : ParserState) : ParserState := s.mkError "longestMatch parsers must generate exactly one Syntax node" /-- Auxiliary function used to execute parsers provided to `longestMatchFn`. Push `left?` into the stack if it is not `none`, and execute `p`. Remark: `p` must produce exactly one syntax node. Remark: the `left?` is not none when we are processing trailing parsers. -/ def runLongestMatchParser (left? : Option Syntax) (startLhsPrec : Nat) (p : ParserFn) : ParserFn := fun c s => Id.run do /- We assume any registered parser `p` has one of two forms: * a direct call to `leadingParser` or `trailingParser` * a direct call to a (leading) token parser In the first case, we can extract the precedence of the parser by having `leadingParser/trailingParser` set `ParserState.lhsPrec` to it in the very end so that no nested parser can interfere. In the second case, the precedence is effectively `max` (there is a `checkPrec` merely for the convenience of the pretty printer) and there are no nested `leadingParser/trailingParser` calls, so the value of `lhsPrec` will not be changed by the parser (nor will it be read by any leading parser). Thus we initialize the field to `maxPrec` in the leading case. -/ let mut s := { s with lhsPrec := if left?.isSome then startLhsPrec else maxPrec } let startSize := s.stackSize if let some left := left? then s := s.pushSyntax left s := p c s -- stack contains `[..., result ]` if s.stackSize == startSize + 1 then s -- success or error with the expected number of nodes else if s.hasError then -- error with an unexpected number of nodes. s.shrinkStack startSize |>.pushSyntax Syntax.missing else -- parser succeded with incorrect number of nodes invalidLongestMatchParser s def longestMatchStep (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn) : ParserContext → ParserState → ParserState × Nat := fun c s => let score (s : ParserState) (prio : Nat) := (s.pos.byteIdx, if s.errorMsg.isSome then (0 : Nat) else 1, prio) let previousScore := score s prevPrio let prevErrorMsg := s.errorMsg let prevStopPos := s.pos let prevSize := s.stackSize let prevLhsPrec := s.lhsPrec let s := s.restore prevSize startPos let s := runLongestMatchParser left? startLhsPrec p c s match (let _ := @lexOrd; compare previousScore (score s prio)) with | .lt => (s.keepNewError startSize, prio) | .gt => (s.keepPrevError prevSize prevStopPos prevErrorMsg prevLhsPrec, prevPrio) | .eq => match prevErrorMsg with | none => -- it is not clear what the precedence of a choice node should be, so we conservatively take the minimum ({s with lhsPrec := s.lhsPrec.min prevLhsPrec }, prio) | some oldError => (s.mergeErrors prevSize oldError, prio) def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState := if s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s def longestMatchFnAux (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn := let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) := match ps with | [] => fun _ s => longestMatchMkResult startSize s | p::ps => fun c s => let (s, prevPrio) := longestMatchStep left? startSize startLhsPrec startPos prevPrio p.2 p.1.fn c s parse prevPrio ps c s parse prevPrio ps def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn | [] => fun _ s => s.mkError "longestMatch: empty list" | [p] => fun c s => runLongestMatchParser left? s.lhsPrec p.1.fn c s | p::ps => fun c s => let startSize := s.stackSize let startLhsPrec := s.lhsPrec let startPos := s.pos let s := runLongestMatchParser left? s.lhsPrec p.1.fn c s longestMatchFnAux left? startSize startLhsPrec startPos p.2 ps c s def anyOfFn : List Parser → ParserFn | [], _, s => s.mkError "anyOf: empty list" | [p], c, s => p.fn c s | p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s def checkColEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column = savedPos.column then s else s.mkError errorMsg def checkColEq (errorMsg : String := "checkColEq") : Parser := { fn := checkColEqFn errorMsg } def checkColGeFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column ≥ savedPos.column then s else s.mkError errorMsg def checkColGe (errorMsg : String := "checkColGe") : Parser := { fn := checkColGeFn errorMsg } def checkColGtFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column > savedPos.column then s else s.mkError errorMsg def checkColGt (errorMsg : String := "checkColGt") : Parser := { fn := checkColGtFn errorMsg } def checkLineEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.line == savedPos.line then s else s.mkError errorMsg def checkLineEq (errorMsg : String := "checkLineEq") : Parser := { fn := checkLineEqFn errorMsg } def withPosition (p : Parser) : Parser := { info := p.info fn := fun c s => p.fn { c with savedPos? := s.pos } s } def withPositionAfterLinebreak (p : Parser) : Parser := { info := p.info fn := fun c s => let prev := s.stxStack.back let c := if checkTailLinebreak prev then { c with savedPos? := s.pos } else c p.fn c s } def withoutPosition (p : Parser) : Parser := { info := p.info fn := fun c s => p.fn { c with savedPos? := none } s } def withForbidden (tk : Token) (p : Parser) : Parser := { info := p.info fn := fun c s => p.fn { c with forbiddenTk? := tk } s } def withoutForbidden (p : Parser) : Parser := { info := p.info fn := fun c s => p.fn { c with forbiddenTk? := none } s } def eoiFn : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else s.mkError "expected end of file" def eoi : Parser := { fn := eoiFn } /-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/ def TokenMap (α : Type) := RBMap Name (List α) Name.quickCmp namespace TokenMap def insert (map : TokenMap α) (k : Name) (v : α) : TokenMap α := match map.find? k with | none => RBMap.insert map k [v] | some vs => RBMap.insert map k (v::vs) instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩ instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩ instance : ForIn m (TokenMap α) (Name × List α) := inferInstanceAs (ForIn _ (RBMap ..) _) end TokenMap structure PrattParsingTables where leadingTable : TokenMap (Parser × Nat) := {} leadingParsers : List (Parser × Nat) := [] -- for supporting parsers we cannot obtain first token trailingTable : TokenMap (Parser × Nat) := {} trailingParsers : List (Parser × Nat) := [] -- for supporting parsers such as function application instance : Inhabited PrattParsingTables := ⟨{}⟩ /-- The type `LeadingIdentBehavior` specifies how the parsing table lookup function behaves for identifiers. The function `prattParser` uses two tables `leadingTable` and `trailingTable`. They map tokens to parsers. We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both` and `nonReservedSymbol` parser to implement the `tactic` parsers. The idea is to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users may still use these symbols as identifiers (e.g., naming a function). -/ inductive LeadingIdentBehavior where /-- `LeadingIdentBehavior.default`: if the leading token is an identifier, then `prattParser` just executes the parsers associated with the auxiliary token "ident". -/ | default /-- `LeadingIdentBehavior.symbol`: if the leading token is an identifier `<foo>`, and there are parsers `P` associated with the toek `<foo>`, then it executes `P`. Otherwise, it executes only the parsers associated with the auxiliary token "ident". -/ | symbol /-- `LeadingIdentBehavior.both`: if the leading token an identifier `<foo>`, the it executes the parsers associated with token `<foo>` and parsers associated with the auxiliary token "ident". -/ | both deriving Inhabited, BEq, Repr /-- Each parser category is implemented using a Pratt's parser. The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`. Users and plugins may define extra categories. The method ``` categoryParser `term prec ``` executes the Pratt's parser for category `term` with precedence `prec`. That is, only parsers with precedence at least `prec` are considered. The method `termParser prec` is equivalent to the method above. -/ structure ParserCategory where /-- The name of a declaration which will be used as the target of go-to-definition queries and from which doc strings will be extracted. This is a dummy declaration of type `Lean.Parser.Category` created by `declare_syntax_cat`, but for builtin categories the declaration is made manually and passed to `registerBuiltinParserAttribute`. -/ declName : Name /-- The list of syntax nodes that can parse into this category. This can be used to list all syntaxes in the category. -/ kinds : SyntaxNodeKindSet := {} /-- The parsing tables, which consist of a dynamic set of parser functions based on the syntaxes that have been declared so far. -/ tables : PrattParsingTables := {} /-- The `LeadingIdentBehavior`, which specifies how the parsing table lookup function behaves for the first identifier to be parsed. This is used by the `tactic` parser to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). -/ behavior : LeadingIdentBehavior deriving Inhabited abbrev ParserCategories := PersistentHashMap Name ParserCategory def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState × List α := let (s, stx) := peekToken c s let find (n : Name) : ParserState × List α := match map.find? n with | some as => (s, as) | _ => (s, []) match stx with | Except.ok (Syntax.atom _ sym) => find (Name.mkSimple sym) | Except.ok (Syntax.ident _ _ val _) => match behavior with | LeadingIdentBehavior.default => find identKind | LeadingIdentBehavior.symbol => match map.find? val with | some as => (s, as) | none => find identKind | LeadingIdentBehavior.both => match map.find? val with | some as => if val == identKind then (s, as) -- avoid running the same parsers twice else match map.find? identKind with | some as' => (s, as ++ as') | _ => (s, as) | none => find identKind | Except.ok (Syntax.node _ k _) => find k | Except.ok _ => (s, []) | Except.error s' => (s', []) abbrev CategoryParserFn := Name → ParserFn builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun (_ : Name) => whitespace builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get def categoryParserFn (catName : Name) : ParserFn := fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s def categoryParser (catName : Name) (prec : Nat) : Parser := { fn := fun c s => categoryParserFn catName { c with prec := prec } s } -- Define `termParser` here because we need it for antiquotations def termParser (prec : Nat := 0) : Parser := categoryParser `term prec -- ================== /-! # Antiquotations -/ -- ================== /-- Fail if previous token is immediately followed by ':'. -/ def checkNoImmediateColon : Parser := { fn := fun c s => let prev := s.stxStack.back if checkTailNoWs prev then let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == ':' then s.mkUnexpectedError "unexpected ':'" else s else s } def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s => match p c s with | s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected } } | s' => s' def setExpected (expected : List String) (p : Parser) : Parser := { fn := setExpectedFn expected p.fn, info := p.info } def pushNone : Parser := { fn := fun _ s => s.pushSyntax mkNullNode } -- We support three kinds of antiquotations: `$id`, `$_`, and `$(t)`, where `id` is a term identifier and `t` is a term. def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> decQuotDepth termParser >> symbolNoAntiquot ")") def antiquotExpr : Parser := identNoAntiquot <|> symbolNoAntiquot "_" <|> antiquotNestedExpr def tokenAntiquotFn : ParserFn := fun c s => Id.run do if s.hasError then return s let iniSz := s.stackSize let iniPos := s.pos let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s if s.hasError then return s.restore iniSz iniPos s.mkNode (`token_antiquot) (iniSz - 1) def tokenWithAntiquot (p : Parser) : Parser where fn c s := let s := p.fn c s -- fast check that is false in most cases if c.input.get s.pos == '%' then tokenAntiquotFn c s else s info := p.info def symbol (sym : String) : Parser := tokenWithAntiquot (symbolNoAntiquot sym) instance : Coe String Parser := ⟨fun s => symbol s ⟩ def nonReservedSymbol (sym : String) (includeIdent := false) : Parser := tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent) def unicodeSymbol (sym asciiSym : String) : Parser := tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym) /-- Define parser for `$e` (if anonymous == true) and `$e:name`. `kind` is embedded in the antiquotation's kind, and checked at syntax `match` unless `isPseudoKind` is false. Antiquotations can be escaped as in `$$e`, which produces the syntax tree for `$e`. -/ def mkAntiquot (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := false) : Parser := let kind := kind ++ (if isPseudoKind then `pseudo else Name.anonymous) ++ `antiquot let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name -- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different -- antiquotation kind via `noImmediateColon` let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP -- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> antiquotExpr >> nameP def withAntiquotFn (antiquotP p : ParserFn) (isCatAntiquot := false) : ParserFn := fun c s => -- fast check that is false in most cases if c.input.get s.pos == '$' then -- Do not allow antiquotation choice nodes here as `antiquotP` is the strictly more general -- antiquotation than any in `p`. -- If it is a category antiquotation, do not backtrack into the category at all as that would -- run *all* parsers of the category, and trailing parsers will later be applied anyway. orelseFnCore (antiquotBehavior := if isCatAntiquot then .acceptLhs else .takeLongest) antiquotP p c s else p c s /-- Optimized version of `mkAntiquot ... <|> p`. -/ def withAntiquot (antiquotP p : Parser) : Parser := { fn := withAntiquotFn antiquotP.fn p.fn, info := orelseInfo antiquotP.info p.info } def withoutInfo (p : Parser) : Parser := { fn := p.fn } /-- Parse `$[p]suffix`, e.g. `$[p],*`. -/ def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := let kind := kind ++ `antiquot_scope leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >> suffix private def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (suffix : ParserFn) : ParserFn := fun c s => Id.run do let iniSz := s.stackSize let iniPos := s.pos let s := suffix c s if s.hasError then return s.restore iniSz iniPos s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2) /-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/ def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser where info := andthenInfo p.info suffix.info fn c s := let s := p.fn c s -- fast check that is false in most cases if !s.hasError && s.stxStack.back.isAntiquots then withAntiquotSuffixSpliceFn kind suffix.fn c s else s def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) := -- prevent `p`'s info from being collected twice withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix) def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser := withAntiquot (mkAntiquot name kind anonymous) $ node kind p -- ========================= /-! # End of Antiquotations -/ -- ========================= def sepByElemParser (p : Parser) (sep : String) : Parser := withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*")) def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident _ _ catName _ => categoryParserFn catName ctx s | _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier") def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s } private def mkResult (s : ParserState) (iniSz : Nat) : ParserState := if s.stackSize == iniSz + 1 then s else s.mkNode nullKind iniSz -- throw error instead? def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => Id.run do let iniSz := s.stackSize let (s, ps) := indexed tables.leadingTable c s behavior if s.hasError then return s let ps := tables.leadingParsers ++ ps if ps.isEmpty then return s.mkError (toString kind) let s := longestMatchFn none ps c s mkResult s iniSz def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := withAntiquotFn (isCatAntiquot := true) antiquotParser (leadingParserAux kind tables behavior) def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := Id.run do let iniSz := s.stackSize let iniPos := s.pos let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default if s.hasError then -- Discard token parse errors and break the trailing loop instead. -- The error will be flagged when the next leading position is parsed, unless the token -- is in fact valid there (e.g. EOI at command level, no-longer forbidden token) return s.restore iniSz iniPos if ps.isEmpty && tables.trailingParsers.isEmpty then return s -- no available trailing parser let left := s.stxStack.back let s := s.popSyntax let s := trailingLoopStep tables left ps c s if s.hasError then -- Discard non-consuming parse errors and break the trailing loop instead, restoring `left`. -- This is necessary for fallback parsers like `app` that pretend to be always applicable. return if s.pos == iniPos then s.restore (iniSz - 1) iniPos |>.pushSyntax left else s trailingLoop tables c s /-- Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power. In our implementation, parsers have precedence instead. This method selects a parser (or more, via `longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example: ``` syntax term:51 "≤" ident "<" term "|" term : index ``` Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`. After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`. Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible, modular and easier to understand. `antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers. It should not be added to the regular leading parsers because it would heavily overlap with antiquotation parsers nested inside them. -/ def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s => let s := leadingParser kind tables behavior antiquotParser c s if s.hasError then s else trailingLoop tables c s def fieldIdxFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let curr := c.input.get iniPos if curr.isDigit && curr != '0' then let s := takeWhileFn (fun c => c.isDigit) c s mkNodeToken fieldIdxKind iniPos c s else s.mkErrorAt "field index" iniPos initStackSz def fieldIdx : Parser := withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) { fn := fieldIdxFn, info := mkAtomicInfo "fieldIdx" } def skip : Parser := { fn := fun _ s => s, info := epsilonInfo } end Parser namespace Syntax section variable {β : Type} {m : Type → Type} [Monad m] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := s.getArgs.foldlM (flip f) b def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := Id.run (s.foldArgsM f b) def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit := s.foldArgsM (fun s _ => f s) () end end Syntax end Lean
cc2d399d6250a062013ce423e7c3b231daca4fa0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/basis/bilinear.lean
59232b8c269982a4daa1988f136da2b0b488f61a
[ "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
2,567
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import linear_algebra.basis import linear_algebra.bilinear_map /-! # Lemmas about bilinear maps with a basis over each argument > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace linear_map variables {ι₁ ι₂ : Type*} variables {R R₂ S S₂ M N P : Type*} variables {Mₗ Nₗ Pₗ : Type*} variables [comm_semiring R] [comm_semiring S] [comm_semiring R₂] [comm_semiring S₂] section add_comm_monoid variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] variables [add_comm_monoid Mₗ] [add_comm_monoid Nₗ] [add_comm_monoid Pₗ] variables [module R M] [module S N] [module R₂ P] [module S₂ P] variables [module R Mₗ] [module R Nₗ] [module R Pₗ] variables [smul_comm_class S₂ R₂ P] variables {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂} variables (b₁ : basis ι₁ R M) (b₂ : basis ι₂ S N) (b₁' : basis ι₁ R Mₗ) (b₂' : basis ι₂ R Nₗ) /-- Two bilinear maps are equal when they are equal on all basis vectors. -/ lemma ext_basis {B B' : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (h : ∀ i j, B (b₁ i) (b₂ j) = B' (b₁ i) (b₂ j)) : B = B' := b₁.ext $ λ i, b₂.ext $ λ j, h i j /-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis. Version for semi-bilinear maps, see `sum_repr_mul_repr_mul` for the bilinear version. -/ lemma sum_repr_mul_repr_mulₛₗ {B : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (x y) : (b₁.repr x).sum (λ i xi, (b₂.repr y).sum (λ j yj, (ρ₁₂ xi) • (σ₁₂ yj) • B (b₁ i) (b₂ j))) = B x y := begin conv_rhs { rw [← b₁.total_repr x, ← b₂.total_repr y] }, simp_rw [finsupp.total_apply, finsupp.sum, map_sum₂, map_sum, linear_map.map_smulₛₗ₂, linear_map.map_smulₛₗ], end /-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis. Version for bilinear maps, see `sum_repr_mul_repr_mulₛₗ` for the semi-bilinear version. -/ lemma sum_repr_mul_repr_mul {B : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ} (x y) : (b₁'.repr x).sum (λ i xi, (b₂'.repr y).sum (λ j yj, xi • yj • B (b₁' i) (b₂' j))) = B x y := begin conv_rhs { rw [← b₁'.total_repr x, ← b₂'.total_repr y] }, simp_rw [finsupp.total_apply, finsupp.sum, map_sum₂, map_sum, linear_map.map_smul₂, linear_map.map_smul], end end add_comm_monoid end linear_map
2b92716b48504d39ba86a2283056e699c466a600
4727251e0cd73359b15b664c3170e5d754078599
/src/order/filter/ultrafilter.lean
f57ad6d34510d6a348e94b0d48b70ee5e3b3037f
[ "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
14,855
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, Yury Kudryashov -/ import order.filter.cofinite import order.zorn /-! # Ultrafilters An ultrafilter is a minimal (maximal in the set order) proper filter. In this file we define * `ultrafilter.of`: an ultrafilter that is less than or equal to a given filter; * `ultrafilter`: subtype of ultrafilters; * `ultrafilter.pure`: `pure x` as an `ultrafiler`; * `ultrafilter.map`, `ultrafilter.bind`, `ultrafilter.comap` : operations on ultrafilters; * `hyperfilter`: the ultrafilter extending the cofinite filter. -/ universes u v variables {α : Type u} {β : Type v} open set filter function open_locale classical filter /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ @[protect_proj] structure ultrafilter (α : Type*) extends filter α := (ne_bot' : ne_bot to_filter) (le_of_le : ∀ g, filter.ne_bot g → g ≤ to_filter → to_filter ≤ g) namespace ultrafilter variables {f g : ultrafilter α} {s t : set α} {p q : α → Prop} instance : has_coe_t (ultrafilter α) (filter α) := ⟨ultrafilter.to_filter⟩ instance : has_mem (set α) (ultrafilter α) := ⟨λ s f, s ∈ (f : filter α)⟩ lemma unique (f : ultrafilter α) {g : filter α} (h : g ≤ f) (hne : ne_bot g . tactic.apply_instance) : g = f := le_antisymm h $ f.le_of_le g hne h instance ne_bot (f : ultrafilter α) : ne_bot (f : filter α) := f.ne_bot' @[simp, norm_cast] lemma mem_coe : s ∈ (f : filter α) ↔ s ∈ f := iff.rfl lemma coe_injective : injective (coe : ultrafilter α → filter α) | ⟨f, h₁, h₂⟩ ⟨g, h₃, h₄⟩ rfl := by congr lemma eq_of_le {f g : ultrafilter α} (h : (f : filter α) ≤ g) : f = g := coe_injective (g.unique h) @[simp, norm_cast] lemma coe_le_coe {f g : ultrafilter α} : (f : filter α) ≤ g ↔ f = g := ⟨λ h, eq_of_le h, λ h, h ▸ le_rfl⟩ @[simp, norm_cast] lemma coe_inj : (f : filter α) = g ↔ f = g := coe_injective.eq_iff @[ext] lemma ext ⦃f g : ultrafilter α⦄ (h : ∀ s, s ∈ f ↔ s ∈ g) : f = g := coe_injective $ filter.ext h lemma le_of_inf_ne_bot (f : ultrafilter α) {g : filter α} (hg : ne_bot (↑f ⊓ g)) : ↑f ≤ g := le_of_inf_eq (f.unique inf_le_left hg) lemma le_of_inf_ne_bot' (f : ultrafilter α) {g : filter α} (hg : ne_bot (g ⊓ f)) : ↑f ≤ g := f.le_of_inf_ne_bot $ by rwa inf_comm @[simp] lemma compl_not_mem_iff : sᶜ ∉ f ↔ s ∈ f := ⟨λ hsc, le_principal_iff.1 $ f.le_of_inf_ne_bot ⟨λ h, hsc $ mem_of_eq_bot$ by rwa compl_compl⟩, compl_not_mem⟩ @[simp] lemma frequently_iff_eventually : (∃ᶠ x in f, p x) ↔ ∀ᶠ x in f, p x := compl_not_mem_iff alias frequently_iff_eventually ↔ filter.frequently.eventually _ lemma compl_mem_iff_not_mem : sᶜ ∈ f ↔ s ∉ f := by rw [← compl_not_mem_iff, compl_compl] lemma diff_mem_iff (f : ultrafilter α) : s \ t ∈ f ↔ s ∈ f ∧ t ∉ f := inter_mem_iff.trans $ and_congr iff.rfl compl_mem_iff_not_mem /-- If `sᶜ ∉ f ↔ s ∈ f`, then `f` is an ultrafilter. The other implication is given by `ultrafilter.compl_not_mem_iff`. -/ def of_compl_not_mem_iff (f : filter α) (h : ∀ s, sᶜ ∉ f ↔ s ∈ f) : ultrafilter α := { to_filter := f, ne_bot' := ⟨λ hf, by simpa [hf] using h⟩, le_of_le := λ g hg hgf s hs, (h s).1 $ λ hsc, by exactI compl_not_mem hs (hgf hsc) } lemma nonempty_of_mem (hs : s ∈ f) : s.nonempty := nonempty_of_mem hs lemma ne_empty_of_mem (hs : s ∈ f) : s ≠ ∅ := (nonempty_of_mem hs).ne_empty @[simp] lemma empty_not_mem : ∅ ∉ f := empty_not_mem f lemma mem_or_compl_mem (f : ultrafilter α) (s : set α) : s ∈ f ∨ sᶜ ∈ f := or_iff_not_imp_left.2 compl_mem_iff_not_mem.2 protected lemma em (f : ultrafilter α) (p : α → Prop) : (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x := f.mem_or_compl_mem {x | p x} lemma eventually_or : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x := ⟨λ H, (f.em p).imp_right $ λ hp, (H.and hp).mono $ λ x ⟨hx, hnx⟩, hx.resolve_left hnx, λ H, H.elim (λ hp, hp.mono $ λ x, or.inl) (λ hp, hp.mono $ λ x, or.inr)⟩ lemma union_mem_iff : s ∪ t ∈ f ↔ s ∈ f ∨ t ∈ f := eventually_or lemma eventually_not : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := compl_mem_iff_not_mem lemma eventually_imp : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x := by simp only [imp_iff_not_or, eventually_or, eventually_not] lemma finite_sUnion_mem_iff {s : set (set α)} (hs : finite s) : ⋃₀ s ∈ f ↔ ∃t∈s, t ∈ f := finite.induction_on hs (by simp) $ λ a s ha hs his, by simp [union_mem_iff, his, or_and_distrib_right, exists_or_distrib] lemma finite_bUnion_mem_iff {is : set β} {s : β → set α} (his : finite is) : (⋃i∈is, s i) ∈ f ↔ ∃i∈is, s i ∈ f := by simp only [← sUnion_image, finite_sUnion_mem_iff (his.image s), bex_image_iff] /-- Pushforward for ultrafilters. -/ def map (m : α → β) (f : ultrafilter α) : ultrafilter β := of_compl_not_mem_iff (map m f) $ λ s, @compl_not_mem_iff _ f (m ⁻¹' s) @[simp, norm_cast] lemma coe_map (m : α → β) (f : ultrafilter α) : (map m f : filter β) = filter.map m ↑f := rfl @[simp] lemma mem_map {m : α → β} {f : ultrafilter α} {s : set β} : s ∈ map m f ↔ m ⁻¹' s ∈ f := iff.rfl /-- The pullback of an ultrafilter along an injection whose range is large with respect to the given ultrafilter. -/ def comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : ultrafilter α := { to_filter := comap m u, ne_bot' := u.ne_bot'.comap_of_range_mem large, le_of_le := λ g hg hgu, by { resetI, simp only [← u.unique (map_le_iff_le_comap.2 hgu), comap_map inj, le_rfl] } } @[simp] lemma mem_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) {s : set α} : s ∈ u.comap inj large ↔ m '' s ∈ u := mem_comap_iff inj large @[simp] lemma coe_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : (u.comap inj large : filter α) = filter.comap m u := rfl /-- The principal ultrafilter associated to a point `x`. -/ instance : has_pure ultrafilter := ⟨λ α a, of_compl_not_mem_iff (pure a) $ λ s, by simp⟩ @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : ultrafilter α) ↔ a ∈ s := iff.rfl instance [inhabited α] : inhabited (ultrafilter α) := ⟨pure default⟩ instance [nonempty α] : nonempty (ultrafilter α) := nonempty.map pure infer_instance lemma eq_principal_of_finite_mem {f : ultrafilter α} {s : set α} (h : s.finite) (h' : s ∈ f) : ∃ x ∈ s, (f : filter α) = pure x := begin rw ← bUnion_of_singleton s at h', rcases (ultrafilter.finite_bUnion_mem_iff h).mp h' with ⟨a, has, haf⟩, use [a, has], change (f : filter α) = (pure a : ultrafilter α), rw [ultrafilter.coe_inj, ← ultrafilter.coe_le_coe], change (f : filter α) ≤ pure a, rwa [← principal_singleton, le_principal_iff] end /-- Monadic bind for ultrafilters, coming from the one on filters defined in terms of map and join.-/ def bind (f : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := of_compl_not_mem_iff (bind ↑f (λ x, ↑(m x))) $ λ s, by simp only [mem_bind', mem_coe, ← compl_mem_iff_not_mem, compl_set_of, compl_compl] instance has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance functor : functor ultrafilter := { map := @ultrafilter.map } instance monad : monad ultrafilter := { map := @ultrafilter.map } section local attribute [instance] filter.monad filter.is_lawful_monad instance is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, coe_injective (id_map f.1), pure_bind := assume α β a f, coe_injective (pure_bind a (coe ∘ f)), bind_assoc := assume α β γ f m₁ m₂, coe_injective (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, coe_injective (bind_pure_comp_eq_map f x.1) } end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_le (f : filter α) [h : ne_bot f] : ∃u : ultrafilter α, ↑u ≤ f := begin let τ := {f' // ne_bot f' ∧ f' ≤ f}, let r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, haveI := nonempty_of_ne_bot f, let top : τ := ⟨f, h, le_refl f⟩, let sup : Π(c:set τ), is_chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.1, infi_ne_bot_of_directed (is_chain.directed $ hc.insert $ λ ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ le_rfl⟩, have : ∀ c (hc : is_chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ le_rfl, have : (∃ (u : τ), ∀ (a : τ), r u a → r a u), from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), cases this with uτ hmin, exact ⟨⟨uτ.val, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩, uτ.property.right⟩ end alias exists_le ← filter.exists_ultrafilter_le /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def of (f : filter α) [ne_bot f] : ultrafilter α := classical.some (exists_le f) lemma of_le (f : filter α) [ne_bot f] : ↑(of f) ≤ f := classical.some_spec (exists_le f) lemma of_coe (f : ultrafilter α) : of ↑f = f := coe_inj.1 $ f.unique (of_le f) lemma exists_ultrafilter_of_finite_inter_nonempty (S : set (set α)) (cond : ∀ T : finset (set α), (↑T : set (set α)) ⊆ S → (⋂₀ (↑T : set (set α))).nonempty) : ∃ F : ultrafilter α, S ⊆ F.sets := begin suffices : ∃ F : filter α, ne_bot F ∧ S ⊆ F.sets, { rcases this with ⟨F, cond, hF⟩, resetI, obtain ⟨G : ultrafilter α, h1 : ↑G ≤ F⟩ := exists_le F, exact ⟨G, λ T hT, h1 (hF hT)⟩ }, use filter.generate S, refine ⟨_, λ T hT, filter.generate_sets.basic hT⟩, rw ← forall_mem_nonempty_iff_ne_bot, intros T hT, rcases mem_generate_iff.mp hT with ⟨A, h1, h2, h3⟩, let B := set.finite.to_finset h2, rw (show A = ↑B, by simp) at *, rcases cond B h1 with ⟨x, hx⟩, exact ⟨x, h3 hx⟩, end end ultrafilter namespace filter open ultrafilter lemma mem_iff_ultrafilter {s : set α} {f : filter α} : s ∈ f ↔ ∀ g : ultrafilter α, ↑g ≤ f → s ∈ g := begin refine ⟨λ hf g hg, hg hf, λ H, by_contra $ λ hf, _⟩, set g : filter ↥sᶜ := comap coe f, haveI : ne_bot g := comap_ne_bot_iff_compl_range.2 (by simpa [compl_set_of]), simpa using H ((of g).map coe) (map_le_iff_le_comap.mpr (of_le g)) end lemma le_iff_ultrafilter {f₁ f₂ : filter α} : f₁ ≤ f₂ ↔ ∀ g : ultrafilter α, ↑g ≤ f₁ → ↑g ≤ f₂ := ⟨λ h g h₁, h₁.trans h, λ h s hs, mem_iff_ultrafilter.2 $ λ g hg, h g hg hs⟩ /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma supr_ultrafilter_le_eq (f : filter α) : (⨆ (g : ultrafilter α) (hg : ↑g ≤ f), (g : filter α)) = f := eq_of_forall_ge_iff $ λ f', by simp only [supr_le_iff, ← le_iff_ultrafilter] /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g : ultrafilter α, ↑g ≤ l₁ → tendsto f g l₂ := by simpa only [tendsto_iff_comap] using le_iff_ultrafilter lemma exists_ultrafilter_iff {f : filter α} : (∃ (u : ultrafilter α), ↑u ≤ f) ↔ ne_bot f := ⟨λ ⟨u, uf⟩, ne_bot_of_le uf, λ h, @exists_ultrafilter_le _ _ h⟩ lemma forall_ne_bot_le_iff {g : filter α} {p : filter α → Prop} (hp : monotone p) : (∀ f : filter α, ne_bot f → f ≤ g → p f) ↔ ∀ f : ultrafilter α, ↑f ≤ g → p f := begin refine ⟨λ H f hf, H f f.ne_bot hf, _⟩, introsI H f hf hfg, exact hp (of_le f) (H _ ((of_le f).trans hfg)) end section hyperfilter variables (α) [infinite α] /-- The ultrafilter extending the cofinite filter. -/ noncomputable def hyperfilter : ultrafilter α := ultrafilter.of cofinite variable {α} lemma hyperfilter_le_cofinite : ↑(hyperfilter α) ≤ @cofinite α := ultrafilter.of_le cofinite @[simp] lemma bot_ne_hyperfilter : (⊥ : filter α) ≠ hyperfilter α := (by apply_instance : ne_bot ↑(hyperfilter α)).1.symm theorem nmem_hyperfilter_of_finite {s : set α} (hf : s.finite) : s ∉ hyperfilter α := λ hy, compl_not_mem hy $ hyperfilter_le_cofinite hf.compl_mem_cofinite alias nmem_hyperfilter_of_finite ← set.finite.nmem_hyperfilter theorem compl_mem_hyperfilter_of_finite {s : set α} (hf : set.finite s) : sᶜ ∈ hyperfilter α := compl_mem_iff_not_mem.2 hf.nmem_hyperfilter alias compl_mem_hyperfilter_of_finite ← set.finite.compl_mem_hyperfilter theorem mem_hyperfilter_of_finite_compl {s : set α} (hf : set.finite sᶜ) : s ∈ hyperfilter α := compl_compl s ▸ hf.compl_mem_hyperfilter end hyperfilter end filter namespace ultrafilter open filter variables {m : α → β} {s : set α} {g : ultrafilter β} lemma comap_inf_principal_ne_bot_of_image_mem (h : m '' s ∈ g) : (filter.comap m g ⊓ 𝓟 s).ne_bot := filter.comap_inf_principal_ne_bot_of_image_mem g.ne_bot h /-- Ultrafilter extending the inf of a comapped ultrafilter and a principal ultrafilter. -/ noncomputable def of_comap_inf_principal (h : m '' s ∈ g) : ultrafilter α := @of _ (filter.comap m g ⊓ 𝓟 s) (comap_inf_principal_ne_bot_of_image_mem h) lemma of_comap_inf_principal_mem (h : m '' s ∈ g) : s ∈ of_comap_inf_principal h := begin let f := filter.comap m g ⊓ 𝓟 s, haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h, have : s ∈ f := mem_inf_of_right (mem_principal_self s), exact le_def.mp (of_le _) s this end lemma of_comap_inf_principal_eq_of_map (h : m '' s ∈ g) : (of_comap_inf_principal h).map m = g := begin let f := filter.comap m g ⊓ 𝓟 s, haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h, apply eq_of_le, calc filter.map m (of f) ≤ filter.map m f : map_mono (of_le _) ... ≤ (filter.map m $ filter.comap m g) ⊓ filter.map m (𝓟 s) : map_inf_le ... = (filter.map m $ filter.comap m g) ⊓ (𝓟 $ m '' s) : by rw map_principal ... ≤ g ⊓ (𝓟 $ m '' s) : inf_le_inf_right _ map_comap_le ... = g : inf_of_le_left (le_principal_iff.mpr h) end end ultrafilter
e15ccee1a1b61b8fc7c5c4a3f0f7ec24b8078d07
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/run/1590.lean
90a15ff3eb34697482b07666a76c66c5b9c1cd94
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
102
lean
#check `(true.intro) #check (`(true.intro) : expr) variables (h : true) [reflected h] #check `(id h)
427977ee29f4b29bc39f13dcc3d2a61601aa2701
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/monoidal/types.lean
a96a3d16be555c7b6b198165a3f95081e30d83fb
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,691
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import category_theory.monoidal.of_chosen_finite_products import category_theory.limits.shapes.types import logic.equiv.fin /-! # The category of types is a symmetric monoidal category -/ open category_theory open category_theory.limits open tactic universes v u namespace category_theory instance types_monoidal : monoidal_category.{u} (Type u) := monoidal_of_chosen_finite_products (types.terminal_limit_cone) (types.binary_product_limit_cone) instance types_symmetric : symmetric_category.{u} (Type u) := symmetric_of_chosen_finite_products (types.terminal_limit_cone) (types.binary_product_limit_cone) @[simp] lemma tensor_apply {W X Y Z : Type u} (f : W ⟶ X) (g : Y ⟶ Z) (p : W ⊗ Y) : (f ⊗ g) p = (f p.1, g p.2) := rfl @[simp] lemma left_unitor_hom_apply {X : Type u} {x : X} {p : punit} : ((λ_ X).hom : (𝟙_ (Type u)) ⊗ X → X) (p, x) = x := rfl @[simp] lemma left_unitor_inv_apply {X : Type u} {x : X} : ((λ_ X).inv : X ⟶ (𝟙_ (Type u)) ⊗ X) x = (punit.star, x) := rfl @[simp] lemma right_unitor_hom_apply {X : Type u} {x : X} {p : punit} : ((ρ_ X).hom : X ⊗ (𝟙_ (Type u)) → X) (x, p) = x := rfl @[simp] lemma right_unitor_inv_apply {X : Type u} {x : X} : ((ρ_ X).inv : X ⟶ X ⊗ (𝟙_ (Type u))) x = (x, punit.star) := rfl @[simp] lemma associator_hom_apply {X Y Z : Type u} {x : X} {y : Y} {z : Z} : ((α_ X Y Z).hom : (X ⊗ Y) ⊗ Z → X ⊗ (Y ⊗ Z)) ((x, y), z) = (x, (y, z)) := rfl @[simp] lemma associator_inv_apply {X Y Z : Type u} {x : X} {y : Y} {z : Z} : ((α_ X Y Z).inv : X ⊗ (Y ⊗ Z) → (X ⊗ Y) ⊗ Z) (x, (y, z)) = ((x, y), z) := rfl @[simp] lemma braiding_hom_apply {X Y : Type u} {x : X} {y : Y} : ((β_ X Y).hom : X ⊗ Y → Y ⊗ X) (x, y) = (y, x) := rfl @[simp] lemma braiding_inv_apply {X Y : Type u} {x : X} {y : Y} : ((β_ X Y).inv : Y ⊗ X → X ⊗ Y) (y, x) = (x, y) := rfl open opposite open monoidal_category /-- `(𝟙_ C ⟶ -)` is a lax monoidal functor to `Type`. -/ def coyoneda_tensor_unit (C : Type u) [category.{v} C] [monoidal_category C] : lax_monoidal_functor C (Type v) := { ε := λ p, 𝟙 _, μ := λ X Y p, (λ_ (𝟙_ C)).inv ≫ (p.1 ⊗ p.2), μ_natural' := by tidy, associativity' := λ X Y Z, begin ext ⟨⟨f, g⟩, h⟩, dsimp at f g h, dsimp, simp only [iso.cancel_iso_inv_left, category.assoc], conv_lhs { rw [←category.id_comp h, tensor_comp, category.assoc, associator_naturality, ←category.assoc, unitors_inv_equal, triangle_assoc_comp_right_inv], }, conv_rhs { rw [←category.id_comp f, tensor_comp], }, end, left_unitality' := by tidy, right_unitality' := λ X, begin ext ⟨f, ⟨⟩⟩, dsimp at f, dsimp, simp only [category.assoc], rw [right_unitor_naturality, unitors_inv_equal, iso.inv_hom_id_assoc], end, ..coyoneda.obj (op (𝟙_ C)) }. noncomputable theory /-- If `F` is a monoidal functor out of `Type`, it takes the (n+1)st cartesian power of a type to the image of that type, tensored with the image of the nth cartesian power. -/ -- We don't yet have an API for tensor products indexed by finite ordered types, -- but it would be nice to state how monoidal functors preserve these. def monoidal_functor.map_pi {C : Type*} [category C] [monoidal_category C] (F : monoidal_functor Type* C) (n : ℕ) (β : Type*) : F.obj (fin (n+1) → β) ≅ F.obj β ⊗ F.obj (fin n → β) := functor.map_iso _ (equiv.pi_fin_succ n β).to_iso ≪≫ (as_iso (F.μ β (fin n → β))).symm end category_theory
6c52d2721f6de0506755491e792717c671612563
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/fix1.lean
2079545e46735bed068254c878a4837594e71ef8
[ "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
612
lean
def foo (rec : Nat → Nat → Nat) : Nat → Nat → Nat | 0 a := a | (n+1) a := rec n a + a + rec n (a+1) partial def fix' (f: (Nat → Nat → Nat) → (Nat → Nat → Nat)) : Nat → Nat → Nat | a b := f fix' a b def prof {α : Type} (msg : String) (p : IO α) : IO α := let msg := "Time for '" ++ msg ++ "':" in timeit msg p def fix_test (n : Nat) : IO Unit := IO.println (fix foo n 10) def fix'_test (n : Nat) : IO Unit := IO.println (fix' foo n 10) def main (xs : List String) : IO Unit := prof "native fix" (fix_test xs.head.toNat) *> prof "fix in lean" (fix'_test xs.head.toNat) *> pure ()
892261f9fb2efce153c795b6389244dde5330a61
93b17e1ec33b7fd9fb0d8f958cdc9f2214b131a2
/src/sep/affineScheme.lean
d0fe462c2f41722ee8b2eb62f9423a563f3979ff
[]
no_license
intoverflow/timesink
93f8535cd504bc128ba1b57ce1eda4efc74e5136
c25be4a2edb866ad0a9a87ee79e209afad6ab303
refs/heads/master
1,620,033,920,087
1,524,995,105,000
1,524,995,105,000
120,576,102
1
0
null
null
null
null
UTF-8
Lean
false
false
14,087
lean
/- Affine separation schemes - -/ import .spec import .localization import ..top.sheaf namespace Sep universes ℓ ℓ₁ ℓ₂ open Top def rehome_prime {X : OrdAlg.{ℓ}} {u o : X.Top.OI} (q : {p // p ∈ X.Top.Open u}) (H : X.Top.Open u ⊆ X.Top.Open o) : {p // p ∈ X.Top.Open o} := { val := q.val , property := H q.property } structure ClosedAlg := (alg : OrdAlg.{ℓ}) (closed : alg.ord.Closed) def ClosedAlg.Pt (X : ClosedAlg) := X.alg.Pt def ClosedAlg.Top (X : ClosedAlg) := X.alg.Top def ClosedAlg.BasicOpen (X : ClosedAlg) := X.alg.BasicOpen def ClosedAlg.ZeroPt (X : ClosedAlg) := X.alg.ZeroPt def PrimeAlg {X : ClosedAlg.{ℓ}} (p : X.alg.Pt) : OrdAlg.{ℓ} := X.alg.Localize X.closed p.set.Compl begin apply Set.Prime.Complement_JoinClosed, apply p.prime end begin apply Confined.Local, rw Set.ComplCompl, intros x Hx, rw p.fixed.symm, exact Hx end def BasisAlg {X : ClosedAlg.{ℓ}} (S : X.alg.BasicOpen) (SJC : S.set.JoinClosed) : OrdAlg.{ℓ} := X.alg.Localize X.closed S.set SJC begin intros x H, exact or.inl (S.fixed H) end structure Sec {X : ClosedAlg.{ℓ}} (o : X.Top.OI) : Type.{ℓ} := (fn : ∀ (p : {p // p ∈ X.Top.Open o}) , (PrimeAlg p.val).alg.τ) (continuous : ∀ (p : {p // p ∈ X.Top.Open o}) , ∃ (u : {u // X.Top.Open u ⊆ X.Top.Open o}) , p.val ∈ X.Top.Open u.val ∧ (∀ (q : {p // p ∈ X.Top.Open u}) , fn p ≤ fn (rehome_prime q u.property))) -- , fn (rehome_prime q u.property) = a)) def Sec.eq {X : ClosedAlg.{ℓ}} {o : X.Top.OI} (s₁ s₂ : Sec o) (E : ∀ (p : {p // p ∈ X.Top.Open o}) , (s₁.fn p) = (s₂.fn p)) : s₁ = s₂ := begin cases s₁ with s₁ Hs₁, cases s₂ with s₂ Hs₂, have E' : s₁ = s₂, from begin apply funext, intro p, apply E end, subst E' end def res {X : ClosedAlg.{ℓ}} {o u : X.Top.OI} (H : X.Top.Open u ⊆ X.Top.Open o) : Sec o → Sec u := λ s , { fn := λ p, s.fn (rehome_prime p H) , continuous := sorry } def SecAlg {X : ClosedAlg.{ℓ}} (o : X.Top.OI) : OrdAlg.{ℓ} := { alg := { τ := Sec o , join := λ s₁ s₂ s₃ , ∀ (p : {p // p ∈ X.Top.Open o}) , (PrimeAlg p.val).alg.join (s₁.fn p) (s₂.fn p) (s₃.fn p) , comm := λ s₁ s₃ s₃ J p, (PrimeAlg p.val).alg.comm (J p) , assoc := λ s₁ s₂ s₃ s₁₂ s₁₂₃ J₁₂ J₁₂₃ P C , sorry -- , C { x := { fn := λ p, begin end -- , continuous := begin end -- } -- , J₁ := begin end -- , J₂ := begin end -- } } , ord := λ s₁ s₂ , (∀ (p : {p // p ∈ X.Top.Open o}) , (PrimeAlg p.val).ord (s₁.fn p) (s₂.fn p)) , refl := λ s p , (PrimeAlg p.val).refl (s.fn p) , trans := λ s₁ s₂ s₃ L₁₂ L₂₃ p , (PrimeAlg p.val).trans _ _ _ (L₁₂ p) (L₂₃ p) } def SecAlg.UpClosed (X : OrdAlg.{ℓ}) (XUC : X.ord.UpClosed) (o : X.Top.OI) : (@SecAlg { ClosedAlg . alg := X , closed := or.inl @XUC } o).ord.UpClosed := begin exact sorry end def SecAlg.DownClosed (X : OrdAlg.{ℓ}) (XDC : X.ord.DownClosed) (o : X.Top.OI) : (@SecAlg { ClosedAlg . alg := X , closed := or.inr @XDC } o).ord.DownClosed := begin exact sorry end def SecAlg.Closed {X : ClosedAlg.{ℓ}} (o : X.Top.OI) : (SecAlg o).ord.Closed := begin cases X with X XC, cases XC with XC XC, { apply or.inl, apply SecAlg.UpClosed }, { apply or.inr, apply SecAlg.DownClosed } end def ClosedAlg.StructPreSh (X : ClosedAlg.{ℓ}) : PreSheaf X.Top OrdAlgCat := { Section := SecAlg , ρ := λ U₁ U₂ H , { rel := λ s₁ s₂, s₂ = res H s₁ , total := λ s, exists.intro _ rfl , action := sorry } , ρ_id := λ U H , begin exact sorry end , ρ_circ := λ U₁ U₂ U₃ H₁₂ H₂₃ H₁₃ , begin exact sorry end } def ClosedAlg.StructSh (X : ClosedAlg.{ℓ}) : Top.Sheaf X.Top OrdAlgCat OrdAlgCat.HasProducts := { sh := X.StructPreSh , glue := λ U UU Ucover, sorry } def ClosedAlg.to_section (X : ClosedAlg.{ℓ}) (S : X.BasicOpen) (SJC : S.set.JoinClosed) : (BasisAlg S SJC).alg.τ → (X.StructSh.sh.Section (eq S)).alg.τ := λ a₀ , { fn := λ p, a₀ , continuous := λ p, exists.intro { val := eq S , property := λ q Hq, Hq } begin apply and.intro p.property, intro q, apply OrdAlg.refl end } def to_section.inj {X : ClosedAlg.{ℓ}} {S : X.BasicOpen} (SJC : S.set.JoinClosed) {x₁ x₂ : X.alg.alg.τ} (E : X.to_section S SJC x₁ = X.to_section S SJC x₂) : x₁ = x₂ := begin have Q₁ := congr_arg (λ (x : Sec (eq S)), x.fn) E, have Q₂ := congr_fun Q₁ { val := X.ZeroPt , property := ZeroPt.Everywhere }, exact Q₂ end def to_section.surj {X : ClosedAlg.{ℓ}} {S : X.BasicOpen} (SJC : S.set.JoinClosed) (s : Sec (eq S)) : ∃ x, (X.StructSh.sh.Section (eq S)).ord s (X.to_section S SJC x) := begin existsi s.fn { val := X.ZeroPt, property := ZeroPt.Everywhere }, intro p, have Q := s.continuous p, cases Q with U Q, cases Q with Hp E, have E' := E { val := X.ZeroPt , property := begin cases Hp with V H, cases H with HV HVp, cases HV with V' HV', cases HV' with HV' E, subst E, refine exists.intro _ (exists.intro (exists.intro V' (and.intro HV' rfl)) _), apply ZeroPt.BasisEverywhere end }, exact E' end -- def OrdAlg.to_section__from_section {X : ClosedAlg.{ℓ}} -- (S : X.BasicOpen) (SJC : S.set.JoinClosed) -- : FunRel (X.to_section S SJC) ∘ InvFunRel (X.to_section S SJC) = Alg.IdRel _ -- := begin -- apply funext, intro x, apply funext, intro y, -- apply eq.symm, apply iff.to_eq, apply iff.intro, -- { intro H, -- have Q := to_section.surj SJC x, -- cases Q with y' E, subst E, -- have Q := to_section.surj SJC y, -- cases Q with y₀ E, subst E, -- refine exists.intro y₀ (and.intro H rfl), -- }, -- { intro H, cases H with w H, -- cases H with E₁ E₂, -- have E₁' := E₁.symm, subst E₁', clear E₁, -- have E₂' := E₂.symm, subst E₂', clear E₂, -- exact rfl -- } -- end -- def OrdAlg.from_section__to_section {X : ClosedAlg.{ℓ}} -- (S : X.BasicOpen) (SJC : S.set.JoinClosed) -- : InvFunRel (X.to_section S SJC) ∘ FunRel (X.to_section S SJC) = Alg.IdRel _ -- := begin -- apply funext, intro x, apply funext, intro y, -- apply eq.symm, apply iff.to_eq, apply iff.intro, -- { intro E, have E' : x = y := E, subst E', clear E, -- exact exists.intro (X.to_section S SJC x) (and.intro rfl rfl) -- }, -- { intro H, cases H with w H, -- cases H with E₁ E₂, -- have E₁' := E₁.symm, subst E₁', clear E₁, -- have E₂' := to_section.inj SJC E₂, subst E₂', clear E₂, -- exact rfl -- } -- end def ToSection {X : ClosedAlg.{ℓ}} (S : X.BasicOpen) (SJC : S.set.JoinClosed) : OrdRel (BasisAlg S SJC) (X.StructSh.sh.Section (eq S)) := (FunRel (X.to_section S SJC)).OrdRel (λ x, exists.intro _ rfl) def FromSection {X : ClosedAlg.{ℓ}} (S : X.BasicOpen) (SJC : S.set.JoinClosed) : OrdRel (X.StructSh.sh.Section (eq S)) (BasisAlg S SJC) := { rel := λ x y, x ≤ ClosedAlg.to_section X S SJC y , total := to_section.surj SJC , action := begin apply funext, intro x, apply funext, intro y, apply iff.to_eq, apply iff.intro, { intro H, cases H with y' H, cases H with H Hy, cases H with x' H, cases H with H Hx, apply OrdAlg.trans _ _ _ _ H, apply OrdAlg.trans _ _ _ _ Hx, intro p, dsimp [ClosedAlg.to_section], cases Hy, { apply Localization.locl.base, exact Rxy }, { refine Localization.locl.join _ Rx Ry J, intro F, cases p with p Hp, cases Hp with U Hp, cases Hp with H Hp, cases H with U₀ H, cases H with H E, subst E, have E := H.symm, subst E, apply cast (congr_fun Hp s), exact and.intro Hs F } }, { intro H, refine exists.intro _ (and.intro _ (OrdAlg.refl _ _)), refine exists.intro _ (and.intro _ H), intro p, apply OrdAlg.refl } end } def ToSection_FromSection {X : ClosedAlg.{ℓ}} (S : X.BasicOpen) (SJC : S.set.JoinClosed) : ToSection S SJC ∘∘ FromSection S SJC = OrdAlg.IdRel _ := begin apply OrdRel.eq, apply funext, intro x, apply funext, intro y, apply eq.symm, apply iff.to_eq, apply iff.intro, { exact sorry }, { exact sorry } end def FromSection_ToSection {X : ClosedAlg.{ℓ}} (S : X.BasicOpen) (SJC : S.set.JoinClosed) : FromSection S SJC ∘∘ ToSection S SJC = OrdAlg.IdRel _ := begin apply OrdRel.eq, apply funext, intro x, apply funext, intro y, apply eq.symm, apply iff.to_eq, apply iff.intro, { exact sorry }, { exact sorry } end def ClosedAlg.Spec (X : ClosedAlg.{ℓ}) : ShSpace OrdAlgCat := { Pt := X.Pt , Top := X.Top , Prod := OrdAlgCat.HasProducts , Sh := X.StructSh } def PrimeRel.Spec {A : ClosedAlg.{ℓ₁}} {B : ClosedAlg.{ℓ₁}} (r : OrdRel A.alg B.alg) (rP : r.PrimeRel) : ShHom B.Spec A.Spec := { map := PrimeRel.Map r rP , sh := { hom := λ U, { rel := λ s t , ∀ (p : {p // p ∈ B.Top.Open (((PrimeRel.Map r rP).preimage U).val)}) , r.rel (s.fn { val := (PrimeRel.Map r rP).map p.val , property := (PrimeRel.Map r rP).in_preimage p }) (t.fn p) , total := sorry , action := sorry } , natural := sorry } } def JoinRel.Spec {A : ClosedAlg.{ℓ₁}} {B : ClosedAlg.{ℓ₁}} (r : OrdRel A.alg B.alg) (rJ : r.JoinRel) : ShHom A.Spec B.Spec := { map := JoinRel.Map r rJ , sh := { hom := λ U, { rel := λ s t , ∀ (p : {p // p ∈ A.Top.Open (((JoinRel.Map r rJ).preimage U).val)}) , r.rel (t.fn p) (s.fn { val := (JoinRel.Map r rJ).map p.val , property := (JoinRel.Map r rJ).in_preimage p }) , total := sorry , action := begin apply funext, intro s, apply funext, intro t, apply iff.to_eq, apply iff.intro, { intro H, intro q, cases H with t' H, cases H with H Lt, cases H with s' H, cases H with Ls H, have Q := H q, clear H, -- apply cast (congr_fun (congr_fun r.action _) _), -- refine exists.intro _ (and.intro (exists.intro _ (and.intro _ Q)) _), -- exact sorry }, { exact sorry } end } , natural := sorry } } def JoinRel.Spec.JoinRel {A : ClosedAlg.{ℓ₁}} {B : ClosedAlg.{ℓ₁}} (r : OrdRel A.alg B.alg) (rJ : r.JoinRel) (rDC : r.rel.DownClosed) (p : A.Pt) : ((JoinRel.Spec r rJ).sh.hom (eq (Nhbd ((JoinRel.Map r rJ).map p)))).rel.Flip.DownClosed := begin intros x₁ x₂ y₁ y₂ y₃ R₁ R₂ J, have Hp : A.Top.Open (((JoinRel.Map r rJ).preimage (eq (Nhbd ((JoinRel.Map r rJ).map p)))).val) p, from begin existsi A.alg.OpenBasis.Open (Nhbd p), refine exists.intro _ Nhbd.mem, refine exists.intro (Nhbd p) (and.intro _ rfl), exact sorry end, have R₁' := R₁ { val := p, property := Hp }, clear R₁, have R₂' := R₂ { val := p, property := Hp }, clear R₂, have Jy' := J { val := (JoinRel.Map r rJ).map p , property := (JoinRel.Map r rJ).in_preimage { val := p, property := Hp } }, clear J, dsimp at *, have Q := rDC R₁' R₂' Jy', -- cases Q with x₃ Q, cases Q with R₃ Jx, refine exists.intro { fn := λ p, x₃ , continuous := sorry } _, apply and.intro, { intro q, simp, exact sorry -- continuity of y₃ }, { intro q, simp, exact sorry -- continuity of x₁ and x₂ } end end Sep
d054b23116abcd3dcadb66f2bd4788ddbbe4d952
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world4/level2.lean
9e512a7e3eff6093569d97f2d22e3b185cdfbc4c
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
314
lean
import game.world4.level1 -- hide namespace mynat -- hide /- # Power World ## Level 2: `zero_pow_succ` -/ /- Lemma For all naturals $m$, $0 ^{succ (m)} = 0$. -/ lemma zero_pow_succ (m : mynat) : (0 : mynat) ^ (succ m) = 0 := begin [nat_num_game] rw pow_succ, rw mul_zero, refl, end end mynat -- hide
ea24ee530bd8cb136d7a0068567d36f94eca9a1d
e1fb097d56131b99641125824bf370019b30ab6b
/src/mywork/lecture_4.lean
1d1201c402e9547e200baa1f6c24a2865ee9d4ae
[]
no_license
pcarey627/CS-2120-Base-Repository
fc18fc35b7d40928af7637625077abff6055271c
434b2391b131e04cbc3be60dc0320639d0e20fb4
refs/heads/main
1,690,861,648,224
1,632,323,226,000
1,632,323,226,000
399,946,234
0
0
null
null
null
null
UTF-8
Lean
false
false
3,921
lean
/- In this file, we give formal statements (our version) of the two axioms of equality. We also present Lean's versions of these rules, and show how you can use them without giving all of the arguments explicitly. -/ /- AXIOMS Everything is equal to itself. A bit more formally, if one is given a type, T, and a value, t, of this type, then you may have a proof of t = t "for free. -/ /- Introduction rule for equality (How we can build a proof of an equality) -/ axiom eq_refl : ∀ (T : Type) -- if T is any type (of thing) (t : T), -- and t is thing of that type, T t = t -- the result type: proof of t = t /- This is an example of an introduction rule. INFERENCE RULE #2/2: SUBSTITUTION OF EQUALS FOR EQUALS Given any type, T, of objects, and any *property*, P, of objects of this type, if you know x has property P (written as P x) and you know that x = y, then you can deduce that y has property P. -/ /- Elimination rule for equality. (How we can use a proof of an equality.) -/ axiom eq_subst : ∀ (T : Type) -- if T is a type (P : T → Prop) -- and P is a property of T objects (x y : T) -- and x and y are T objects (e : x = y) -- and you have a proof that x = y (px : P x), -- and you have a proof that x has property P P y -- then you can deduce (and get a proof) of P y /- The Lean versions of these axioms are called eq.refl and eq.subst. They're defined in ways that allow (and require) one not to give the T, P, x, or y parameters explicitly when applying eq_subst. More details come later. -/ /- We will now present formal proofs of our two theorems in this style. -/ /- CONJECTURES: a proposition which you believe is true but don't yet have a proof of -/ -- We define eq_symm to be the proposition at issue -- Note: Prop is the type of all propositions in Lean -- And each proposition is itself a type: of it proofs def eq_symm : Prop := ∀ (T : Type) (x y : T), x = y → y = x -- We define eq_trans formally in the same basic way def eq_trans : Prop := ∀ (T : Type) (x y z : T), x = y → y = z → x = z /- PROOFS: From conjectures to theorems -/ /- Proofs: equality is symmetric. -/ example : eq_symm := begin unfold eq_symm, -- replace name with definition assume T x y e, -- assume arbitrary values rw e, -- rw uses eq.subst to replace x with y -- and then applies eq.refl automatically -- QED. end /- A fundamental idea is that any proof is as good as any other for establishing the truth of a proposition. Here is an equally good alternative proof (or to be correct, proof-generating scripts in the "proof tactic" language" of the Lean Prover. -/ example : eq_symm := begin unfold eq_symm, -- replace name with definition assume T x y e, -- assume arbitrary values apply eq.subst e, -- apply axiom 2, substitutability exact eq.refl x, -- apply axiom 1, reflexivity -- QED. end /- Proof: equality is transitive. -/ example : eq_trans := begin unfold eq_trans, assume T, assume x y z, assume e1, assume e2, rw e1, exact e2, end /- Note: Lean defines these rules as - eq.refl - eq.subst - eq.symm - eq.trans -/ /- Practice -/ example : ∀ (T : Type) (x y z : T), x = y → y = z → z = x := begin /- assume T, assume (x : T), assume (y:T), assume (z: T), -/ assume T x y z, assume h1 h2, apply eq.symm _, apply eq.trans h1 h2, end /- INTRODUCTION and ELIMINATION RULES An introduction rule creates a proof. Elimination rules use proofs as some of their inputs. For equals - introduction rule: eq.refl - elimination rule: eq.subst For ∀ x, P x - introduction rule: assume arbitrary x, then show P x - elimination rule: next time! For P -> Q (implies) - introduction rule: assume arbitrary P, then show Q - elimination rule: next time -/
2c0c96bea751c42d26a167db7bf05556260f5442
4fa161becb8ce7378a709f5992a594764699e268
/src/group_theory/congruence.lean
0a1e561a07e1c76b8236bd7e9e6888160ee1eae1
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
42,764
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.pi_instances /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_beta {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw Sup_eq_con_gen, congr, ext x y, erw [Sup_image, supr_apply, supr_apply, supr_Prop_eq], simp only [Sup_image, supr_Prop_eq, supr_apply, supr_Prop_eq, exists_prop], refl, end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : ((≤) : {d // c ≤ d} → {d // c ≤ d} → Prop) ≃o ((≤) : con c.quotient → con c.quotient → Prop) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy⟩ } end end -- Monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive add_monoid "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive add_comm_monoid "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive add_submonoid "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive of_add_submonoid "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive to_add_submonoid "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive to_add_submonoid_inj] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective (ker_lift f) ⟨ker_lift_injective f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end con
968e8d93a1417bdb673b744829a02fd2da047583
a339bc2ac96174381fb610f4b2e1ba42df2be819
/hott/types/fin.hlean
c9f2328e0b07ed31af3ec0b04e2b7d0ed2252eb4
[ "Apache-2.0" ]
permissive
kalfsvag/lean2
25b2dccc07a98e5aa20f9a11229831f9d3edf2e7
4d4a0c7c53a9922c5f630f6f8ebdccf7ddef2cc7
refs/heads/master
1,610,513,122,164
1,483,135,198,000
1,483,135,198,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,732
hlean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Haitao Zhang, Leonardo de Moura, Jakob von Raumer, Floris van Doorn Finite ordinal types. -/ import types.list algebra.bundled function logic types.prod types.sum types.nat.div open eq function list equiv is_trunc algebra sigma sum nat structure fin (n : nat) := (val : nat) (is_lt : val < n) definition less_than [reducible] := fin namespace fin attribute fin.val [coercion] section def_equal variable {n : nat} protected definition sigma_char : fin n ≃ Σ (val : nat), val < n := begin fapply equiv.MK, intro i, cases i with i ilt, apply dpair i ilt, intro s, cases s with i ilt, apply fin.mk i ilt, intro s, cases s with i ilt, reflexivity, intro i, cases i with i ilt, reflexivity end definition is_set_fin [instance] : is_set (fin n) := begin assert H : Πa, is_set (a < n), exact _, -- I don't know why this is necessary apply is_trunc_equiv_closed_rev, apply fin.sigma_char, end definition eq_of_veq : Π {i j : fin n}, (val i) = j → i = j := begin intro i j, cases i with i ilt, cases j with j jlt, esimp, intro p, induction p, apply ap (mk i), apply !is_prop.elim end definition fin_eq := @eq_of_veq definition eq_of_veq_refl (i : fin n) : eq_of_veq (refl (val i)) = idp := !is_prop.elim definition veq_of_eq : Π {i j : fin n}, i = j → (val i) = j := by intro i j P; apply ap val; exact P definition eq_iff_veq {i j : fin n} : (val i) = j ↔ i = j := pair eq_of_veq veq_of_eq definition val_inj := @eq_of_veq n end def_equal section decidable open decidable protected definition has_decidable_eq [instance] (n : nat) : Π (i j : fin n), decidable (i = j) := begin intros i j, apply decidable_of_decidable_of_iff, apply nat.has_decidable_eq i j, apply eq_iff_veq, end end decidable /-lemma dinj_lt (n : nat) : dinj (λ i, i < n) fin.mk := take a1 a2 Pa1 Pa2 Pmkeq, fin.no_confusion Pmkeq (λ Pe Pqe, Pe) lemma val_mk (n i : nat) (Plt : i < n) : fin.val (fin.mk i Plt) = i := rfl definition upto [reducible] (n : nat) : list (fin n) := dmap (λ i, i < n) fin.mk (list.upto n) lemma nodup_upto (n : nat) : nodup (upto n) := dmap_nodup_of_dinj (dinj_lt n) (list.nodup_upto n) lemma mem_upto (n : nat) : Π (i : fin n), i ∈ upto n := take i, fin.destruct i (take ival Piltn, have ival ∈ list.upto n, from mem_upto_of_lt Piltn, mem_dmap Piltn this) lemma upto_zero : upto 0 = [] := by rewrite [↑upto, list.upto_nil, dmap_nil] lemma map_val_upto (n : nat) : map fin.val (upto n) = list.upto n := map_dmap_of_inv_of_pos (val_mk n) (@lt_of_mem_upto n) lemma length_upto (n : nat) : length (upto n) = n := calc length (upto n) = length (list.upto n) : (map_val_upto n ▸ length_map fin.val (upto n))⁻¹ ... = n : list.length_upto n definition is_fintype [instance] (n : nat) : fintype (fin n) := fintype.mk (upto n) (nodup_upto n) (mem_upto n) section pigeonhole open fintype lemma card_fin (n : nat) : card (fin n) = n := length_upto n theorem pigeonhole {n m : nat} (Pmltn : m < n) : ¬Σ f : fin n → fin m, injective f := assume Pex, absurd Pmltn (not_lt_of_ge (calc n = card (fin n) : card_fin ... ≤ card (fin m) : card_le_of_inj (fin n) (fin m) Pex ... = m : card_fin)) end pigeonhole-/ protected definition zero [constructor] (n : nat) : fin (succ n) := mk 0 !zero_lt_succ definition fin_has_zero [instance] (n : nat) : has_zero (fin (succ n)) := has_zero.mk (fin.zero n) definition val_zero (n : nat) : val (0 : fin (succ n)) = 0 := rfl definition mk_mod [reducible] (n i : nat) : fin (succ n) := mk (i % (succ n)) (mod_lt _ !zero_lt_succ) theorem mk_mod_zero_eq (n : nat) : mk_mod n 0 = 0 := apd011 fin.mk rfl !is_prop.elimo variable {n : nat} theorem val_lt : Π i : fin n, val i < n | (mk v h) := h lemma max_lt (i j : fin n) : max i j < n := max_lt (is_lt i) (is_lt j) definition lift [constructor] : fin n → Π m : nat, fin (n + m) | (mk v h) m := mk v (lt_add_of_lt_right h m) definition lift_succ [constructor] (i : fin n) : fin (nat.succ n) := have r : fin (n+1), from lift i 1, r definition maxi [reducible] : fin (succ n) := mk n !lt_succ_self definition val_lift : Π (i : fin n) (m : nat), val i = val (lift i m) | (mk v h) m := rfl lemma mk_succ_ne_zero {i : nat} : Π {P}, mk (succ i) P ≠ (0 : fin (succ n)) := assume P Pe, absurd (veq_of_eq Pe) !succ_ne_zero lemma mk_mod_eq {i : fin (succ n)} : i = mk_mod n i := eq_of_veq begin rewrite [↑mk_mod, mod_eq_of_lt !is_lt] end lemma mk_mod_of_lt {i : nat} (Plt : i < succ n) : mk_mod n i = mk i Plt := begin esimp [mk_mod], congruence, exact mod_eq_of_lt Plt end section lift_lower lemma lift_zero : lift_succ (0 : fin (succ n)) = (0 : fin (succ (succ n))) := by apply eq_of_veq; reflexivity lemma ne_max_of_lt_max {i : fin (succ n)} : i < n → i ≠ maxi := begin intro hlt he, have he' : maxi = i, by apply he⁻¹, induction he', apply nat.lt_irrefl n hlt, end lemma lt_max_of_ne_max {i : fin (succ n)} : i ≠ maxi → i < n := assume hne : i ≠ maxi, have vne : val i ≠ n, from assume he, have val (@maxi n) = n, from rfl, have val i = val (@maxi n), from he ⬝ this⁻¹, absurd (eq_of_veq this) hne, have val i < nat.succ n, from val_lt i, lt_of_le_of_ne (le_of_lt_succ this) vne lemma lift_succ_ne_max {i : fin n} : lift_succ i ≠ maxi := begin cases i with v hlt, esimp [lift_succ, lift, max], intro he, injection he, substvars, exact absurd hlt (lt.irrefl v) end lemma lift_succ_inj [instance] : is_embedding (@lift_succ n) := begin apply is_embedding_of_is_injective, intro i j, induction i with iv ilt, induction j with jv jlt, intro Pmkeq, apply eq_of_veq, apply veq_of_eq Pmkeq end definition lt_of_inj_of_max (f : fin (succ n) → fin (succ n)) : is_embedding f → (f maxi = maxi) → Π i : fin (succ n), i < n → f i < n := assume Pinj Peq, take i, assume Pilt, have P1 : f i = f maxi → i = maxi, from assume Peq, is_injective_of_is_embedding Peq, have f i ≠ maxi, from begin rewrite -Peq, intro P2, apply absurd (P1 P2) (ne_max_of_lt_max Pilt) end, lt_max_of_ne_max this definition lift_fun : (fin n → fin n) → (fin (succ n) → fin (succ n)) := λ f i, dite (i = maxi) (λ Pe, maxi) (λ Pne, lift_succ (f (mk i (lt_max_of_ne_max Pne)))) definition lower_inj (f : fin (succ n) → fin (succ n)) (inj : is_embedding f) : f maxi = maxi → fin n → fin n := assume Peq, take i, mk (f (lift_succ i)) (lt_of_inj_of_max f inj Peq (lift_succ i) (lt_max_of_ne_max lift_succ_ne_max)) lemma lift_fun_max {f : fin n → fin n} : lift_fun f maxi = maxi := begin rewrite [↑lift_fun, dif_pos rfl] end lemma lift_fun_of_ne_max {f : fin n → fin n} {i} (Pne : i ≠ maxi) : lift_fun f i = lift_succ (f (mk i (lt_max_of_ne_max Pne))) := begin rewrite [↑lift_fun, dif_neg Pne] end lemma lift_fun_eq {f : fin n → fin n} {i : fin n} : lift_fun f (lift_succ i) = lift_succ (f i) := begin rewrite [lift_fun_of_ne_max lift_succ_ne_max], do 2 congruence, apply eq_of_veq, esimp, rewrite -val_lift, end lemma lift_fun_of_inj {f : fin n → fin n} : is_embedding f → is_embedding (lift_fun f) := begin intro Pemb, apply is_embedding_of_is_injective, intro i j, have Pdi : decidable (i = maxi), by apply _, have Pdj : decidable (j = maxi), by apply _, cases Pdi with Pimax Pinmax, cases Pdj with Pjmax Pjnmax, substvars, intros, reflexivity, substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pjnmax], intro Plmax, apply absurd Plmax⁻¹ lift_succ_ne_max, cases Pdj with Pjmax Pjnmax, substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pinmax], intro Plmax, apply absurd Plmax lift_succ_ne_max, rewrite [lift_fun_of_ne_max Pinmax, lift_fun_of_ne_max Pjnmax], intro Peq, apply eq_of_veq, cases i with i ilt, cases j with j jlt, esimp at *, fapply veq_of_eq, apply is_injective_of_is_embedding, apply @is_injective_of_is_embedding _ _ lift_succ _ _ _ Peq, end lemma lift_fun_inj : is_embedding (@lift_fun n) := begin apply is_embedding_of_is_injective, intro f f' Peq, apply eq_of_homotopy, intro i, have H : lift_fun f (lift_succ i) = lift_fun f' (lift_succ i), by apply congr_fun Peq _, revert H, rewrite [*lift_fun_eq], apply is_injective_of_is_embedding, end lemma lower_inj_apply {f Pinj Pmax} (i : fin n) : val (lower_inj f Pinj Pmax i) = val (f (lift_succ i)) := by rewrite [↑lower_inj] end lift_lower section madd definition madd (i j : fin (succ n)) : fin (succ n) := mk ((i + j) % (succ n)) (mod_lt _ !zero_lt_succ) definition minv : Π i : fin (succ n), fin (succ n) | (mk iv ilt) := mk ((succ n - iv) % succ n) (mod_lt _ !zero_lt_succ) lemma val_madd : Π i j : fin (succ n), val (madd i j) = (i + j) % (succ n) | (mk iv ilt) (mk jv jlt) := by esimp lemma madd_inj : Π {i : fin (succ n)}, is_embedding (madd i) | (mk iv ilt) := is_embedding_of_is_injective (take j₁ j₂, fin.destruct j₁ (fin.destruct j₂ (λ jv₁ jlt₁ jv₂ jlt₂, begin rewrite [↑madd], intro Peq', note Peq := ap val Peq', congruence, rewrite [-(mod_eq_of_lt jlt₁), -(mod_eq_of_lt jlt₂)], apply mod_eq_mod_of_add_mod_eq_add_mod_left Peq end))) lemma madd_mk_mod {i j : nat} : madd (mk_mod n i) (mk_mod n j) = mk_mod n (i+j) := eq_of_veq begin esimp [madd, mk_mod], rewrite [ mod_add_mod, add_mod_mod ] end lemma val_mod : Π i : fin (succ n), (val i) % (succ n) = val i | (mk iv ilt) := by esimp; rewrite [(mod_eq_of_lt ilt)] lemma madd_comm (i j : fin (succ n)) : madd i j = madd j i := by apply eq_of_veq; rewrite [*val_madd, add.comm (val i)] lemma zero_madd (i : fin (succ n)) : madd 0 i = i := have H : madd (fin.zero n) i = i, by apply eq_of_veq; rewrite [val_madd, ↑fin.zero, nat.zero_add, mod_eq_of_lt (is_lt i)], H lemma madd_zero (i : fin (succ n)) : madd i (fin.zero n) = i := !madd_comm ▸ zero_madd i lemma madd_assoc (i j k : fin (succ n)) : madd (madd i j) k = madd i (madd j k) := by apply eq_of_veq; rewrite [*val_madd, mod_add_mod, add_mod_mod, add.assoc (val i)] lemma madd_left_inv : Π i : fin (succ n), madd (minv i) i = fin.zero n | (mk iv ilt) := eq_of_veq (by rewrite [val_madd, ↑minv, mod_add_mod, nat.sub_add_cancel (le_of_lt ilt), mod_self]) definition madd_is_ab_group [instance] : add_ab_group (fin (succ n)) := ab_group.mk madd _ madd_assoc (fin.zero n) zero_madd madd_zero minv madd_left_inv madd_comm definition gfin (n : ℕ) [H : is_succ n] : AddAbGroup.{0} := by induction H with n; exact AddAbGroup.mk (fin (succ n)) _ end madd definition pred [constructor] : fin n → fin n | (mk v h) := mk (nat.pred v) (pre_lt_of_lt h) lemma val_pred : Π (i : fin n), val (pred i) = nat.pred (val i) | (mk v h) := rfl lemma pred_zero : pred (fin.zero n) = fin.zero n := begin induction n, reflexivity, apply eq_of_veq, reflexivity, end definition mk_pred (i : nat) (h : succ i < succ n) : fin n := mk i (lt_of_succ_lt_succ h) definition succ : fin n → fin (succ n) | (mk v h) := mk (nat.succ v) (succ_lt_succ h) lemma val_succ : Π (i : fin n), val (succ i) = nat.succ (val i) | (mk v h) := rfl lemma succ_max : fin.succ maxi = (@maxi (nat.succ n)) := rfl lemma lift_succ.comm : lift_succ ∘ (@succ n) = succ ∘ lift_succ := eq_of_homotopy take i, eq_of_veq (begin rewrite [↑lift_succ, -val_lift, *val_succ, -val_lift] end) definition elim0 {C : fin 0 → Type} : Π i : fin 0, C i | (mk v h) := absurd h !not_lt_zero definition zero_succ_cases {C : fin (nat.succ n) → Type} : C (fin.zero n) → (Π j : fin n, C (succ j)) → (Π k : fin (nat.succ n), C k) := begin intros CO CS k, induction k with [vk, pk], induction (nat.decidable_lt 0 vk) with [HT, HF], { show C (mk vk pk), from let vj := nat.pred vk in have vk = nat.succ vj, from inverse (succ_pred_of_pos HT), have vj < n, from lt_of_succ_lt_succ (eq.subst `vk = nat.succ vj` pk), have succ (mk vj `vj < n`) = mk vk pk, by apply val_inj; apply (succ_pred_of_pos HT), eq.rec_on this (CS (mk vj `vj < n`)) }, { show C (mk vk pk), from have vk = 0, from eq_zero_of_le_zero (le_of_not_gt HF), have fin.zero n = mk vk pk, from val_inj (inverse this), eq.rec_on this CO } end definition succ_maxi_cases {C : fin (nat.succ n) → Type} : (Π j : fin n, C (lift_succ j)) → C maxi → (Π k : fin (nat.succ n), C k) := begin intros CL CM k, induction k with [vk, pk], induction (nat.decidable_lt vk n) with [HT, HF], { show C (mk vk pk), from have HL : lift_succ (mk vk HT) = mk vk pk, from val_inj rfl, eq.rec_on HL (CL (mk vk HT)) }, { show C (mk vk pk), from have HMv : vk = n, from le.antisymm (le_of_lt_succ pk) (le_of_not_gt HF), have HM : maxi = mk vk pk, from val_inj (inverse HMv), eq.rec_on HM CM } end open decidable -- TODO there has to be a less painful way to do this definition elim_succ_maxi_cases_lift_succ {C : fin (nat.succ n) → Type} {Cls : Π j : fin n, C (lift_succ j)} {Cm : C maxi} (i : fin n) : succ_maxi_cases Cls Cm (lift_succ i) = Cls i := begin esimp[succ_maxi_cases], cases i with i ilt, esimp, apply decidable.rec, { intro ilt', esimp[val_inj], apply concat, apply ap (λ x, eq.rec_on x _), esimp[eq_of_veq, rfl], reflexivity, have H : ilt = ilt', by apply is_prop.elim, cases H, have H' : is_prop.elim (lt_add_of_lt_right ilt 1) (lt_add_of_lt_right ilt 1) = idp, by apply is_prop.elim, krewrite H' }, { intro a, exact absurd ilt a }, end definition elim_succ_maxi_cases_maxi {C : fin (nat.succ n) → Type} {Cls : Π j : fin n, C (lift_succ j)} {Cm : C maxi} : succ_maxi_cases Cls Cm maxi = Cm := begin esimp[succ_maxi_cases, maxi], apply decidable.rec, { intro a, apply absurd a !nat.lt_irrefl }, { intro a, esimp[val_inj], apply concat, have H : (le.antisymm (le_of_lt_succ (lt_succ_self n)) (le_of_not_gt a))⁻¹ = idp, by apply is_prop.elim, apply ap _ H, krewrite eq_of_veq_refl }, end definition foldr {A B : Type} (m : A → B → B) (b : B) : Π {n : nat}, (fin n → A) → B := nat.rec (λ f, b) (λ n IH f, m (f (fin.zero n)) (IH (λ i : fin n, f (succ i)))) definition foldl {A B : Type} (m : B → A → B) (b : B) : Π {n : nat}, (fin n → A) → B := nat.rec (λ f, b) (λ n IH f, m (IH (λ i : fin n, f (lift_succ i))) (f maxi)) theorem choice {C : fin n → Type} : (Π i : fin n, nonempty (C i)) → nonempty (Π i : fin n, C i) := begin revert C, induction n with [n, IH], { intros C H, apply nonempty.intro, exact elim0 }, { intros C H, fapply nonempty.elim (H (fin.zero n)), intro CO, fapply nonempty.elim (IH (λ i, C (succ i)) (λ i, H (succ i))), intro CS, apply nonempty.intro, exact zero_succ_cases CO CS } end /-section open list local postfix `+1`:100 := nat.succ lemma dmap_map_lift {n : nat} : Π l : list nat, (Π i, i ∈ l → i < n) → dmap (λ i, i < n +1) mk l = map lift_succ (dmap (λ i, i < n) mk l) | [] := assume Plt, rfl | (i::l) := assume Plt, begin rewrite [@dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (lt_succ_of_lt (Plt i !mem_cons)), @dmap_cons_of_pos _ _ (λ i, i < n) _ _ _ (Plt i !mem_cons), map_cons], congruence, apply dmap_map_lift, intro j Pjinl, apply Plt, apply mem_cons_of_mem, assumption end lemma upto_succ (n : nat) : upto (n +1) = maxi :: map lift_succ (upto n) := begin rewrite [↑fin.upto, list.upto_succ, @dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (nat.self_lt_succ n)], congruence, apply dmap_map_lift, apply @list.lt_of_mem_upto end definition upto_step : Π {n : nat}, fin.upto (n +1) = (map succ (upto n))++[0] | 0 := rfl | (i +1) := begin rewrite [upto_succ i, map_cons, append_cons, succ_max, upto_succ, -lift_zero], congruence, rewrite [map_map, -lift_succ.comm, -map_map, -(map_singleton _ 0), -map_append, -upto_step] end end-/ open sum equiv decidable definition fin_zero_equiv_empty : fin 0 ≃ empty := begin fapply equiv.MK, rotate 1, do 2 (intro x; contradiction), rotate 1, do 2 (intro x; apply elim0 x) end definition is_contr_fin_one [instance] : is_contr (fin 1) := begin fapply is_contr.mk, exact 0, intro x, induction x with v vlt, apply eq_of_veq, rewrite val_zero, apply inverse, apply eq_zero_of_le_zero, apply le_of_succ_le_succ, exact vlt, end definition fin_sum_equiv (n m : nat) : (fin n + fin m) ≃ fin (n+m) := begin fapply equiv.MK, { intro s, induction s with l r, induction l with v vlt, apply mk v, apply lt_add_of_lt_right, exact vlt, induction r with v vlt, apply mk (v + n), rewrite {n + m}add.comm, apply add_lt_add_of_lt_of_le vlt, apply nat.le_refl }, { intro f, induction f with v vlt, exact if h : v < n then sum.inl (mk v h) else sum.inr (mk (v-n) (nat.sub_lt_of_lt_add vlt (le_of_not_gt h))) }, { intro f, cases f with v vlt, esimp, apply @by_cases (v < n), intro vltn, rewrite [dif_pos vltn], apply eq_of_veq, reflexivity, intro nvltn, rewrite [dif_neg nvltn], apply eq_of_veq, esimp, apply nat.sub_add_cancel, apply le_of_not_gt, apply nvltn }, { intro s, cases s with f g, cases f with v vlt, rewrite [dif_pos vlt], cases g with v vlt, esimp, have ¬ v + n < n, from suppose v + n < n, have v < n - n, from nat.lt_sub_of_add_lt this !le.refl, have v < 0, by rewrite [nat.sub_self at this]; exact this, absurd this !not_lt_zero, apply concat, apply dif_neg this, apply ap inr, apply eq_of_veq, esimp, apply nat.add_sub_cancel }, end definition fin_succ_equiv (n : nat) : fin (n + 1) ≃ fin n + unit := begin fapply equiv.MK, { apply succ_maxi_cases, esimp, apply inl, apply inr unit.star }, { intro d, cases d, apply lift_succ a, apply maxi }, { intro d, cases d, cases a with a alt, esimp, apply elim_succ_maxi_cases_lift_succ, cases a, apply elim_succ_maxi_cases_maxi }, { intro a, apply succ_maxi_cases, esimp, intro j, krewrite elim_succ_maxi_cases_lift_succ, krewrite elim_succ_maxi_cases_maxi }, end open prod definition fin_prod_equiv (n m : nat) : (fin n × fin m) ≃ fin (n*m) := begin induction n, { krewrite nat.zero_mul, calc fin 0 × fin m ≃ empty × fin m : fin_zero_equiv_empty ... ≃ fin m × empty : prod_comm_equiv ... ≃ empty : prod_empty_equiv ... ≃ fin 0 : fin_zero_equiv_empty }, { have H : (a + 1) * m = a * m + m, by rewrite [nat.right_distrib, one_mul], calc fin (a + 1) × fin m ≃ (fin a + unit) × fin m : prod.prod_equiv_prod_right !fin_succ_equiv ... ≃ (fin a × fin m) + (unit × fin m) : sum_prod_right_distrib ... ≃ (fin a × fin m) + (fin m × unit) : prod_comm_equiv ... ≃ fin (a * m) + (fin m × unit) : v_0 ... ≃ fin (a * m) + fin m : prod_unit_equiv ... ≃ fin (a * m + m) : fin_sum_equiv ... ≃ fin ((a + 1) * m) : equiv_of_eq (ap fin H⁻¹) }, end definition fin_two_equiv_bool : fin 2 ≃ bool := let H := equiv_unit_of_is_contr (fin 1) in calc fin 2 ≃ fin (1 + 1) : equiv.refl ... ≃ fin 1 + fin 1 : fin_sum_equiv ... ≃ unit + unit : H ... ≃ bool : bool_equiv_unit_sum_unit definition fin_sum_unit_equiv (n : nat) : fin n + unit ≃ fin (nat.succ n) := let H := equiv_unit_of_is_contr (fin 1) in calc fin n + unit ≃ fin n + fin 1 : H ... ≃ fin (nat.succ n) : fin_sum_equiv definition fin_sum_equiv_cancel {n : nat} {A B : Type} (H : (fin n) + A ≃ (fin n) + B) : A ≃ B := begin induction n with n IH, { calc A ≃ A + empty : sum_empty_equiv ... ≃ empty + A : sum_comm_equiv ... ≃ fin 0 + A : fin_zero_equiv_empty ... ≃ fin 0 + B : H ... ≃ empty + B : fin_zero_equiv_empty ... ≃ B + empty : sum_comm_equiv ... ≃ B : sum_empty_equiv }, { apply IH, apply unit_sum_equiv_cancel, calc unit + (fin n + A) ≃ (unit + fin n) + A : sum_assoc_equiv ... ≃ (fin n + unit) + A : sum_comm_equiv ... ≃ fin (nat.succ n) + A : fin_sum_unit_equiv ... ≃ fin (nat.succ n) + B : H ... ≃ (fin n + unit) + B : fin_sum_unit_equiv ... ≃ (unit + fin n) + B : sum_comm_equiv ... ≃ unit + (fin n + B) : sum_assoc_equiv }, end definition eq_of_fin_equiv {m n : nat} (H :fin m ≃ fin n) : m = n := begin revert n H, induction m with m IH IH, { intro n H, cases n, reflexivity, exfalso, apply to_fun fin_zero_equiv_empty, apply to_inv H, apply fin.zero }, { intro n H, cases n with n, exfalso, apply to_fun fin_zero_equiv_empty, apply to_fun H, apply fin.zero, have unit + fin m ≃ unit + fin n, from calc unit + fin m ≃ fin m + unit : sum_comm_equiv ... ≃ fin (nat.succ m) : fin_succ_equiv ... ≃ fin (nat.succ n) : H ... ≃ fin n + unit : fin_succ_equiv ... ≃ unit + fin n : sum_comm_equiv, have fin m ≃ fin n, from unit_sum_equiv_cancel this, apply ap nat.succ, apply IH _ this }, end definition cyclic_succ {n : ℕ} (x : fin n) : fin n := begin cases n with n, { exfalso, apply not_lt_zero _ (is_lt x)}, { exact if H : val x = n then fin.mk 0 !zero_lt_succ else fin.mk (nat.succ (val x)) (succ_lt_succ (lt_of_le_of_ne (le_of_lt_succ (is_lt x)) H))} end /- We want to say that fin (succ n) always has a 0 and 1. However, we want a bit more, because sometimes we want a zero of (fin a) where a is either - equal to a successor, but not definitionally a successor (e.g. (0 : fin (3 + n))) - definitionally equal to a successor, but not in a way that type class inference can infer. (e.g. (0 : fin 4). Note that 4 is bit0 (bit0 one), but (bit0 x) (defined as x + x), is not always a successor) To solve this we use an auxillary class `is_succ` which can solve whether a number is a successor. -/ /- this is a version of `madd` which might compute better -/ protected definition add {n : ℕ} (x y : fin n) : fin n := iterate cyclic_succ (val y) x definition has_zero_fin [instance] (n : ℕ) [H : is_succ n] : has_zero (fin n) := by induction H with n; exact has_zero.mk (fin.zero n) definition has_one_fin [instance] (n : ℕ) [H : is_succ n] : has_one (fin n) := by induction H with n; exact has_one.mk (cyclic_succ (fin.zero n)) definition has_add_fin [instance] (n : ℕ) : has_add (fin n) := has_add.mk fin.add end fin
69baefa84851eb941c1237be625ac67156f43769
4727251e0cd73359b15b664c3170e5d754078599
/src/meta/rb_map.lean
27ae900a748d35be2e1910c830cae9d1a6f31e43
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,037
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.list.defs /-! # rb_map This file defines additional operations on native rb_maps and rb_sets. These structures are defined in core in `init.meta.rb_map`. They are meta objects, and are generally the most efficient dictionary structures to use for pure metaprogramming right now. -/ namespace native /-! ### Declarations about `rb_set` -/ namespace rb_set meta instance {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_set key) := ⟨mk_rb_set⟩ /-- `filter s P` returns the subset of elements of `s` satisfying `P`. -/ meta def filter {key} (s : rb_set key) (P : key → bool) : rb_set key := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter s P` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] {key} (s : rb_set key) (P : key → m bool) : m (rb_set key) := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `union s t` returns an rb_set containing every element that appears in either `s` or `t`. -/ meta def union {key} (s t : rb_set key) : rb_set key := s.fold t (λ a t, t.insert a) /-- `of_list_core empty l` turns a list of keys into an `rb_set`. It takes a user_provided `rb_set` to use for the base case. This can be used to pre-seed the set with additional elements, and/or to use a custom comparison operator. -/ meta def of_list_core {key} (base : rb_set key) : list key → rb_map key unit | [] := base | (x::xs) := rb_set.insert (of_list_core xs) x /-- `of_list l` transforms a list `l : list key` into an `rb_set`, inferring an order on the type `key`. -/ meta def of_list {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list key → rb_set key := of_list_core mk_rb_set /-- `sdiff s1 s2` returns the set of elements that are in `s1` but not in `s2`. It does so by folding over `s2`. If `s1` is significantly smaller than `s2`, it may be worth it to reverse the fold. -/ meta def sdiff {α} (s1 s2 : rb_set α) : rb_set α := s2.fold s1 $ λ v s, s.erase v /-- `insert_list s l` inserts each element of `l` into `s`. -/ meta def insert_list {key} (s : rb_set key) (l : list key) : rb_set key := l.foldl rb_set.insert s end rb_set /-! ### Declarations about `rb_map` -/ namespace rb_map meta instance {key data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_map key data) := ⟨mk_rb_map⟩ /-- `find_def default m k` returns the value corresponding to `k` in `m`, if it exists. Otherwise it returns `default`. -/ meta def find_def {key value} (default : value) (m : rb_map key value) (k : key) := (m.find k).get_or_else default /-- `ifind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns the default value of `value`. -/ meta def ifind {key value} [inhabited value] (m : rb_map key value) (k : key) : value := (m.find k).iget /-- `zfind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns 0. -/ meta def zfind {key value} [has_zero value] (m : rb_map key value) (k : key) : value := (m.find k).get_or_else 0 /-- Returns the pointwise sum of `m1` and `m2`, treating nonexistent values as 0. -/ meta def add {key value} [has_add value] [has_zero value] [decidable_eq value] (m1 m2 : rb_map key value) : rb_map key value := m1.fold m2 (λ n v m, let nv := v + m2.zfind n in if nv = 0 then m.erase n else m.insert n nv) variables {m : Type → Type*} [monad m] open function /-- `mfilter P s` filters `s` by the monadic predicate `P` on keys and values. -/ meta def mfilter {key val} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (P : key → val → m bool) (s : rb_map key val) : m (rb_map.{0 0} key val) := rb_map.of_list <$> s.to_list.mfilter (uncurry P) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {key val val'} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (f : val → m val') (s : rb_map key val) : m (rb_map.{0 0} key val') := rb_map.of_list <$> s.to_list.mmap (λ ⟨a,b⟩, prod.mk a <$> f b) /-- `scale b m` multiplies every value in `m` by `b`. -/ meta def scale {key value} [has_lt key] [decidable_rel ((<) : key → key → Prop)] [has_mul value] (b : value) (m : rb_map key value) : rb_map key value := m.map ((*) b) section open format prod variables {key : Type} {data : Type} [has_to_tactic_format key] [has_to_tactic_format data] private meta def pp_key_data (k : key) (d : data) (first : bool) : tactic format := do fk ← tactic.pp k, fd ← tactic.pp d, return $ (if first then to_fmt "" else to_fmt "," ++ line) ++ fk ++ space ++ to_fmt "←" ++ space ++ fd meta instance : has_to_tactic_format (rb_map key data) := ⟨λ m, do (fmt, _) ← fold m (return (to_fmt "", tt)) (λ k d p, do p ← p, pkd ← pp_key_data k d (snd p), return (fst p ++ pkd, ff)), return $ group $ to_fmt "⟨" ++ nest 1 fmt ++ to_fmt "⟩"⟩ end end rb_map /-! ### Declarations about `rb_lmap` -/ namespace rb_lmap meta instance (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : inhabited (rb_lmap key data) := ⟨rb_lmap.mk _ _⟩ /-- Construct a rb_lmap from a list of key-data pairs -/ protected meta def of_list {key : Type} {data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list (key × data) → rb_lmap key data | [] := rb_lmap.mk key data | ((k, v)::ls) := (of_list ls).insert k v /-- Returns the list of values of an `rb_lmap`. -/ protected meta def values {key data} (m : rb_lmap key data) : list data := m.fold [] (λ _, (++)) end rb_lmap end native /-! ### Declarations about `name_set` -/ namespace name_set meta instance : inhabited name_set := ⟨mk_name_set⟩ /-- `filter P s` returns the subset of elements of `s` satisfying `P`. -/ meta def filter (P : name → bool) (s : name_set) : name_set := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter P s` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] (P : name → m bool) (s : name_set) : m name_set := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {m} [monad m] (f : name → m name) (s : name_set) : m name_set := s.fold (pure mk_name_set) (λ a m, do x ← m, b ← f a, (pure $ x.insert b)) /-- `insert_list s l` inserts every element of `l` into `s`. -/ meta def insert_list (s : name_set) (l : list name) : name_set := l.foldr (λ n s', s'.insert n) s /-- `local_list_to_name_set lcs` is the set of unique names of the local constants `lcs`. If any of the `lcs` are not local constants, the returned set will contain bogus names. -/ meta def local_list_to_name_set (lcs : list expr) : name_set := lcs.foldl (λ ns h, ns.insert h.local_uniq_name) mk_name_set end name_set /-! ### Declarations about `name_map` -/ namespace name_map meta instance {data : Type} : inhabited (name_map data) := ⟨mk_name_map⟩ end name_map /-! ### Declarations about `expr_set` -/ namespace expr_set /-- `local_set_to_name_set lcs` is the set of unique names of the local constants `lcs`. If any of the `lcs` are not local constants, the returned set will contain bogus names. -/ meta def local_set_to_name_set (lcs : expr_set) : name_set := lcs.fold mk_name_set $ λ h ns, ns.insert h.local_uniq_name end expr_set namespace list /-- `to_rb_map as` is the map that associates each index `i` of `as` with the corresponding element of `as`. ``` to_rb_map ['a', 'b', 'c'] = rb_map.of_list [(0, 'a'), (1, 'b'), (2, 'c')] ``` -/ meta def to_rb_map {α : Type} : list α → native.rb_map ℕ α := foldl_with_index (λ i mapp a, mapp.insert i a) native.mk_rb_map end list
6963a217cee29b6fbfe0fce37bddd2c85a742d8a
3863d2564418bccb1859e057bf5a4ef240e75fd7
/hott/types/int/hott.hlean
c2a7cb8c4dc3a9caa5f6ee6a64a020fedc7bdbc1
[ "Apache-2.0" ]
permissive
JacobGross/lean
118bbb067ff4d4af48a266face2c7eb9868fa91c
eb26087df940c54337cb807b4bc6d345d1fc1085
refs/heads/master
1,582,735,011,532
1,462,557,826,000
1,462,557,826,000
46,451,196
0
0
null
1,462,557,826,000
1,447,885,161,000
C++
UTF-8
Lean
false
false
5,845
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about the integers specific to HoTT -/ import .basic types.eq arity algebra.bundled open core eq is_equiv equiv algebra is_trunc open nat (hiding pred) namespace int section open algebra definition group_integers : Group := Group.mk ℤ (group_of_add_group _) notation `gℤ` := group_integers end definition is_equiv_succ [instance] : is_equiv succ := adjointify succ pred (λa, !add_sub_cancel) (λa, !sub_add_cancel) definition equiv_succ : ℤ ≃ ℤ := equiv.mk succ _ definition is_equiv_neg [instance] : is_equiv (neg : ℤ → ℤ) := adjointify neg neg (λx, !neg_neg) (λa, !neg_neg) definition equiv_neg : ℤ ≃ ℤ := equiv.mk neg _ definition iterate {A : Type} (f : A ≃ A) (a : ℤ) : A ≃ A := rec_nat_on a erfl (λb g, f ⬝e g) (λb g, g ⬝e f⁻¹ᵉ) -- definition iterate_trans {A : Type} (f : A ≃ A) (a : ℤ) -- : iterate f a ⬝e f = iterate f (a + 1) := -- sorry -- definition trans_iterate {A : Type} (f : A ≃ A) (a : ℤ) -- : f ⬝e iterate f a = iterate f (a + 1) := -- sorry -- definition iterate_trans_symm {A : Type} (f : A ≃ A) (a : ℤ) -- : iterate f a ⬝e f⁻¹e = iterate f (a - 1) := -- sorry -- definition symm_trans_iterate {A : Type} (f : A ≃ A) (a : ℤ) -- : f⁻¹e ⬝e iterate f a = iterate f (a - 1) := -- sorry -- definition iterate_neg {A : Type} (f : A ≃ A) (a : ℤ) -- : iterate f (-a) = (iterate f a)⁻¹e := -- rec_nat_on a idp -- (λn p, calc -- iterate f (-succ n) = iterate f (-n) ⬝e f⁻¹e : rec_nat_on_neg -- ... = (iterate f n)⁻¹e ⬝e f⁻¹e : by rewrite p -- ... = (f ⬝e iterate f n)⁻¹e : sorry -- ... = (iterate f (succ n))⁻¹e : idp) -- sorry -- definition iterate_add {A : Type} (f : A ≃ A) (a b : ℤ) -- : iterate f (a + b) = equiv.trans (iterate f a) (iterate f b) := -- sorry -- definition iterate_sub {A : Type} (f : A ≃ A) (a b : ℤ) -- : iterate f (a - b) = equiv.trans (iterate f a) (equiv.symm (iterate f b)) := -- sorry -- definition iterate_mul {A : Type} (f : A ≃ A) (a b : ℤ) -- : iterate f (a * b) = iterate (iterate f a) b := -- sorry end int open int namespace eq variables {A : Type} {a : A} (p : a = a) (b c : ℤ) (n : ℕ) definition power : a = a := rec_nat_on b idp (λc q, q ⬝ p) (λc q, q ⬝ p⁻¹) --iterate (equiv_eq_closed_right p a) b idp -- definition power_neg_succ (n : ℕ) : power p (-succ n) = power p (-n) ⬝ p⁻¹ := -- !rec_nat_on_neg -- local attribute nat.add int.add int.of_num nat.of_num int.succ [constructor] definition power_con : power p b ⬝ p = power p (succ b) := rec_nat_on b idp (λn IH, idp) (λn IH, calc power p (-succ n) ⬝ p = (power p (-int.of_nat n) ⬝ p⁻¹) ⬝ p : by krewrite [↑power,rec_nat_on_neg] ... = power p (-int.of_nat n) : inv_con_cancel_right ... = power p (succ (-succ n)) : by rewrite -succ_neg_succ) definition power_con_inv : power p b ⬝ p⁻¹ = power p (pred b) := rec_nat_on b idp (λn IH, calc power p (succ n) ⬝ p⁻¹ = power p n : by apply con_inv_cancel_right ... = power p (pred (succ n)) : by rewrite pred_nat_succ) (λn IH, calc power p (-int.of_nat (succ n)) ⬝ p⁻¹ = power p (-int.of_nat (succ (succ n))) : by krewrite [↑power,*rec_nat_on_neg] ... = power p (pred (-succ n)) : by rewrite -neg_succ) definition con_power : p ⬝ power p b = power p (succ b) := rec_nat_on b ( by rewrite ↑[power];exact !idp_con⁻¹) ( λn IH, proof calc p ⬝ power p (succ n) = (p ⬝ power p n) ⬝ p : con.assoc p _ p ... = power p (succ (succ n)) : by rewrite IH qed) ( λn IH, calc p ⬝ power p (-int.of_nat (succ n)) = p ⬝ (power p (-int.of_nat n) ⬝ p⁻¹) : by rewrite [↑power, rec_nat_on_neg] ... = (p ⬝ power p (-int.of_nat n)) ⬝ p⁻¹ : con.assoc ... = power p (succ (-int.of_nat n)) ⬝ p⁻¹ : by rewrite IH ... = power p (pred (succ (-int.of_nat n))) : power_con_inv ... = power p (succ (-int.of_nat (succ n))) : by rewrite [succ_neg_nat_succ,int.pred_succ]) definition inv_con_power : p⁻¹ ⬝ power p b = power p (pred b) := rec_nat_on b ( by rewrite ↑[power];exact !idp_con⁻¹) (λn IH, calc p⁻¹ ⬝ power p (succ n) = p⁻¹ ⬝ power p n ⬝ p : con.assoc ... = power p (pred n) ⬝ p : by rewrite IH ... = power p (succ (pred n)) : power_con ... = power p (pred (succ n)) : by rewrite [succ_pred,-int.pred_succ n]) ( λn IH, calc p⁻¹ ⬝ power p (-int.of_nat (succ n)) = p⁻¹ ⬝ (power p (-int.of_nat n) ⬝ p⁻¹) : by rewrite [↑power,rec_nat_on_neg] ... = (p⁻¹ ⬝ power p (-int.of_nat n)) ⬝ p⁻¹ : con.assoc ... = power p (pred (-int.of_nat n)) ⬝ p⁻¹ : by rewrite IH ... = power p (-int.of_nat (succ n)) ⬝ p⁻¹ : by rewrite -neg_succ ... = power p (-succ (succ n)) : by krewrite [↑power,*rec_nat_on_neg] ... = power p (pred (-succ n)) : by rewrite -neg_succ) definition power_con_power : Π(b : ℤ), power p b ⬝ power p c = power p (b + c) := rec_nat_on c (λb, by rewrite int.add_zero) (λn IH b, by rewrite [-con_power,-con.assoc,power_con,IH,↑succ,add.assoc, add.comm (int.of_nat n)]) (λn IH b, by rewrite [neg_nat_succ,-inv_con_power,-con.assoc,power_con_inv,IH,↑pred, +sub_eq_add_neg,add.assoc,add.comm (-n)]) end eq
0c8f20973a811c71f84ef6afc16a219037c4816e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/sylow.lean
cb6ae0218a3c8412acdbc18e02764e983b70284f
[ "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
35,179
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Thomas Browning -/ import data.nat.factorization.basic import data.set_like.fintype import group_theory.group_action.conj_act import group_theory.p_group import group_theory.noncomm_pi_coprod /-! # Sylow theorems The Sylow theorems are the following results for every finite group `G` and every prime number `p`. * There exists a Sylow `p`-subgroup of `G`. * All Sylow `p`-subgroups of `G` are conjugate to each other. * Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow `p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow `p`-subgroup in `G`. ## Main definitions * `sylow p G` : The type of Sylow `p`-subgroups of `G`. ## Main statements * `exists_subgroup_card_pow_prime`: A generalization of Sylow's first theorem: For every prime power `pⁿ` dividing the cardinality of `G`, there exists a subgroup of `G` of order `pⁿ`. * `is_p_group.exists_le_sylow`: A generalization of Sylow's first theorem: Every `p`-subgroup is contained in a Sylow `p`-subgroup. * `sylow.card_eq_multiplicity`: The cardinality of a Sylow group is `p ^ n` where `n` is the multiplicity of `p` in the group order. * `sylow_conjugate`: A generalization of Sylow's second theorem: If the number of Sylow `p`-subgroups is finite, then all Sylow `p`-subgroups are conjugate. * `card_sylow_modeq_one`: A generalization of Sylow's third theorem: If the number of Sylow `p`-subgroups is finite, then it is congruent to `1` modulo `p`. -/ open fintype mul_action subgroup section infinite_sylow variables (p : ℕ) (G : Type*) [group G] /-- A Sylow `p`-subgroup is a maximal `p`-subgroup. -/ structure sylow extends subgroup G := (is_p_group' : is_p_group p to_subgroup) (is_maximal' : ∀ {Q : subgroup G}, is_p_group p Q → to_subgroup ≤ Q → Q = to_subgroup) variables {p} {G} namespace sylow instance : has_coe (sylow p G) (subgroup G) := ⟨sylow.to_subgroup⟩ @[simp] lemma to_subgroup_eq_coe {P : sylow p G} : P.to_subgroup = ↑P := rfl @[ext] lemma ext {P Q : sylow p G} (h : (P : subgroup G) = Q) : P = Q := by cases P; cases Q; congr' lemma ext_iff {P Q : sylow p G} : P = Q ↔ (P : subgroup G) = Q := ⟨congr_arg coe, ext⟩ instance : set_like (sylow p G) G := { coe := coe, coe_injective' := λ P Q h, ext (set_like.coe_injective h) } instance : subgroup_class (sylow p G) G := { mul_mem := λ s _ _, s.mul_mem', one_mem := λ s, s.one_mem', inv_mem := λ s _, s.inv_mem' } variables (P : sylow p G) /-- The action by a Sylow subgroup is the action by the underlying group. -/ instance mul_action_left {α : Type*} [mul_action G α] : mul_action P α := subgroup.mul_action ↑P variables {K : Type*} [group K] (ϕ : K →* G) {N : subgroup G} /-- The preimage of a Sylow subgroup under a p-group-kernel homomorphism is a Sylow subgroup. -/ def comap_of_ker_is_p_group (hϕ : is_p_group p ϕ.ker) (h : ↑P ≤ ϕ.range) : sylow p K := { P.1.comap ϕ with is_p_group' := P.2.comap_of_ker_is_p_group ϕ hϕ, is_maximal' := λ Q hQ hle, by { rw ← P.3 (hQ.map ϕ) (le_trans (ge_of_eq (map_comap_eq_self h)) (map_mono hle)), exact (comap_map_eq_self ((P.1.ker_le_comap ϕ).trans hle)).symm }, } @[simp] lemma coe_comap_of_ker_is_p_group (hϕ : is_p_group p ϕ.ker) (h : ↑P ≤ ϕ.range) : ↑(P.comap_of_ker_is_p_group ϕ hϕ h) = subgroup.comap ϕ ↑P := rfl /-- The preimage of a Sylow subgroup under an injective homomorphism is a Sylow subgroup. -/ def comap_of_injective (hϕ : function.injective ϕ) (h : ↑P ≤ ϕ.range) : sylow p K := P.comap_of_ker_is_p_group ϕ (is_p_group.ker_is_p_group_of_injective hϕ) h @[simp] lemma coe_comap_of_injective (hϕ : function.injective ϕ) (h : ↑P ≤ ϕ.range) : ↑(P.comap_of_injective ϕ hϕ h) = subgroup.comap ϕ ↑P := rfl /-- A sylow subgroup of G is also a sylow subgroup of a subgroup of G. -/ protected def subtype (h : ↑P ≤ N) : sylow p N := P.comap_of_injective N.subtype subtype.coe_injective (by rwa [subtype_range]) @[simp] lemma coe_subtype (h : ↑P ≤ N) : ↑(P.subtype h) = subgroup_of ↑P N := rfl lemma subtype_injective {P Q : sylow p G} {hP : ↑P ≤ N} {hQ : ↑Q ≤ N} (h : P.subtype hP = Q.subtype hQ) : P = Q := begin rw set_like.ext_iff at h ⊢, exact λ g, ⟨λ hg, (h ⟨g, hP hg⟩).mp hg, λ hg, (h ⟨g, hQ hg⟩).mpr hg⟩, end end sylow /-- A generalization of **Sylow's first theorem**. Every `p`-subgroup is contained in a Sylow `p`-subgroup. -/ lemma is_p_group.exists_le_sylow {P : subgroup G} (hP : is_p_group p P) : ∃ Q : sylow p G, P ≤ Q := exists.elim (zorn_nonempty_partial_order₀ {Q : subgroup G | is_p_group p Q} (λ c hc1 hc2 Q hQ, ⟨ { carrier := ⋃ (R : c), R, one_mem' := ⟨Q, ⟨⟨Q, hQ⟩, rfl⟩, Q.one_mem⟩, inv_mem' := λ g ⟨_, ⟨R, rfl⟩, hg⟩, ⟨R, ⟨R, rfl⟩, R.1.inv_mem hg⟩, mul_mem' := λ g h ⟨_, ⟨R, rfl⟩, hg⟩ ⟨_, ⟨S, rfl⟩, hh⟩, (hc2.total R.2 S.2).elim (λ T, ⟨S, ⟨S, rfl⟩, S.1.mul_mem (T hg) hh⟩) (λ T, ⟨R, ⟨R, rfl⟩, R.1.mul_mem hg (T hh)⟩) }, λ ⟨g, _, ⟨S, rfl⟩, hg⟩, by { refine exists_imp_exists (λ k hk, _) (hc1 S.2 ⟨g, hg⟩), rwa [subtype.ext_iff, coe_pow] at hk ⊢ }, λ M hM g hg, ⟨M, ⟨⟨M, hM⟩, rfl⟩, hg⟩⟩) P hP) (λ Q ⟨hQ1, hQ2, hQ3⟩, ⟨⟨Q, hQ1, hQ3⟩, hQ2⟩) instance sylow.nonempty : nonempty (sylow p G) := nonempty_of_exists is_p_group.of_bot.exists_le_sylow noncomputable instance sylow.inhabited : inhabited (sylow p G) := classical.inhabited_of_nonempty sylow.nonempty lemma sylow.exists_comap_eq_of_ker_is_p_group {H : Type*} [group H] (P : sylow p H) {f : H →* G} (hf : is_p_group p f.ker) : ∃ Q : sylow p G, (Q : subgroup G).comap f = P := exists_imp_exists (λ Q hQ, P.3 (Q.2.comap_of_ker_is_p_group f hf) (map_le_iff_le_comap.mp hQ)) (P.2.map f).exists_le_sylow lemma sylow.exists_comap_eq_of_injective {H : Type*} [group H] (P : sylow p H) {f : H →* G} (hf : function.injective f) : ∃ Q : sylow p G, (Q : subgroup G).comap f = P := P.exists_comap_eq_of_ker_is_p_group (is_p_group.ker_is_p_group_of_injective hf) lemma sylow.exists_comap_subtype_eq {H : subgroup G} (P : sylow p H) : ∃ Q : sylow p G, (Q : subgroup G).comap H.subtype = P := P.exists_comap_eq_of_injective subtype.coe_injective /-- If the kernel of `f : H →* G` is a `p`-group, then `fintype (sylow p G)` implies `fintype (sylow p H)`. -/ noncomputable def sylow.fintype_of_ker_is_p_group {H : Type*} [group H] {f : H →* G} (hf : is_p_group p f.ker) [fintype (sylow p G)] : fintype (sylow p H) := let h_exists := λ P : sylow p H, P.exists_comap_eq_of_ker_is_p_group hf, g : sylow p H → sylow p G := λ P, classical.some (h_exists P), hg : ∀ P : sylow p H, (g P).1.comap f = P := λ P, classical.some_spec (h_exists P) in fintype.of_injective g (λ P Q h, sylow.ext (by simp only [←hg, h])) /-- If `f : H →* G` is injective, then `fintype (sylow p G)` implies `fintype (sylow p H)`. -/ noncomputable def sylow.fintype_of_injective {H : Type*} [group H] {f : H →* G} (hf : function.injective f) [fintype (sylow p G)] : fintype (sylow p H) := sylow.fintype_of_ker_is_p_group (is_p_group.ker_is_p_group_of_injective hf) /-- If `H` is a subgroup of `G`, then `fintype (sylow p G)` implies `fintype (sylow p H)`. -/ noncomputable instance (H : subgroup G) [fintype (sylow p G)] : fintype (sylow p H) := sylow.fintype_of_injective H.subtype_injective /-- If `H` is a subgroup of `G`, then `finite (sylow p G)` implies `finite (sylow p H)`. -/ instance (H : subgroup G) [finite (sylow p G)] : finite (sylow p H) := by { casesI nonempty_fintype (sylow p G), apply_instance } open_locale pointwise /-- `subgroup.pointwise_mul_action` preserves Sylow subgroups. -/ instance sylow.pointwise_mul_action {α : Type*} [group α] [mul_distrib_mul_action α G] : mul_action α (sylow p G) := { smul := λ g P, ⟨g • P, P.2.map _, λ Q hQ hS, inv_smul_eq_iff.mp (P.3 (hQ.map _) (λ s hs, (congr_arg (∈ g⁻¹ • Q) (inv_smul_smul g s)).mp (smul_mem_pointwise_smul (g • s) g⁻¹ Q (hS (smul_mem_pointwise_smul s g P hs)))))⟩, one_smul := λ P, sylow.ext (one_smul α P), mul_smul := λ g h P, sylow.ext (mul_smul g h P) } lemma sylow.pointwise_smul_def {α : Type*} [group α] [mul_distrib_mul_action α G] {g : α} {P : sylow p G} : ↑(g • P) = g • (P : subgroup G) := rfl instance sylow.mul_action : mul_action G (sylow p G) := comp_hom _ mul_aut.conj lemma sylow.smul_def {g : G} {P : sylow p G} : g • P = mul_aut.conj g • P := rfl lemma sylow.coe_subgroup_smul {g : G} {P : sylow p G} : ↑(g • P) = mul_aut.conj g • (P : subgroup G) := rfl lemma sylow.coe_smul {g : G} {P : sylow p G} : ↑(g • P) = mul_aut.conj g • (P : set G) := rfl lemma sylow.smul_le {P : sylow p G} {H : subgroup G} (hP : ↑P ≤ H) (h : H) : ↑(h • P) ≤ H := subgroup.conj_smul_le_of_le hP h lemma sylow.smul_subtype {P : sylow p G} {H : subgroup G} (hP : ↑P ≤ H) (h : H) : h • P.subtype hP = (h • P).subtype (sylow.smul_le hP h) := sylow.ext (subgroup.conj_smul_subgroup_of hP h) lemma sylow.smul_eq_iff_mem_normalizer {g : G} {P : sylow p G} : g • P = P ↔ g ∈ (P : subgroup G).normalizer := begin rw [eq_comm, set_like.ext_iff, ←inv_mem_iff, mem_normalizer_iff, inv_inv], exact forall_congr (λ h, iff_congr iff.rfl ⟨λ ⟨a, b, c⟩, (congr_arg _ c).mp ((congr_arg (∈ P.1) (mul_aut.inv_apply_self G (mul_aut.conj g) a)).mpr b), λ hh, ⟨(mul_aut.conj g)⁻¹ h, hh, mul_aut.apply_inv_self G (mul_aut.conj g) h⟩⟩), end lemma sylow.smul_eq_of_normal {g : G} {P : sylow p G} [h : (P : subgroup G).normal] : g • P = P := by simp only [sylow.smul_eq_iff_mem_normalizer, normalizer_eq_top.mpr h, mem_top] lemma subgroup.sylow_mem_fixed_points_iff (H : subgroup G) {P : sylow p G} : P ∈ fixed_points H (sylow p G) ↔ H ≤ (P : subgroup G).normalizer := by simp_rw [set_like.le_def, ←sylow.smul_eq_iff_mem_normalizer]; exact subtype.forall lemma is_p_group.inf_normalizer_sylow {P : subgroup G} (hP : is_p_group p P) (Q : sylow p G) : P ⊓ (Q : subgroup G).normalizer = P ⊓ Q := le_antisymm (le_inf inf_le_left (sup_eq_right.mp (Q.3 (hP.to_inf_left.to_sup_of_normal_right' Q.2 inf_le_right) le_sup_right))) (inf_le_inf_left P le_normalizer) lemma is_p_group.sylow_mem_fixed_points_iff {P : subgroup G} (hP : is_p_group p P) {Q : sylow p G} : Q ∈ fixed_points P (sylow p G) ↔ P ≤ Q := by rw [P.sylow_mem_fixed_points_iff, ←inf_eq_left, hP.inf_normalizer_sylow, inf_eq_left] /-- A generalization of **Sylow's second theorem**. If the number of Sylow `p`-subgroups is finite, then all Sylow `p`-subgroups are conjugate. -/ instance [hp : fact p.prime] [finite (sylow p G)] : is_pretransitive G (sylow p G) := ⟨λ P Q, by { classical, casesI nonempty_fintype (sylow p G), have H := λ {R : sylow p G} {S : orbit G P}, calc S ∈ fixed_points R (orbit G P) ↔ S.1 ∈ fixed_points R (sylow p G) : forall_congr (λ a, subtype.ext_iff) ... ↔ R.1 ≤ S : R.2.sylow_mem_fixed_points_iff ... ↔ S.1.1 = R : ⟨λ h, R.3 S.1.2 h, ge_of_eq⟩, suffices : set.nonempty (fixed_points Q (orbit G P)), { exact exists.elim this (λ R hR, (congr_arg _ (sylow.ext (H.mp hR))).mp R.2) }, apply Q.2.nonempty_fixed_point_of_prime_not_dvd_card, refine λ h, hp.out.not_dvd_one (nat.modeq_zero_iff_dvd.mp _), calc 1 = card (fixed_points P (orbit G P)) : _ ... ≡ card (orbit G P) [MOD p] : (P.2.card_modeq_card_fixed_points (orbit G P)).symm ... ≡ 0 [MOD p] : nat.modeq_zero_iff_dvd.mpr h, rw ← set.card_singleton (⟨P, mem_orbit_self P⟩ : orbit G P), refine card_congr' (congr_arg _ (eq.symm _)), rw set.eq_singleton_iff_unique_mem, exact ⟨H.mpr rfl, λ R h, subtype.ext (sylow.ext (H.mp h))⟩ }⟩ variables (p) (G) /-- A generalization of **Sylow's third theorem**. If the number of Sylow `p`-subgroups is finite, then it is congruent to `1` modulo `p`. -/ lemma card_sylow_modeq_one [fact p.prime] [fintype (sylow p G)] : card (sylow p G) ≡ 1 [MOD p] := begin refine sylow.nonempty.elim (λ P : sylow p G, _), have : fixed_points P.1 (sylow p G) = {P} := set.ext (λ Q : sylow p G, calc Q ∈ fixed_points P (sylow p G) ↔ P.1 ≤ Q : P.2.sylow_mem_fixed_points_iff ... ↔ Q.1 = P.1 : ⟨P.3 Q.2, ge_of_eq⟩ ... ↔ Q ∈ {P} : sylow.ext_iff.symm.trans set.mem_singleton_iff.symm), haveI : fintype (fixed_points P.1 (sylow p G)), { rw this, apply_instance }, have : card (fixed_points P.1 (sylow p G)) = 1, { simp [this] }, exact (P.2.card_modeq_card_fixed_points (sylow p G)).trans (by rw this), end lemma not_dvd_card_sylow [hp : fact p.prime] [fintype (sylow p G)] : ¬ p ∣ card (sylow p G) := λ h, hp.1.ne_one (nat.dvd_one.mp ((nat.modeq_iff_dvd' zero_le_one).mp ((nat.modeq_zero_iff_dvd.mpr h).symm.trans (card_sylow_modeq_one p G)))) variables {p} {G} /-- Sylow subgroups are isomorphic -/ def sylow.equiv_smul (P : sylow p G) (g : G) : P ≃* (g • P : sylow p G) := equiv_smul (mul_aut.conj g) ↑P /-- Sylow subgroups are isomorphic -/ noncomputable def sylow.equiv [fact p.prime] [finite (sylow p G)] (P Q : sylow p G) : P ≃* Q := begin rw ← classical.some_spec (exists_smul_eq G P Q), exact P.equiv_smul (classical.some (exists_smul_eq G P Q)), end @[simp] lemma sylow.orbit_eq_top [fact p.prime] [finite (sylow p G)] (P : sylow p G) : orbit G P = ⊤ := top_le_iff.mp (λ Q hQ, exists_smul_eq G P Q) lemma sylow.stabilizer_eq_normalizer (P : sylow p G) : stabilizer G P = (P : subgroup G).normalizer := ext (λ g, sylow.smul_eq_iff_mem_normalizer) lemma sylow.conj_eq_normalizer_conj_of_mem_centralizer [fact p.prime] [finite (sylow p G)] (P : sylow p G) (x g : G) (hx : x ∈ (P : subgroup G).centralizer) (hy : g⁻¹ * x * g ∈ (P : subgroup G).centralizer) : ∃ n ∈ (P : subgroup G).normalizer, g⁻¹ * x * g = n⁻¹ * x * n := begin have h1 : ↑P ≤ (zpowers x).centralizer, { rwa [le_centralizer_iff, zpowers_le] }, have h2 : ↑(g • P) ≤ (zpowers x).centralizer, { rw [le_centralizer_iff, zpowers_le], rintros - ⟨z, hz, rfl⟩, specialize hy z hz, rwa [←mul_assoc, ←eq_mul_inv_iff_mul_eq, mul_assoc, mul_assoc, mul_assoc, ←mul_assoc, eq_inv_mul_iff_mul_eq, ←mul_assoc, ←mul_assoc] at hy }, obtain ⟨h, hh⟩ := exists_smul_eq (zpowers x).centralizer ((g • P).subtype h2) (P.subtype h1), simp_rw [sylow.smul_subtype, smul_def, smul_smul] at hh, refine ⟨h * g, sylow.smul_eq_iff_mem_normalizer.mp (sylow.subtype_injective hh), _⟩, rw [←mul_assoc, commute.right_comm (h.prop x (mem_zpowers x)), mul_inv_rev, inv_mul_cancel_right] end lemma sylow.conj_eq_normalizer_conj_of_mem [fact p.prime] [finite (sylow p G)] (P : sylow p G) [hP : (P : subgroup G).is_commutative] (x g : G) (hx : x ∈ P) (hy : g⁻¹ * x * g ∈ P) : ∃ n ∈ (P : subgroup G).normalizer, g⁻¹ * x * g = n⁻¹ * x * n := P.conj_eq_normalizer_conj_of_mem_centralizer x g (le_centralizer P hx) (le_centralizer P hy) /-- Sylow `p`-subgroups are in bijection with cosets of the normalizer of a Sylow `p`-subgroup -/ noncomputable def sylow.equiv_quotient_normalizer [fact p.prime] [fintype (sylow p G)] (P : sylow p G) : sylow p G ≃ G ⧸ (P : subgroup G).normalizer := calc sylow p G ≃ (⊤ : set (sylow p G)) : (equiv.set.univ (sylow p G)).symm ... ≃ orbit G P : by rw P.orbit_eq_top ... ≃ G ⧸ (stabilizer G P) : orbit_equiv_quotient_stabilizer G P ... ≃ G ⧸ (P : subgroup G).normalizer : by rw P.stabilizer_eq_normalizer noncomputable instance [fact p.prime] [fintype (sylow p G)] (P : sylow p G) : fintype (G ⧸ (P : subgroup G).normalizer) := of_equiv (sylow p G) P.equiv_quotient_normalizer lemma card_sylow_eq_card_quotient_normalizer [fact p.prime] [fintype (sylow p G)] (P : sylow p G) : card (sylow p G) = card (G ⧸ (P : subgroup G).normalizer) := card_congr P.equiv_quotient_normalizer lemma card_sylow_eq_index_normalizer [fact p.prime] [fintype (sylow p G)] (P : sylow p G) : card (sylow p G) = (P : subgroup G).normalizer.index := (card_sylow_eq_card_quotient_normalizer P).trans (P : subgroup G).normalizer.index_eq_card.symm lemma card_sylow_dvd_index [fact p.prime] [fintype (sylow p G)] (P : sylow p G) : card (sylow p G) ∣ (P : subgroup G).index := ((congr_arg _ (card_sylow_eq_index_normalizer P)).mp dvd_rfl).trans (index_dvd_of_le le_normalizer) lemma not_dvd_index_sylow' [hp : fact p.prime] (P : sylow p G) [(P : subgroup G).normal] [finite_index (P : subgroup G)] : ¬ p ∣ (P : subgroup G).index := begin intro h, haveI := (P : subgroup G).fintype_quotient_of_finite_index, rw index_eq_card at h, obtain ⟨x, hx⟩ := exists_prime_order_of_dvd_card p h, have h := is_p_group.of_card ((order_eq_card_zpowers.symm.trans hx).trans (pow_one p).symm), let Q := (zpowers x).comap (quotient_group.mk' (P : subgroup G)), have hQ : is_p_group p Q, { apply h.comap_of_ker_is_p_group, rw [quotient_group.ker_mk], exact P.2 }, replace hp := mt order_of_eq_one_iff.mpr (ne_of_eq_of_ne hx hp.1.ne_one), rw [←zpowers_eq_bot, ←ne, ←bot_lt_iff_ne_bot, ←comap_lt_comap_of_surjective (quotient_group.mk'_surjective _), monoid_hom.comap_bot, quotient_group.ker_mk] at hp, exact hp.ne' (P.3 hQ hp.le), end lemma not_dvd_index_sylow [hp : fact p.prime] [finite (sylow p G)] (P : sylow p G) (hP : relindex ↑P (P : subgroup G).normalizer ≠ 0) : ¬ p ∣ (P : subgroup G).index := begin casesI nonempty_fintype (sylow p G), rw [←relindex_mul_index le_normalizer, ←card_sylow_eq_index_normalizer], haveI : (P.subtype le_normalizer : subgroup (P : subgroup G).normalizer).normal := subgroup.normal_in_normalizer, haveI : finite_index ↑(P.subtype le_normalizer) := ⟨hP⟩, replace hP := not_dvd_index_sylow' (P.subtype le_normalizer), exact hp.1.not_dvd_mul hP (not_dvd_card_sylow p G), end /-- **Frattini's Argument**: If `N` is a normal subgroup of `G`, and if `P` is a Sylow `p`-subgroup of `N`, then `N_G(P) ⊔ N = G`. -/ lemma sylow.normalizer_sup_eq_top {p : ℕ} [fact p.prime] {N : subgroup G} [N.normal] [finite (sylow p N)] (P : sylow p N) : ((↑P : subgroup N).map N.subtype).normalizer ⊔ N = ⊤ := begin refine top_le_iff.mp (λ g hg, _), obtain ⟨n, hn⟩ := exists_smul_eq N ((mul_aut.conj_normal g : mul_aut N) • P) P, rw [←inv_mul_cancel_left ↑n g, sup_comm], apply mul_mem_sup (N.inv_mem n.2), rw [sylow.smul_def, ←mul_smul, ←mul_aut.conj_normal_coe, ←mul_aut.conj_normal.map_mul, sylow.ext_iff, sylow.pointwise_smul_def, pointwise_smul_def] at hn, refine λ x, (mem_map_iff_mem (show function.injective (mul_aut.conj (↑n * g)).to_monoid_hom, from (mul_aut.conj (↑n * g)).injective)).symm.trans _, rw [map_map, ←(congr_arg (map N.subtype) hn), map_map], refl, end /-- **Frattini's Argument**: If `N` is a normal subgroup of `G`, and if `P` is a Sylow `p`-subgroup of `N`, then `N_G(P) ⊔ N = G`. -/ lemma sylow.normalizer_sup_eq_top' {p : ℕ} [fact p.prime] {N : subgroup G} [N.normal] [finite (sylow p N)] (P : sylow p G) (hP : ↑P ≤ N) : (P : subgroup G).normalizer ⊔ N = ⊤ := by rw [← sylow.normalizer_sup_eq_top (P.subtype hP), P.coe_subtype, subgroup_of_map_subtype, inf_of_le_left hP] end infinite_sylow open equiv equiv.perm finset function list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G) (t : set (G ⧸ s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow open subgroup submonoid mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [finite ↥(H : set G)] {x : G} : (x : G ⧸ H) ∈ fixed_points H (G ⧸ H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : G ⧸ H}, y ∈ orbit H (x : G ⧸ H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), inv_mem_iff.1 (mem_normalizer_fintype (λ n (hn : n ∈ H), have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)), show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv} )), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, inv_mem_iff.1 $ (hx _).2 $ (mul_mem_cancel_left (inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ /-- The fixed points of the action of `H` on its cosets correspond to `normalizer H / H`. -/ def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [finite (H : set G)] : mul_action.fixed_points H (G ⧸ H) ≃ normalizer H ⧸ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := @subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _) (λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ ‹_› _).symm) (by { intros, rw setoid_has_equiv, simp only [left_rel_apply], refl }) /-- If `H` is a `p`-subgroup of `G`, then the index of `H` inside its normalizer is congruent mod `p` to the index of `H`. -/ lemma card_quotient_normalizer_modeq_card_quotient [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime] {H : subgroup G} (hH : fintype.card H = p ^ n) : card (normalizer H ⧸ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) ≡ card (G ⧸ H) [MOD p] := begin rw [← fintype.card_congr (fixed_points_mul_left_cosets_equiv_quotient H)], exact ((is_p_group.of_card hH).card_modeq_card_fixed_points _).symm end /-- If `H` is a subgroup of `G` of cardinality `p ^ n`, then the cardinality of the normalizer of `H` is congruent mod `p ^ (n + 1)` to the cardinality of `G`. -/ lemma card_normalizer_modeq_card [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime] {H : subgroup G} (hH : fintype.card H = p ^ n) : card (normalizer H) ≡ card G [MOD p ^ (n + 1)] := have H.subgroup_of (normalizer H) ≃ H, from (subgroup_of_equiv_of_le le_normalizer).to_equiv, begin rw [card_eq_card_quotient_mul_card_subgroup H, card_eq_card_quotient_mul_card_subgroup (H.subgroup_of (normalizer H)), fintype.card_congr this, hH, pow_succ], exact (card_quotient_normalizer_modeq_card_quotient hH).mul_right' _ end /-- If `H` is a `p`-subgroup but not a Sylow `p`-subgroup, then `p` divides the index of `H` inside its normalizer. -/ lemma prime_dvd_card_quotient_normalizer [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime] (hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) : p ∣ card (normalizer H ⧸ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) := let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (G ⧸ H) = s * p := (mul_left_inj' (show card H ≠ 0, from fintype.card_ne_zero)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH, hs, pow_succ', mul_assoc, mul_comm p]), have hm : s * p % p = card (normalizer H ⧸ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p := hcard ▸ (card_quotient_normalizer_modeq_card_quotient hH).symm, nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm) /-- If `H` is a `p`-subgroup but not a Sylow `p`-subgroup of cardinality `p ^ n`, then `p ^ (n + 1)` divides the cardinality of the normalizer of `H`. -/ lemma prime_pow_dvd_card_normalizer [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime] (hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) : p ^ (n + 1) ∣ card (normalizer H) := nat.modeq_zero_iff_dvd.1 ((card_normalizer_modeq_card hH).trans hdvd.modeq_zero_nat) /-- If `H` is a subgroup of `G` of cardinality `p ^ n`, then `H` is contained in a subgroup of cardinality `p ^ (n + 1)` if `p ^ (n + 1)` divides the cardinality of `G` -/ theorem exists_subgroup_card_pow_succ [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime] (hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) : ∃ K : subgroup G, fintype.card K = p ^ (n + 1) ∧ H ≤ K := let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (G ⧸ H) = s * p := (mul_left_inj' (show card H ≠ 0, from fintype.card_ne_zero)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH, hs, pow_succ', mul_assoc, mul_comm p]), have hm : s * p % p = card (normalizer H ⧸ (H.subgroup_of H.normalizer)) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ (is_p_group.of_card hH).card_modeq_card_fixed_points _, have hm' : p ∣ card (normalizer H ⧸ (H.subgroup_of H.normalizer)) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in have hequiv : H ≃ (H.subgroup_of H.normalizer) := (subgroup_of_equiv_of_le le_normalizer).symm.to_equiv, ⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (mk' (H.subgroup_of H.normalizer)) (zpowers x)), begin show card ↥(map H.normalizer.subtype (comap (mk' (H.subgroup_of H.normalizer)) (subgroup.zpowers x))) = p ^ (n + 1), suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (H.subgroup_of H.normalizer)) (zpowers x)) : set (↥(H.normalizer)))) = p^(n+1), { convert this using 2 }, rw [set.card_image_of_injective (subgroup.comap (mk' (H.subgroup_of H.normalizer)) (zpowers x) : set (H.normalizer)) subtype.val_injective, pow_succ', ← hH, fintype.card_congr hequiv, ← hx, order_eq_card_zpowers, ← fintype.card_prod], exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _) end, begin assume y hy, simp only [exists_prop, subgroup.coe_subtype, mk'_apply, subgroup.mem_map, subgroup.mem_comap], refine ⟨⟨y, le_normalizer hy⟩, ⟨0, _⟩, rfl⟩, rw [zpow_zero, eq_comm, quotient_group.eq_one_iff], simpa using hy end⟩ /-- If `H` is a subgroup of `G` of cardinality `p ^ n`, then `H` is contained in a subgroup of cardinality `p ^ m` if `n ≤ m` and `p ^ m` divides the cardinality of `G` -/ theorem exists_subgroup_card_pow_prime_le [fintype G] (p : ℕ) : ∀ {n m : ℕ} [hp : fact p.prime] (hdvd : p ^ m ∣ card G) (H : subgroup G) (hH : card H = p ^ n) (hnm : n ≤ m), ∃ K : subgroup G, card K = p ^ m ∧ H ≤ K | n m := λ hp hdvd H hH hnm, (lt_or_eq_of_le hnm).elim (λ hnm : n < m, have h0m : 0 < m, from (lt_of_le_of_lt n.zero_le hnm), have wf : m - 1 < m, from nat.sub_lt h0m zero_lt_one, have hnm1 : n ≤ m - 1, from le_tsub_of_add_le_right hnm, let ⟨K, hK⟩ := @exists_subgroup_card_pow_prime_le n (m - 1) hp (nat.pow_dvd_of_le_of_pow_dvd tsub_le_self hdvd) H hH hnm1 in have hdvd' : p ^ ((m - 1) + 1) ∣ card G, by rwa [tsub_add_cancel_of_le h0m.nat_succ_le], let ⟨K', hK'⟩ := @exists_subgroup_card_pow_succ _ _ _ _ _ hp hdvd' K hK.1 in ⟨K', by rw [hK'.1, tsub_add_cancel_of_le h0m.nat_succ_le], le_trans hK.2 hK'.2⟩) (λ hnm : n = m, ⟨H, by simp [hH, hnm]⟩) /-- A generalisation of **Sylow's first theorem**. If `p ^ n` divides the cardinality of `G`, then there is a subgroup of cardinality `p ^ n` -/ theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) {n : ℕ} [fact p.prime] (hdvd : p ^ n ∣ card G) : ∃ K : subgroup G, fintype.card K = p ^ n := let ⟨K, hK⟩ := exists_subgroup_card_pow_prime_le p hdvd ⊥ (by simp) n.zero_le in ⟨K, hK.1⟩ lemma pow_dvd_card_of_pow_dvd_card [fintype G] {p n : ℕ} [hp : fact p.prime] (P : sylow p G) (hdvd : p ^ n ∣ card G) : p ^ n ∣ card P := (hp.1.coprime_pow_of_not_dvd (not_dvd_index_sylow P index_ne_zero_of_finite)).symm.dvd_of_dvd_mul_left ((index_mul_card P.1).symm ▸ hdvd) lemma dvd_card_of_dvd_card [fintype G] {p : ℕ} [fact p.prime] (P : sylow p G) (hdvd : p ∣ card G) : p ∣ card P := begin rw ← pow_one p at hdvd, have key := P.pow_dvd_card_of_pow_dvd_card hdvd, rwa pow_one at key, end /-- Sylow subgroups are Hall subgroups. -/ lemma card_coprime_index [fintype G] {p : ℕ} [hp : fact p.prime] (P : sylow p G) : (card P).coprime (index (P : subgroup G)) := let ⟨n, hn⟩ := is_p_group.iff_card.mp P.2 in hn.symm ▸ (hp.1.coprime_pow_of_not_dvd (not_dvd_index_sylow P index_ne_zero_of_finite)).symm lemma ne_bot_of_dvd_card [fintype G] {p : ℕ} [hp : fact p.prime] (P : sylow p G) (hdvd : p ∣ card G) : (P : subgroup G) ≠ ⊥ := begin refine λ h, hp.out.not_dvd_one _, have key : p ∣ card (P : subgroup G) := P.dvd_card_of_dvd_card hdvd, rwa [h, card_bot] at key, end /-- The cardinality of a Sylow group is `p ^ n` where `n` is the multiplicity of `p` in the group order. -/ lemma card_eq_multiplicity [fintype G] {p : ℕ} [hp : fact p.prime] (P : sylow p G) : card P = p ^ nat.factorization (card G) p := begin obtain ⟨n, heq : card P = _⟩ := is_p_group.iff_card.mp (P.is_p_group'), refine nat.dvd_antisymm _ (P.pow_dvd_card_of_pow_dvd_card (nat.ord_proj_dvd _ p)), rw [heq, ←hp.out.pow_dvd_iff_dvd_ord_proj (show card G ≠ 0, from card_ne_zero), ←heq], exact P.1.card_subgroup_dvd_card, end lemma subsingleton_of_normal {p : ℕ} [fact p.prime] [finite (sylow p G)] (P : sylow p G) (h : (P : subgroup G).normal) : subsingleton (sylow p G) := begin apply subsingleton.intro, intros Q R, obtain ⟨x, h1⟩ := exists_smul_eq G P Q, obtain ⟨x, h2⟩ := exists_smul_eq G P R, rw sylow.smul_eq_of_normal at h1 h2, rw [← h1, ← h2], end section pointwise open_locale pointwise lemma characteristic_of_normal {p : ℕ} [fact p.prime] [finite (sylow p G)] (P : sylow p G) (h : (P : subgroup G).normal) : (P : subgroup G).characteristic := begin haveI := sylow.subsingleton_of_normal P h, rw characteristic_iff_map_eq, intros Φ, show (Φ • P).to_subgroup = P.to_subgroup, congr, end end pointwise lemma normal_of_normalizer_normal {p : ℕ} [fact p.prime] [finite (sylow p G)] (P : sylow p G) (hn : (↑P : subgroup G).normalizer.normal) : (↑P : subgroup G).normal := by rw [← normalizer_eq_top, ← normalizer_sup_eq_top' P le_normalizer, sup_idem] @[simp] lemma normalizer_normalizer {p : ℕ} [fact p.prime] [finite (sylow p G)] (P : sylow p G) : (↑P : subgroup G).normalizer.normalizer = (↑P : subgroup G).normalizer := begin have := normal_of_normalizer_normal (P.subtype (le_normalizer.trans le_normalizer)), simp_rw [←normalizer_eq_top, coe_subtype, ← subgroup_of_normalizer_eq le_normalizer, ← subgroup_of_normalizer_eq le_rfl, subgroup_of_self] at this, rw [←subtype_range (P : subgroup G).normalizer.normalizer, monoid_hom.range_eq_map, ←this rfl], exact map_comap_eq_self (le_normalizer.trans (ge_of_eq (subtype_range _))), end lemma normal_of_all_max_subgroups_normal [finite G] (hnc : ∀ (H : subgroup G), is_coatom H → H.normal) {p : ℕ} [fact p.prime] [finite (sylow p G)] (P : sylow p G) : (↑P : subgroup G).normal := normalizer_eq_top.mp begin rcases eq_top_or_exists_le_coatom ((↑P : subgroup G).normalizer) with heq | ⟨K, hK, hNK⟩, { exact heq }, { haveI := hnc _ hK, have hPK : ↑P ≤ K := le_trans le_normalizer hNK, refine (hK.1 _).elim, rw [← sup_of_le_right hNK, P.normalizer_sup_eq_top' hPK] }, end lemma normal_of_normalizer_condition (hnc : normalizer_condition G) {p : ℕ} [fact p.prime] [finite (sylow p G)] (P : sylow p G) : (↑P : subgroup G).normal := normalizer_eq_top.mp $ normalizer_condition_iff_only_full_group_self_normalizing.mp hnc _ $ normalizer_normalizer _ open_locale big_operators /-- If all its sylow groups are normal, then a finite group is isomorphic to the direct product of these sylow groups. -/ noncomputable def direct_product_of_normal [fintype G] (hn : ∀ {p : ℕ} [fact p.prime] (P : sylow p G), (↑P : subgroup G).normal) : (Π p : (card G).factorization.support, Π P : sylow p G, (↑P : subgroup G)) ≃* G := begin set ps := (fintype.card G).factorization.support, -- “The” sylow group for p let P : Π p, sylow p G := default, have hcomm : pairwise (λ (p₁ p₂ : ps), ∀ (x y : G), x ∈ P p₁ → y ∈ P p₂ → commute x y), { rintros ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ hne, haveI hp₁' := fact.mk (nat.prime_of_mem_factorization hp₁), haveI hp₂' := fact.mk (nat.prime_of_mem_factorization hp₂), have hne' : p₁ ≠ p₂, by simpa using hne, apply subgroup.commute_of_normal_of_disjoint _ _ (hn (P p₁)) (hn (P p₂)), apply is_p_group.disjoint_of_ne p₁ p₂ hne' _ _ (P p₁).is_p_group' (P p₂).is_p_group', }, refine mul_equiv.trans _ _, -- There is only one sylow group for each p, so the inner product is trivial show (Π p : ps, Π P : sylow p G, P) ≃* (Π p : ps, P p), { -- here we need to help the elaborator with an explicit instantiation apply @mul_equiv.Pi_congr_right ps (λ p, (Π P : sylow p G, P)) (λ p, P p) _ _ , rintro ⟨p, hp⟩, haveI hp' := fact.mk (nat.prime_of_mem_factorization hp), haveI := subsingleton_of_normal _ (hn (P p)), change (Π (P : sylow p G), P) ≃* P p, exact mul_equiv.Pi_subsingleton _ _, }, show (Π p : ps, P p) ≃* G, apply mul_equiv.of_bijective (subgroup.noncomm_pi_coprod hcomm), apply (bijective_iff_injective_and_card _).mpr, split, show injective _, { apply subgroup.injective_noncomm_pi_coprod_of_independent, apply independent_of_coprime_order hcomm, rintros ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ hne, haveI hp₁' := fact.mk (nat.prime_of_mem_factorization hp₁), haveI hp₂' := fact.mk (nat.prime_of_mem_factorization hp₂), have hne' : p₁ ≠ p₂, by simpa using hne, apply is_p_group.coprime_card_of_ne p₁ p₂ hne' _ _ (P p₁).is_p_group' (P p₂).is_p_group', }, show card (Π (p : ps), P p) = card G, { calc card (Π (p : ps), P p) = ∏ (p : ps), card ↥(P p) : fintype.card_pi ... = ∏ (p : ps), p.1 ^ (card G).factorization p.1 : begin congr' 1 with ⟨p, hp⟩, exact @card_eq_multiplicity _ _ _ p ⟨nat.prime_of_mem_factorization hp⟩ (P p) end ... = ∏ p in ps, p ^ (card G).factorization p : finset.prod_finset_coe (λ p, p ^ (card G).factorization p) _ ... = (card G).factorization.prod pow : rfl ... = card G : nat.factorization_prod_pow_eq_self fintype.card_ne_zero } end end sylow